DataList控件绑定到字典中 [英] Binding DataList to Dictionary

查看:103
本文介绍了DataList控件绑定到字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

是的。使用密钥作为DataKeyField:

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

这篇关于DataList控件绑定到字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆