Bind an ASP.NET DropDownList to a Dictionary

I have seen a lot of folks keeping data in a Dictionary<,>. However when it comes to binding this Dictionary with a control, they feel lost!

Here's a simple way that demonstrates how to bind a Dictionary to an ASP.NET DropDownList control

        <asp:DropDownList ID="ddlRelatives" runat="server">



    Dictionary<int, string> dicRel = new Dictionary<int, string>();

    dicRel.Add(1, "Father");

    dicRel.Add(2, "Mother");

    dicRel.Add(3, "Brother");

    dicRel.Add(4, "Sister");

    dicRel.Add(5, "Others");

    ddlRelatives.DataSource = dicRel;

    ddlRelatives.DataTextField = "Value";

    ddlRelatives.DataValueField = "Key";



    Dim dicRel As New Dictionary(Of Integer, String)()

    dicRel.Add(1, "Father")

    dicRel.Add(2, "Mother")

    dicRel.Add(3, "Brother")

    dicRel.Add(4, "Sister")

    dicRel.Add(5, "Others")

    ddlRelatives.DataSource = dicRel

    ddlRelatives.DataTextField = "Value"

    ddlRelatives.DataValueField = "Key"


Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


kartik sukumaran said...

It says null exception

Anonymous said...

Thanks ! It helped me ! ;-)

Anonymous said...

This is a great start. Could you include the definition of ddlRelatives? Also, with the addition of MVC to, an example of the MVC UI code would rock too. Thanks much. Steve