65.9K
CodeProject is changing. Read more.
Home

Define Display Labels as Attributes in Business Entity Class in C#

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (4 votes)

Nov 25, 2015

CPOL
viewsIcon

6032

A way to define display names for class members in BE class that can be used as table headers.

Introduction

Assume that in your Business Entity (BE) class, you have certain properties to match with table fields. I want to expose descriptive name for each of these properties. For example, to show it as column header in grid.

For example, there is a property called FirstName. I want to expose its descriptive name as First Name.

Background

You must be familiar with Object oriented concepts in order to understand this tip.

Using the Code

In BE class, define the descriptive name for the property.

[DisplayName("First Name"), Description("First Name of the Member")]
public string FirstName
{
    get { return _firstName; }
    set { _firstName = value; }
}

You can read these details of each property as below:

PropertyDescriptorCollection propertiesCol = TypeDescriptor.GetProperties(objectBE);

PropertyDescriptor property;

for (int i = 0; i < propertiesCol.Count; i++)
{
    property = TypeDescriptor.GetProperties(objectBE)[i];

    /*
    // Access the Property Name, Display Name and Description as follows
    property.Name          // Returns "FirstName"
    property.DisplayName   // Returns "First Name"
    property.Description   // Returns "First Name of the Member"
    */
}
// *here objectBE is the object instance of BE class.

Points of Interest

This is pretty useful when using ASP.NET WebForms applications. However, this may not be required if you are using ASP.NET MVC application.

History

  • 2015-11-25 - Initial version