Home > ASP.Net > Bind DropdownList to Enum

Bind DropdownList to Enum


Hi

try this example:

public enum test
    {
        Male=1,
        Female=2
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //Gets your enum names and adds it to a string array 
            string[] enumNames = Enum.GetNames(typeof(test));

            int[] enumValues = (int[])System.Enum.GetValues(typeof(test));

            //--- first way -----------
            //Creates an ArrayList 
            //ArrayList enumList = new ArrayList();

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

            //    enumList.Insert(i , enumNames[i]); 
            //} 
            //DropDownList1.DataSource=enumList;
            //DropDownList1.DataBind();

            //----- another way -------------

            for (int i = 0; i <= enumNames.Length - 1; i++)
            {
                ListItem x = new ListItem(enumNames[i].ToString(), enumValues[i].ToString());
                DropDownList1.Items.Add(x);
            }
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Write(DropDownList1.SelectedValue.ToString());
    }

and in HTML mode :

<asp: DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem Value="-1">Select</asp:ListItem>
</asp: DropDownList>

Good Luck

Advertisements
Categories: ASP.Net Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: