jQuery and ASP.NET

April 17, 2009

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


Bookmark this link on del.icio.us (saved by 0 users)

Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter
Others Also Read..

comments

3 Responses to "How to Bind an ASP.NET DropDownList to an Enumeration with two lines of code"
  1. Eric said...
    September 10, 2009 7:26 PM

    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?

  2. Suprotim Agarwal said...
    September 10, 2009 11:42 PM

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

  3. Suprotim Agarwal said...
    September 12, 2009 5:56 AM

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

 

Copyright 2010 All Rights Reserved DevCurry.com by Suprotim Agarwal