Click here to Skip to main content
16,017,261 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
3.50/5 (4 votes)
25 Nov 2015CPOL 5.9K   5  
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.

C#
[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:

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --