【问题标题】:Binding DataList to Dictionary将 DataList 绑定到字典
【发布时间】:2009-03-14 00:37:35
【问题描述】:

我有一个要绑定到 DataList 的字典。但我也想为 DataList 的 DataKeyField 属性使用 Dictionary 的 Key 值。这可能吗?

【问题讨论】:

  • 您希望项目以什么顺序出现?

标签: c# asp.net


【解决方案1】:

是的。使用“Key”作为 DataKeyField:

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

代码:

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

【讨论】:

  • 废话,我已经用不同的方式做了,但我仍然会尝试一下,因为我认为这会更优雅。感谢您的回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多