C#: Set Dictionary as a data source for Drop Down List

There are situations when you need to create a list of key pair values after fetching data from the database and attach them to some Web Controls on your web page. Unlike Windows Application where you can attach whole Data List of Class to the control and the controller will act as a container, Web Controls do not support the same way. Either you need to create a new class with two properties; one for Key and second for Value part.

In this case, you can go for using Disctionary<T key, T value>, T can be used as any datatype with standard .Net datatype. You can go through the loop and create a new Dictionary object and assign the Dictionary object to the web control. And set DataTextField to Key and DataValueField to Value.

Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("item 1", "Item 1");
list.Add("item 2", "Item 2");
list.Add("item 3", "Item 3");
list.Add("item 4", "Item 4");

dropDownList.DataSource = list;
dropDownList.DataTextField = "Value";
dropDownList.DataValueField = "Key";
dropDownList.DataBind();

3 thoughts on “C#: Set Dictionary as a data source for Drop Down List

  1. I do consider all of the concepts you have introduced on your post.
    They’re really convincing and can certainly work. Still, the posts are
    too short for newbies. Could you please extend them a little from next time?
    Thanks for the post.

  2. Do you mind if I quote a few of your posts as long as I provide credit and
    sources back to your blog? My website is in the exact same niche as yours and my users would
    truly benefit from a lot of the information you provide here.
    Please let me know if this ok with you. Cheers!

  3. Pingback: My Homepage

Leave a comment