Feb 24, 2012

Enum Examples or How to Bind the DropDownList With Enum?

Enum is the type provided by dotnet, it stores constant value in it. When we want to specify some constant value to use in the project then it is very usefull for readability.

In this post I will show you how to declare an enum and how to use it in the program.
Here I have bind the enum to the dropdown list

Declare the enum as below

public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

In aspx page I have added DropDownList named ddlDays as below

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

Now below is the code to bind dropdownlist control with above enum
// Add first item to the drop down list to select lable
        ddlDays.Items.Add("--Select Days--");

        string[] enumNames = Enum.GetNames(typeof(Days));
        foreach (string item in enumNames)
        {
            int value = (int)Enum.Parse(typeof(Days), item);
            ListItem listItem = new ListItem(item, value.ToString());
            //Add one by one item to the drop down list
            ddlDays.Items.Add(listItem);
        }
 













Out put is displayed in the side image.


3 comments:

Part Time Jobs

Nice info ..... Just Visit Classiindia - free online Classified Website , Buy & Sell , Real Estate , Jobs, Educations , Services, Pets, Electronics , More Services Visit - www.classiindia.in

Scott Gehrman

Looking for asp.net development contract help. If interested please contact sgehrman@g3service.com Thanks

Launch Business in Delhi

Hi, Really great effort. Everyone must read this article. Thanks for sharing.

Post a Comment

Author Profile

Total Pageviews

Categories

Followers

 

Sponsors