5 Sep 2007

How to bind an enum to a DropDownList

Supposing to have the follow enumerator:

public enum UserRole
{
    Guest = 0,
    StandardUser = 1,
    Administrator = 2
}

And a Web Form with a DropDownList (named "ddlUserRole"):

<form runat="server">
    <asp:DropDownList
        ID="ddlUserRole"
        runat="server"
        OnSelectedIndexChanged="ddlUserRole_SelectedIndexChanged"
        AutoPostBack="true" />
</form>

We can simply bind the enumerator to the DropDownList with a couple of line of code:

protected void Page_Load(object sender, EventArgs e)
{
    comboBox1.DataSource = Enum.GetValues(typeof(UserRole));
    comboBox1.DataBind();
}

private void ComboBox1ValueChanged(object sender, EventArgs e)
{
    // retrieve selected user role from the DropDownList:
    UserRole r = (UserRole)this.comboBox1.SelectedValue;
}

HTH

Categories: ASP.NET | Code box

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

trackback

DotNetKicks.com

September 5 2007 16:17

Trackback from DotNetKicks.com

How to bind an enum to a DropDownList

Add comment


(Will show your Gravatar icon)  

  Country flag





Live preview

Gravatar

May 16 2008 14:55