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


3 comments:

  1. Thanks ! It helped me ! ;-)

    ReplyDelete
  2. 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

    ReplyDelete