May 25, 2009

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()




'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Bind an ASP.NET DropDownList to a Dictionary"
  1. kartik sukumaran said...
    January 7, 2010 10:36 PM

    It says null exception

  2. Anonymous said...
    September 22, 2010 1:30 AM

    Thanks ! It helped me ! ;-)

  3. Anonymous said...
    April 22, 2011 7:14 AM

    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

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions