tags:

views:

487

answers:

1

I have a Dictionary I want to bind to a DataList. But I also want to use the Dictionary's Key value for the DataList's DataKeyField property. Is this possible?

+1  A: 

Yes. Use the "Key" as a DataKeyField:

<asp:DataList ID="datalist" runat="server" DataKeyField="Key">
    <ItemTemplate>
     <asp:Label runat="server" Text='<%# Eval("Value") %>'></asp:Label>
    </ItemTemplate>
</asp:DataList>

Code:

protected void Page_Load(object sender, EventArgs e)
{
    Dictionary<string, string> dictionary = new Dictionary<string, string>()
    {
     {"a", "aaa"},
     {"b", "bbb"},
     {"c", "ccc"}
    };
    datalist.DataSource = dictionary;
    datalist.DataBind();

    for (int i = 0; i < datalist.Items.Count; i++)
    {
     Response.Write(string.Format("datalist.DataKeys[{0}] = {1}<br />", i, datalist.DataKeys[i]));
    }
}
Ruslan
Crap, well I already did it a different way, but I will still give this a try since I think this will work out much more elegantly. Thank you for the response!
hanesjw