Monday, April 23, 2012

Binding Enum Types to DropdownList control in asp.net using C#

I have already explain how to create a Enum in my previous article.See My previous article on Enum.
Now In this post I am going to explain about how to bind the enum values to the dropdown and how to read the selected item from the drop down. In Some cases we need to bind the enm data in to a dropdownlist control.in this situations it will helpful.
To Do this First create a An aspx page with the following code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
    <asp:Button ID="Button1" runat="server" text="Get Selected Enum Value" OnClick="Button1_Click" />
    <hr />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
Then Add a new Class called EnumClass  and Declare the two Enums .My Enumclass is as follows :

public class Enumclass
    {

        public Enumclass()
        {
        }
        public enum TaskType
        {
            Development,
            Operation,
            Reporting,
            Deploying,
            Monitoring
        }

        public enum Status
        {
            New = 100,
            Started = 300,
            Partially = 35,
            Completed = 400
        }
    }
Now add the following code in the code behind . 

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               
                DropDownList1.DataSource = Enum.GetNames(typeof(Enumclass.TaskType));
                DropDownList1.DataBind();

                DropDownList2.DataSource = Enum.GetNames(typeof(Enumclass.Status));
                DropDownList2.DataBind();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Enumclass.TaskType SelectedType = (Enumclass.TaskType)Enum.Parse(typeof(Enumclass.TaskType), DropDownList1.SelectedValue);
            Label1.Text = "Task Type:  SelectedText: " + SelectedType.ToString() + "  SelectedValue: " + SelectedType.GetHashCode();
            Enumclass.Status SelectedStatus = (Enumclass.Status)Enum.Parse(typeof(Enumclass.Status), DropDownList2.SelectedValue);
            Label2.Text = "Task Status:  SelectedText: " + SelectedStatus.ToString() + "  SelectedValue: " + SelectedStatus.GetHashCode();
        }

Output :

No comments:

Post a Comment