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 output that list as a table with property name as a 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 titles, like
First Name | Last Name | Age
Question: How to define column titles for each property of the Person class? Should I use custom attributes on properties or is there any better way?
This is an approach i'd do in your case. It's quite simple and self explaining:
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 linked extensionmethod uses Reflection anyway, you can just modify the Header-Formatting loop like above.
The Usage of 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With