Jul 22 2008

Binding a DropDownList in ASP.NET to an Enumeration

Category: ASP.NET 2.0 | ASP.NET 3.5Bil@l @ 20:19

Here is a snippet code that helps you bind the items contained in an enumeration into a DropDownList in ASP.NET.

To start with, let us define an enumeration as follows:

    public enum Directions
    {
        North = 1,
        East,
        South,
        West
    }

The above is a C# definition for an enumeration called Directions that has 4 main values.

Now, to bind the above enumeration values to a DropDownList we need the following:

        if (!Page.IsPostBack)
        {
            // Loop through the Directions' items
            // and add them item by item into the DropDownList
            ListItem item = null;
            string[] directionNames = Enum.GetNames(typeof(Directions));

            for (int x = 0; x < directionNames.Length - 1; x++)
            {
                // Create the item
                item = new ListItem(
                    directionNames[x],
                    ((Int32)Enum.Parse(typeof(Directions), directionNames[x])).ToString());

                // Add the item to the list of items
                // inside the DropDownList
                this.ddlDirections.Items.Add(item);
            }
        }

You notice in the code above, to retrieve the names of all the items in the enumeration, you make use of the Enum.GetNames() method. Once you have all the items in the enumeration as String values, you loop through the list of values of the enumeration.

For each value, you create a new ListItem class passing to it the:

  1. Text to be displayed which is in this case the name of an item inside the enumeration
  2. Value to be stored in the value of the ListItem in this case the Integer value of an item in the enumeration which is retrieved by parsing the item name into a valid Directions enumeration, then casting to the type of the Enumeration, which is by default int.

 Once the ListItem is created, simply add it to the collection of Items of the DropDownList placed in the HTML markup.

The DropDownList is defined as follows:

    <asp:DropDownList ID="ddlDirections" runat="server" AppendDataBoundItems="true" >
        <asp:ListItem Text=" .. Choose a Direction .." Value="-1" Selected="True"/>
    </asp:DropDownList>

This is all what you need to do to bind a DropDownList to an enumeration!

Hope it helps,
Regards

Tags: ,

Comments are closed