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

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.

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he's a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. I still do ASP.NET for building fast interfaces. There is still no way I can crank out ExtJS quickly

  2. I thought you didn’t do ASP.NET anymore?? When/why do you need ASP.NET form controls? 🙂

Follow

Get every new post delivered to your Inbox

Join other followers: