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 …

Change DropDownList SelectedIndex on Gridview SelectedIndexChanging Event

Tip

Well, here I would like to set the SelectedIndex of a DropDownList based on a Column’s Text Value from the GridView’s SelectedIndexChanging event. I guess, this can be achieved by many ways however, what I am trying to show here is to do the same in just 1 line.


ddlDropDown.SelectedIndex = ddlDropDown.Items.
								IndexOf(ddlDropDown.Items.
									FindByText(((Label)gvGridView.Rows[e.NewSelectedIndex].
										FindControl("lblLabel")).Text));

Happy Coding …