2
var dict = new Dictionary<string,string>();
dict.Add("A","123");
dict.Add("B","456");
dict.Add("C","789");
dict.Add("D","000");
var list = new List<Dictionary<string,string>>(); //pretty much like a DataTable
list.Add(dict); //more than one dict in the list

//ddl is a dropdownlist
ddl.DataSource = list
ddl.DataTextField ="[A]";
ddl.DataValueField ="[C]";
ddl.DataBind();

For WPF, I can do similar binding above, but not in asp.net.

2
  • well you know that WPFs binding is a couple of magnitudes better than ASP.NETs? You will have to transform your data before binding them as DataSource - sorry. Commented Mar 12, 2012 at 7:34
  • You want to bind a string dictionary to dropdownlist in asp.net.Is it? Commented Mar 12, 2012 at 9:26

2 Answers 2

6

You should bind your dictionary, not list. Something like this :

var dict = new Dictionary<string,string>();
dict.Add("A","123");
...

ddl.DataSource = dict
ddl.DataTextField ="Key";
ddl.DataValueField ="Value";
ddl.DataBind();
Sign up to request clarification or add additional context in comments.

Comments

4

This works great for me:

Dictionary<string, string> myDict = Dictionary<string, string>();
myDict.Add("myKey","My test value");

@Html.DropDownList("SomeDropDown", new SelectList(myDict, "key", "Value"),
                   "--- Select tomething ---", new { @class = "myHtmlClassName" })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.