Tips to Bind Dropdownlist in Asp.net

Tips to Bind Dropdownlist in Asp.net

We can bind DropDownList in different ways by using List, Dictionary, Enum and DataSet.

To bind DropDownList, we need to set some properties:

DataSource
DataValueField
DataTextField

Let’s see how to use these properties to bind DropDownList.

Binding DropDownList with List

In this case, the DropDownList both ‘Value’ and ‘Text’ field are same.

DropDownList ddl = new DropDownList();
List countries = new List();
countries.Add(“UK”);
countries.Add("India");
ddl.DataSource = countries;
ddl.DataBind();

Binding DropDownList with Dictionary

Dictionary<string, string> States = new Dictionary<string, string>();
States.Add("-1","-Select-");
States.Add("OD", “Odisha”);
States.Add("DL", “Delhi”);
States.Add("MH", “Maharastra”);
States.Add("WB", “West Bengal”);
ddl.DataSource = States;
ddl.DataValueField = "Key";
ddl.DataTextField = "Value";
ddl.DataBind();

Binding DropDownList with DataSet

My DataSet contains a Class table(class_id,class_name,description).

ddl.DataSource = dataset.Tables[0].DefaultView;
ddl.DataValueField = "class_id";
ddl.DataTextField = "class_name";
ddl.DataBind();
ListItem item = new ListItem(“—Select—“, "-1");
ddl.Items.Insert(0, item);
Binding DropDownList with Enum

Let’s take Countries ‘enum’ as follows:

enum enCountries:int{India=0,USA,UK,UAE};
Let’s see how to bind the DropDownList With Enum:

ddlEnumBind.Items.Add("--Select--");
//get enum items to get the respective enum value
string[] enumNames=Enum.GetNames(typeof(enCountries));
foreach (string item in enumNames)
{
//get the enum item value
int value = (int)Enum.Parse(typeof(enCountries), item);
ListItem listItem = new ListItem(item, value.ToString());
ddlEnumBind.Items.Add(listItem);
}

Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top