Set a String as Enum

There are many instances where, in an Enum we need a string literal. However you can only enter a single word (with no space) against an integer (+ve/-ve). That’s where we use the description attribute.
Look at the Enum declaration below:-


public enum States
{
	[System.ComponentModel.Description("New Delhi")]
	NewDelhi = 1,
	[Description("Uttar Pradesh")]
	UttarPradesh = 2
	[Description("West Bengal")]
	WestBengal = -1,
}

Normally this is how we bind the Enum to a DropDownList

DropDownList1.DataSource = Enum.GetNames(typeof(States));
DropDownList1.DataBind();

This is what we’ll get the output for our Enum States

To get the description value of the Enum, we’ll use the following method


public static string GetEnumDescription(Enum value) 
{ 
	System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString()); 
	if (fi != null) 
	{ 
		System.ComponentModel.DescriptionAttribute[] attributes = 	(System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); 
		if (attributes != null && attributes.Length > 0) 
			return attributes[0].Description; else return value.ToString();
	}
	return value.ToString(); 
}

This is how we’ll do to bind the Enum description to a DropDownList


foreach (States value in Enum.GetValues(typeof(States)))
{
	DropDownList1.Items.Add(new ListItem(GetEnumDescription(value), value.ToString()));
}
DropDownList1.DataBind();

Final Output:

 

 

Happy Coding …

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s