Tutorial :ASp.NET Dropdown and Dictionary


I am using a dropdown list in ASP.NET with C#.

I am trying to bind a dictionary to the dropdownlist.

How can we specify the "Text" (key of dictionary as Text of drop down) and "value" (value as Value) for the dropdown?

Could you please help?

Note: There is a constraint that a class should not be introduced for this purpose. That is why I am trying to use a dictionary.




Setup your dropdown to use Key and Value, like this:

dropdown.DataValueField = "Key";  dropdown.DataTextField= "Value";  dropdown.DataSource = myDictionary;  dropdown.DataBind();  

Since you're actually binding a KeyValuePair to each item, the properties you want to access are Key and Value.


Dictionary<string, string> myDictionary = new Dictionary<string, string>();  myDictionary.Add("1", "Item1");  myDictionary.Add("2", "Item2");  myDictionary.Add("3", "Item3");    DropDownId.DataSource = myDictionary;  DropDownId.DataTextField = "Key";  DropDownId.DataValueField = "Value";  DropDownId.DataBind();  

I would also add, that if you can't add a new List<myClass> for this purpose then why are you allowed to use a Dictionary? We can also add items to the dropdownlist without a datasource:

DropDownID.Items.Add(new ListItem("Item4","4"));  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »