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">


        </asp:DropDownList>




C#


    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";


    ddlRelatives.DataBind();




VB.NET


    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"


    ddlRelatives.DataBind()







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

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 asp.net, an example of the MVC UI code would rock too. Thanks much. Steve