1 Replies - 2429 Views - Last Post: 25 October 2014 - 03:25 PM Rate Topic: -----

#1 JasonEnsor   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 25-October 14

Populate ASP Dropdown list with enum Description and Values

Posted 25 October 2014 - 03:17 PM

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
            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 then I can get the Enum description
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
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.

Is This A Good Question/Topic? 0
  • +

Replies To: Populate ASP Dropdown list with enum Description and Values

#2 andrewsw   User is offline

  • head thrashing
  • member icon

Reputation: 6630
  • View blog
  • Posts: 27,105
  • Joined: 12-December 12

Re: Populate ASP Dropdown list with enum Description and Values

Posted 25 October 2014 - 03:25 PM

Moved to the ASP.NET forum.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1