Dictionary as DropDownList Data Source

I have a Dictionary<T,T> called myListOptions. To use it as the datasource for an ASP.NET DropDownList called MyList...

MyList.DataSource = myListOptions;
MyList.DataTextField = "Value";
MyList.DataValueField = "Key";
MyList.DataBind();


It took me some rummaging to realize that you use the actual strings "Value" and "Key," so I hope this post comes in handy for someone else in the future (even if it's me).

6 comments:

Anonymous said...

Thank you!!! Saved me a few lines of code and a ton of frustration.

Anonymous said...

Brilliant! You saved my day!

Anonymous said...

It sure came in handy for me as well. Don't know how you figured out to use the text but I give you a 10 out of 10 for ingenuity!

Dinh Doan Van Bien said...

Thank you very much, very helpful

Chris said...

Cheers! One of those simple things that could of taken hours to figure out! Thanks for sharing!

Eric Fickes said...

Thanks for posting this. I've been trying to DataBind a collection of custom class so that I could specify DataTextField and DataValueField.

So simple, and so perfect!