How to Bind an ASP.NET DropDownList to an Enumeration with two lines of code

I have seen users writing number of lines of code to do a simple thing as binding an Enumeration to an ASP.NET DropDownList or ListBox. Here's how to do this with just two lines of code

<asp:DropDownList ID="DropDownList1" runat="server">
</
asp:DropDownList>

<
asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>

C#

enum Speed
{
Low = 1,
Medium = 2,
High = 3
}
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.DataSource = Enum.GetValues(typeof(Speed));
DropDownList1.DataBind();

ListBox1.DataSource = Enum.GetValues(typeof(Speed));
ListBox1.DataBind();
}

VB.NET

Friend Enum Speed
Low = 1
Medium = 2
High = 3
End Enum

Protected Sub
Page_Load(ByVal sender As Object, ByVal e As EventArgs)
DropDownList1.DataSource = System.Enum.GetValues(GetType(Speed))
DropDownList1.DataBind()

ListBox1.DataSource = System.Enum.GetValues(GetType(Speed))
ListBox1.DataBind()
End Sub

OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

4 comments:

Eric said...

Thanks for the tip, but how would you do it if you wanted the value of the dropdown to be the value of the enumerator, and the text of the dropdown to be the name of the enumerator?

Suprotim Agarwal said...

Eric: Nice question. I will do a post with the solution in a couple of hours from now.

Suprotim Agarwal said...

http://www.devcurry.com/2009/09/how-to-bind-enum-name-and-value-to.html

Maksim said...

Both ASp.net and Winforms tutorial:

In this little tutorial i will try to expline how you can use Enum and fill your Combobox with items from that Enum and make the some thing but in reverse. (Select the item from combobox, check if it belong to your Enum and get proper Enum value)

http://www.docstorus.com/viewer.aspx?code=833d27e2-5e3b-4ec0-b950-02c8fc2ec572&title=How%20to%20use%20Enum%20with%20Combobox%20in%20C#%20WinForms%20and%20Asp.Net