收录日期:2021/02/27 20:45:59 时间:2009-03-14 00:44:33 标签:c#,asp.net

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?

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]));
    }
}