Defining custom headers by object properties

I have a list of objects of some class defined as

public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } } var personList = new List<Person>(); personList.Add(new Person { FirstName = "Alex", LastName = "Friedman", Age = 27 }); 

and display this list as a table with the property name as the column header ( full source code )

 var propertyArray = typeof(T).GetProperties(); foreach (var prop in propertyArray) result.AppendFormat("<th>{0}</th>", prop.Name); 

and get

 FirstName | LastName | Age ---------------------------------- Alex Friedman 27 

I want to have some custom names like

 First Name | Last Name | Age 

Question: How to define column headers for each property of the Person class? Should I use custom attributes for properties or is there a better way?

+5
source share
1 answer

This is the approach I would take in your case. This is pretty simple and self-evident:

  var propertyArray = typeof(T).GetProperties(); foreach (var prop in propertyArray) { foreach (var customAttr in prop.GetCustomAttributes(true)) { if (customAttr is DisplayNameAttribute) {//<--- DisplayName if (String.IsNullOrEmpty(headerStyle)) { result.AppendFormat("<th>{0}</th>", (customAttr as DisplayNameAttribute).DisplayName); } else { result.AppendFormat("<th class=\"{0}\">{1}</th>", headerStyle, (customAttr as DisplayNameAttribute).DisplayName); } break; } } } 

Since the associated extension method uses Reflection anyway, you can simply change the header-formatting loop as described above.

Using the attribute will look like this:

 public class Person { [DisplayName("First Name")] public string FirstName { get; set; } [DisplayName("Last Name")] public string LastName { get; set; } public int Age { get; set; } } 
+3
source

All Articles