Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Populate ASP Dropdown list with enum Description and Values

Status
Not open for further replies.

JasonEnsor

Programmer
Sep 14, 2010
193
0
0
GB
Hi Guys,

I am trying to create a dropdown list in asp.net using an enum as the data for the list. what I am wanting is to have the description set as the dropdownlist text and the value of the enum set as the value for the dropdown list.

So far I have found two snippets of code the first gets the enum names and values

Code:
Array itemValues = System.Enum.GetValues(typeof(CountryList));
Array itemNames = System.Enum.GetNames(typeof(CountryList));

for (int i = 0; i <= itemNames.Length - 1; i++)
{

    var value = (int)(CountryList)Enum.Parse(typeof(CountryList), itemValues.GetValue(i).ToString(), true);

    ListItem item = new ListItem(itemNames.GetValue(i).ToString(), value.ToString());

    ddlCultureList.Items.Add(item);

}

and I can get the Enum description using the following
Code:
protected void Page_Load(object sender, EventArgs e)
        {
            //Get attributes from the enum
            var items =
               typeof(CountryList).GetEnumNames()
                .Select(x => typeof(CountryList).GetMember(x)[0].GetCustomAttributes(
                   typeof(System.ComponentModel.DescriptionAttribute), false))
                .SelectMany(x =>
                   x.Select(y => new ListItem(((System.ComponentModel.DescriptionAttribute)y).Description)));

            //Add items to ddl
            foreach (var item in items)
                ddlCultureList.Items.Add(item);
        }

I just can't figure out how to get both together so the enum description (United Kingdom) populates in the drop down list text and GB is set as the value as I want to use the value for another part of my application.

An example of the Enum I am using is
Code:
public enum CountryList
    {
        [System.ComponentModel.Description("United States")]
        US,
        [System.ComponentModel.Description("United Kingdom")]
        GB
    }

any help and tips would be appreciated. I was originally going to use CultureInfo and RegionInfo to get the list of Countries, however it brings back a load of countries that my company does not do business with so the enum was a better option. Plus I feel I could use this for future projects.

Many Thanks

J.

Regards

J.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top