Tech Junkie Blog - Real World Tutorials, Happy Coding!: Bind Enum Type to A DropDownList Control In ASP.NET C#

Sunday, June 19, 2016

Bind Enum Type to A DropDownList Control In ASP.NET C#

Suppose you have an enum type like the one below, and you want to bind the enum type to a DropDownList control in a Web Forms application.  How would you do this?  There's an easy way to do this with just a few lines of code.  You'll be amaze at how simple it is.

First of all here is our markup code in our .aspx page

<%@ Page Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="Sandbox.Default" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

Now let's define our enum type, the last value is 400 just to confirm that the DropDownList1 control is taking the value of the enum type as the value field

    public enum CategoryEnum
        Beverages = 1,
        Condiments = 2,
        Confections = 3,
        DairyProducts = 400

Once we have our enum type define we can iterate through our enum type with a foreach loop and add a new ListItem object to the DropDownList control. Like the code below.

 foreach(int cat in Enum.GetValues(typeof(CategoryEnum)))
    DropDownList1.Items.Add(new ListItem(Enum.GetName(typeof(CategoryEnum),cat),

One of the ListItem method signature is ListItem(string text, string value), we use the Enum.GetName(Type enumType, Object value) to get the string name of the enum. Then we pass in the current value of the enum with the current int value cat in foreach loop and convert into a string to satisfy the ListItem method signature.

When you run the page you will see that the DropDownList1 control is now populated with the CategoryEnum values

If you look at the generated html markup for the DropDownList1 control you will see that both the value and the text value has been set correctly.
      <select name="DropDownList1" id="DropDownList1">
 <option value="1">Beverages</option>
 <option value="2">Condiments</option>
 <option value="3">Confections</option>
 <option value="400">DairyProducts</option>

1 comment:

Search This Blog