我想將字典列表綁定到GridView。Databind將字典列表綁定到GridView中
var liste = new List<Dictionary<string, string>>();
var dictionary = new Dictionary<string,string>();
dictionary["Id"] = "111";
dictionary["Description"] = "text to show";
dictionary["OtherInfo"] = "other text";
liste.Add(dictionary);
gvClients.DataSource = liste;
gvClients.DataBind();
在ASPX的代碼:
<asp:GridView ID="gvClients" runat="server" AutoGenerateColumns="true" GridLines="None"
AllowPaging="True" CssClass="gridview" AlternatingRowStyle-CssClass="alt" Width="80%">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="PropertyName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PropertyName">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("OtherInfo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
如何可以結合在GridView到該對象(或一System.Collections.HashTable)。
編輯
的怪胎對字典的工作,但不是哈希表的解決方案,有沒有解決方案?
var liste = new List<System.Collections.Hashtable>();
var table = new System.Collections.Hashtable();
table["Denomination"] = "a";
table["Denomination2"] = "an";
liste.Add(table);
var result = liste.Select(map => new
{
IdClient = map["Denomination"],
Denomination = map["Denomination2"]
}).ToList();
gvClients.DataSource = result;
gvClients.DataBind();
我有此錯誤:
The data source for GridView with id 'gvClients' did not have any properties or attributes from which to generate columns.
當我修改這樣的映射:
var result = liste.Select(map => new
{
IdClient = map["Denomination"],
Denomination = map["Denomination2"],
Test = "test"
}).ToList();
這將只顯示測試性能。
謝謝
自動數據綁定無法做到這一點。您必須使用PropertyDescriptor將項目轉換爲表格。 – 2011-04-19 08:44:34
它看起來有點複雜,我的需要。你有一個簡短的例子嗎? – 2011-04-19 09:21:27
你使用哪個版本的.net? – 2011-04-19 09:51:50