Binding DropdownList Using List, Dictionary, Enum and DataSet in ASP.NET

Binding DropdownList Using List, Dictionary, Enum and DataSet in ASP.NET

In this article am going to explain different ways of binding data to DropDownList. We can bind DropDownList in different ways by using List, Dictionary, Enum and DataSet.

First add a DropDownList to .aspx page

<div>

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

</div>

 Binding List to DropDownList

I have created a List of StatusType and binding to DataSource property of DropDownList. In this case both the 'Value' and 'Text' field of DropDownList are same.

List<string> statusTypes = new List<string> ();

statusTypes.Add("Draft");

statusTypes.Add("Published");

statusTypes.Add("Abused");

ddlStatusType.DataSource = statusTypes;

ddlStatusType.DataBind();

 

Binding Dictionary to DropDownList

I have created a Dictionary of StausType and binding it to DataSource property of DropDownList. In this case, am binding Dictionary key to DataValueField and value to DataTextField of the DropDownList.

Binding Key and Value of Dictionary to DropDownList

Dictionary<string,string> statusTypes = new Dictionary<string,string>();

statusTypes.Add("D","Draft");

statusTypes.Add("P","Published");

statusTypes.Add("A","Abused");

ddlStatusType.DataSource = statusTypes;

ddlStatusType.DataValueField = "Key";

ddlStatusType.DataTextField = "Value";  

ddlStatusType.DataBind();

ddlStatusType.Items.Insert(0, new ListItem("-- Please Select --", "-1"));        

 

Binding an Enum to DropDownList

In this case I am binding text of an enum to DropDownList.

 

   enum StatusTypes

        {

            Draft = 1, // To set the Order

            Published,

            Abused

        }

   protected void BindStatusDropDown()

        {

            ddlStatusType.DataSource = Enum.GetNames(typeof(StatusTypes));

            ddlStatusType.DataBind();

        }

 

Binding DataSet to DropDownList

In this case I have created a DataSet with two columns as “StatusID” and “StatusType” and binding it to DataValueField and DataTextField of the DropDownList. 

 

//Creating a Dataset

 DataTable dt = new DataTable();

 dt.Columns.Add("StausID");

 dt.Columns.Add("StausType"); 

 dt.Rows.Add("D", "Draft");

 dt.Rows.Add("P","Publish");

 dt.Rows.Add("A","Abused"); 

 DataSet ds = new DataSet();

 ds.Tables.Add(dt);

  //Binding dataset to DropDownList

 ddlStatusType.DataSource = ds.Tables[0].DefaultView;

 ddlStatusType.DataValueField = "StausID";

 ddlStatusType.DataTextField = "StausType";

 ddlStatusType.DataBind();

 Output

 

Summary

I hope this article will help you to understand various ways of binding data to Asp.net DropDownList. Please share your valuable feedback on this.

comments powered by Disqus

Related Articles