Wednesday, 14 September 2011

Binding Enum list to a dropdown in asp.net

Let's say the dropdown has an id="ddlGender" and the Enum as  Enum Gender { male,female} then to bind the values to the ddlgender the technique is :

Solution:1 :

ddlGender.datasource=Enum.GetTypes(typeOf(Gender));
ddlGender.DataBind( );


Solution:2 :  
In this solution you can bind the value as well as  name.

foreach (Gender gender in Enum.GetValues(typeof(Gender)))  
{  
ListItem item = new ListItem(Enum.GetName(typeof(Gender),  
                                                                     gender ), ((int)gender).ToString("D"));  
ddlGender.Items.Add(item); 

No comments:

Post a Comment