Monday, October 29, 2012

Bind Enum constants to Dropdown control in ASP.NET


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/



The following extension method is used to bind enumerated constants to any ListControls (DropdownList, ListBox etc) in ASP.NET:


using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.UI.WebControls;

public static class ListControlExtension{
    public static void BindEnum(this ListControl listControl,
                                Type enumType) 
        {
       string caption;
       string value;
       object[] objArray;

       foreach (var enumValue in Enum.GetValues(enumType))    
               {
           // Get the numeric value of enum member
                value ((int)enumValue).ToString(); 

           // Get the DisplayAttribute object of enum member
           objArray = enumType.GetField(enumValue.ToString())
                            .GetCustomAttributes(
typeof(DisplayAttribute),
                            false);            

         // If Display attribute is not specified
          if (objArray.Count() == 0) 
          {
             // just take the enum member text         
             caption = enumValue.ToString(); 

          }
          else         
          {
             // take the DisplayAttribute name of enum member
             caption = ((
DisplayAttribute)objArray.Single()).GetName();            
      }

          listControl.Items.Add(new ListItem(caption, value));
                      objArray =  null;
            }
       }
}

For example, the following Enum constant,

public enum EmploymentStatus{
    Active,
    Resigned,
    Retired,
    [
Display(Name = "Unpaid Long Leave")]
    LongLeave,
         [Display(Name = "Paid Long Leave")] 
    Sabbatical
}


can be bound to a Dropdown control as
     
        ddlDefectStatus.BindEnum(typeof(EmploymentStatus));


Note that the extension method binds the Display attribute's Name property value (if it is provided) to the list control.

The Display attribute is helpful when you want to show a  text other than the enum text. For example, 'Unpaid Long Leave' and 'Paid Long Leave' are shown in the list control instead of LongLeave and Sabbatical respectively.



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

No comments:

Post a Comment