Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASp.NET Dropdown and Dictionary

Tags:

asp.net

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.

Thanks

Lijo

like image 867
Lijo Avatar asked Jun 13 '26 19:06

Lijo


2 Answers

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.

like image 97
Nick Craver Avatar answered Jun 16 '26 09:06

Nick Craver


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"));
like image 27
itchi Avatar answered Jun 16 '26 10:06

itchi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!