Powered by Blogger.

Saturday, February 15, 2014

Bind dropdownlist from enum in Asp.Net




In this post we will discuss how to bind a dropdownlist from enum in asp.net. Also you can check my previous posts on:

- Sql Server 2008 joins tutorial

- Difference between Abstract Class and Interface in C#.Net

- Exception handling in C#.Net

Here is an example where I am binding a dropdownlist from a enum.

First write an enum like below:

 public enum UserRole
    {
        Developer = 1,
        Admin = 2,
        SuperAdmin = 3,
        SuperDuperAdmin = 4
    }

Now we can put a dropdownlist in the .aspx page and we can bind like below:

Below is the full code:

.Aspx Code:
<div>
      User Roles:  <asp:DropDownList ID="ddlUserRoles" runat="server"></asp:DropDownList>

</div>

.CS Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class EnumTest : System.Web.UI.Page
{
    public enum UserRole
    {
        Developer = 1,
        Admin = 2,
        SuperAdmin = 3,
        SuperDuperAdmin = 4
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string[] enumRoles = Enum.GetNames(typeof(UserRole));
            foreach (string item in enumRoles)
            {
                //get the enum item value
                int value = (int)Enum.Parse(typeof(UserRole), item);
                ListItem listItem = new ListItem(item, value.ToString());
                ddlUserRoles.Items.Add(listItem);
            }
        }
    }

}

After this it will come like below:



0 comments

Post a Comment