Home | Blog | Screencasts | Projects
# Tuesday, September 23, 2008

I recently had a project where I needed to bind some business objects to a SPGridView in a web part, which on its own is trivial, but I also needed to create the columns for the SPGridView on the fly, since a number of business objects could be rendered in this control.

The main problem was the naming of these columns, if I just bound them directly to the Grid, I would get the ugly naming of my properties (I say it’s ugly, it’s actually pretty awesome if your a developer, but those pesky end users like pretty names).

The sample grid looks like this by default:

 

grid-without

 

So what I came up with isn’t exactly new or innovative, I created a custom attribute called Alias:

 

    public class AliasAttribute : System.Attribute
    {
        protected string[] aliasName;

        public AliasAttribute(params string[] alias)
        {
            this.aliasName = alias;
        }

        public string[] Alias
        {
            get { return aliasName; }
            set { aliasName = value; }
        }
    }

 

This attribute gets applied to each property on your business object with a pretty name:

 

        [Alias("Internet URL")]
        public string InternetAddress
        {
            get { return internetAddress; }
            set { internetAddress = value; }
        }

 

Now the code that performs the binding looks for properties with a custom attribute and pulls out the alias as the HeaderText:

BoundField newBoundField = new BoundField();
newBoundField.HeaderText = Helpers.GetPropertyAlias(field.Trim());
newBoundField.DataField = field.Trim();
grid.Columns.Add(newBoundField);
public static string GetPropertyAlias(string propertyName)
{
    //Change the next line for your business object ..
    PropertyInfo[] propInfos = typeof(BusinessObject).GetProperties();

    foreach (PropertyInfo propInfo in propInfos)
    {
        if (propInfo.Name.ToUpper().Equals(propertyName.ToUpper()))
        {
            object[] attribs = propInfo.GetCustomAttributes(typeof(AliasAttribute), true);
            foreach (object attrib in attribs)
            {
                if (attrib is AliasAttribute)
                {
                    AliasAttribute alias = (AliasAttribute)attrib;
                    //return the alias
                    return alias.Alias[0];
                }
            }
        }
    }

    //if we don't find the custom attribute, just return the same value we passed in
    return propertyName;
}

 

The end result is a nice pretty grid:

 

Grid-With

 

A sample project can be found here.

Tuesday, September 23, 2008 10:20:00 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
code | MOSS | Sharepoint
Statistics
Total Posts: 119
This Year: 104
This Month: 11
This Week: 1
Comments: 15