Bind Dictionary to GridView

If your looking to bind a Dictionary object to a GridView control, like most GridView bindings, here are 3 ways of doing it:
 

Option 1
Declaring the GridView with no coloum specific information:

[xhtml]
<asp:GridView ID=”SearchResults” runat=”server”>
</asp:GridView>
[/xhtml]

 

Option 2
Declaring the GridView using the bound column method:

[xhtml]
<asp:GridView ID=”SearchResults” runat=”server” AutoGenerateColumns=”false”>
    <Columns>
      <asp:BoundField DataField=”Key” HeaderText=”GUID”/>
      <asp:BoundField DataField=”Value” HeaderText=”Description”/>
    </Columns>
</asp:GridView>
[/xhtml]

 

Option 3
Declaring the GridView using the Template Field method:

[xhtml]
<asp:GridView ID=”SearchResults” runat=”server” AutoGenerateColumns=”false”>
    <Columns>
    <asp:TemplateField HeaderText=”GUID”>
        <ItemTemplate>
        <%# Eval(“Key”) %>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText=”Description”>
        <ItemTemplate>
        <%# Eval(“Value”) %>
        </ItemTemplate>
    </asp:TemplateField>
    </Columns>
</asp:GridView>
[/xhtml]

 

Sample Test Code
To test this out, place this in your code behind Page_Load method:

[csharp]

protected void Page_Load(object sender, EventArgs e)
{
    Dictionary<string, string> list = new Dictionary<string, string>();

    for (int i = 1; i <= 10; i++)
    {
        list.Add((new Guid(System.Guid.NewGuid().ToString(“B”))).ToString(), “list item ” + (i).ToString());
    }

    SearchResults.DataSource = list;
    SearchResults.DataBind();
}

[/csharp]

4 thoughts on “Bind Dictionary to GridView

Comments are closed.