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:
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:
A sample project can be found here.