This tutorial explaiins how to bind a Dictionary<key,value> pair to a listbox/dropdown list. The following simple steps show how to bind your listbox/dropdown list to Dictionary<key,value> pair.
Step 1:
Create a Dictionary<key,value> pair in your code behind file i.e .CS file. The following code shows how the Dictionary<key,value> pair of <int,string> is created. dStudent is a Dictionary<key,value> pair which stores a list of student name as value with id as key.
///Creating Dictionary of <int,string> for Student.
Dictionary<int, string> dStudent = new Dictionary<int, string>();
//Adding key value pair to the dictionary
dStudent.Add(0, "Eena");
dStudent.Add(1, "Meena");
dStudent.Add(2, "Deeka");
dStudent.Add(3, "Tom");
dStudent.Add(4, "Dick");
dStudent.Add(5, "Harry");
dStudent.Add(6, "Yamla");
dStudent.Add(7, "Pagla");
dStudent.Add(8, "Dewana");
dStudent.Add(9, "Guru");
dStudent.Add(10, "Sholay");
Step 2:
After creating a Dictionary<key,value> pair it's time to bind a Dictionary<key,value> pair with your listbox/dropdown list. The following code binds to dropdown and listbox too.
//binding to the list
lst.DataTextField = "Value";
lst.DataValueField = "Key";
lst.DataSource = dStudent;
lst.DataBind();
//binding to the Dropdown
drp.DataTextField = "Value";
drp.DataValueField = "Key";
drp.DataSource = dStudent;
drp.DataBind();
Step 3:
Some code written on the selected index change event of both listbox and dropdownlist control. The following code will just display the Text and the value of the selected item of the respective control.
protected void lst_SelectedIndexChanged(object sender, EventArgs e)
{
lbl.Text+= "<br/>" + String.Format("Selected Text:{0} and Value:{1}", lst.SelectedItem.Text, lst.SelectedValue);
}
protected void drp_SelectedIndexChanged(object sender, EventArgs e)
{
lbl.Text+= "<br/>" + String.Format("Selected Text:{0} and Value:{1}", drp.SelectedItem.Text, drp.SelectedValue);
}
Output:
When you run your application, the Dictionary<key,value> pair is bound to the listbox/dropdown list.
When you select from the listbox, look at the selected item text and the value assigned to the label.
When you select from dropdown list, look at the selected item text and value assigned to the label.
When you select from list box, look at the selected item text and value assigned to the label.
When you select from dropdown list, look at the selected item text and value assigned to the label.