Skip to content

In ASP.NET, How To Create a DropDownList from an ENUM

Updated: at 06:34 PM

So, you have an enum defined as follows:

public enum CompanyAddressType
    {
        Unknown = 0,
        Primary = 1,
        Warehouse = 2,
        Distribution_Center = 3,
        Cross_Dock = 4
    }

You want to iterate through the list and put the data into an asp.net dropdownlist.

Here is the simple code:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string[] names = Enum.GetNames(typeof(CompanyAddressType));
                var values = (CompanyAddressType[])Enum.GetValues(typeof(CompanyAddressType));
                for (int i = 0; i < names.Length; i++)
                {
                    DropDownListCompanyAddressType.Items.Add(new ListItem(names[i], values.ToString()));
                }
            }
        }

 

There are probably easier ways to do it, but this works.

and…

image

HTH’s.