I had recently written a blog post on How to Bind an ASP.NET DropDownList to an Enumeration with two lines of code. A devcurry reader mailed back asking if it was possible to bind an Enumeration Name and Value to the DropDownList. Here’s how:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
C#
enum Speed
{
Low = 1,
Medium = 2,
High = 3
}
protected void Page_Load(object sender, EventArgs e)
{
Hashtable htSpeed = BindEnum(typeof(Speed));
DropDownList1.DataSource = htSpeed;
DropDownList1.DataValueField = "key";
DropDownList1.DataTextField = "value";
DropDownList1.DataBind();
}
protected Hashtable BindEnum(Type speedEnum)
{
string[] enumNm = Enum.GetNames(speedEnum);
int[] enumVal = (int[])Enum.GetValues(speedEnum);
Hashtable htSpeed = new Hashtable();
for (int cnt = 0; cnt < enumVal.Length; cnt++)
{
htSpeed.Add(enumVal.GetValue(cnt), enumNm[cnt]);
}
return htSpeed;
}
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)
Dim htSpeed As Hashtable = BindEnum(GetType(Speed))
DropDownList1.DataSource = htSpeed
DropDownList1.DataValueField = "key"
DropDownList1.DataTextField = "value"
DropDownList1.DataBind()
End Sub
Protected Function BindEnum(ByVal speedEnum As Type) As Hashtable
Dim enumNm() As String = System.Enum.GetNames(speedEnum)
Dim enumVal() As Integer = _
CType(System.Enum.GetValues(speedEnum), Integer())
Dim htSpeed As New Hashtable()
For cnt As Integer = 0 To enumVal.Length - 1
htSpeed.Add(enumVal.GetValue(cnt), enumNm(cnt))
Next cnt
Return htSpeed
End Function
Note 1: You need not have to explicitly create a HashTable and then bind it to a DropDownList,
as shown in this example. Instead, you can also directly (quick and dirty) use:
DropDownList1.Items.Add(new ListItem(string text, string value));
I although prefer it the HashTable way since I can refer it at multiple places and it also looks neat to keep stuff seperate in your code!
Note 2: If you want the DropDownList to be sorted based on the value, just reverse the loop.
Tweet
2 comments:
Ok,
Personally I would recommend using this approach instead:
if (!Page.IsPostBack)
{
this.DropDownList1.DataSource = Enum.GetValues(typeof(Speed));
this.DropDownList1.DataBind();
}
* The "if not Page.IsPostBack" check is important. Without it you will re-bind the list on every page load!
Then in the code behind to get the value you simply use:
Speed speed = (Speed)Enum.Parse(typeof(Speed), this.DropDownList1.SelectedValue);
However if you do want to show the ID as the value then yours works fine but I would suggest that you change the name of the method 'BindEnum' to something like GetEnumValues as it is important that method names actually describe what the method is doing.
This doesn't allow sorting of the values in the dropdown.
Post a Comment