In this article I will explain with an example, how to populate (bind) DropDownList from Enum in ASP.Net using C# and VB.Net.
The Enum values will be extracted into an Array and then each Array item will be added to the ASP.Net DropDownList using C# and VB.Net.
HTML Markup
The following HTML Markup consists of an ASP.Net DropDownList which will be populated using Enum values.
<asp:DropDownList ID="ddlColors" runat="server">
</asp:DropDownList>
Enum
Following is a simple Enum of 3 colors Red, Green and Blue to which I have assigned integer values 1, 2 and 3 respectively.
C#
public enum Colors
{
Red = 1,
Blue = 2,
Green = 3
}
VB.Net
Public Enum Colors
Red = 1
Blue = 2
Green = 3
End Enum
Populate (Bind) DropDownList from Enum in ASP.Net
Inside the Page Load event of the page, the values of the Enum are fetched into an Array and then a loop is executed over the Array items and one by one each item is added to the DropDownList.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Array colors = Enum.GetValues(typeof(Colors));
foreach (Colors color in colors)
{
ddlColors.Items.Add(new ListItem(color.ToString(), ((int)color).ToString()));
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim colors As Array = [Enum].GetValues(GetType(Colors))
For Each color As Colors In colors
ddlColors.Items.Add(New ListItem(color.ToString(), CInt(color).ToString()))
Next
End If
End Sub
Screenshot
Demo
Downloads