I’d like to bind a List of Dictionary to a 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();
The code in the 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>
How can I bind the GridView to that Object (or a System.Collections.HashTable).
edit
The geek’s solution for Dictionary work but not for HashTable, is there a solution ?
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();
I’ve this error :
The data source for GridView with id 'gvClients' did not have any properties or attributes from which to generate columns.
When I modify the mapping like this :
var result = liste.Select(map => new
{
IdClient = map["Denomination"],
Denomination = map["Denomination2"],
Test = "test"
}).ToList();
It will show only the Test property.
Thanks
Check out the following code.
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>Edit
I have edited the code as per your requirements.Please try this code and let me know if you experience any problems .
EDITII
If you want to use Hashtable then do the following
Create a new class named Client (what ever you want)
and then query the list as follows