Friday 26 September 2008

How to databind a dictionary to a repeater

Lets populate a dictionary object first then databind it to a repeater, this can be done in the Page_load event:

using System.Collections.Generic;

protected void Page_Load(object sender, EventArgs e)

{

Dictionary<int, string> dataList = new Dictionary<int, string>();

dataList.Add(1, "One");

dataList.Add(2, "Two");

dataList.Add(3, "Three");


Repeater1.DataSource = dataList;

Repeater1.Databind();

}

This is what the repeater will look like in the ASPX/ASCX:

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound=" Repeater1_OnItemDataBound">

<ItemTemplate>

<asp:Literal ID="IntValue" runat="server">asp:Literal>

<asp:Literal ID="StringValue" runat="server">asp:Literal>

ItemTemplate>

asp:Repeater>

Now in the ItemDatabound event you can set the values:

protected void Repeater1_OnItemDataBound(Object sender, RepeaterItemEventArgs e)

{

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

{

int intValue = (int)((KeyValuePair<ImageReference, string>)e.Item.DataItem).Key;

int stringValue = (string)((KeyValuePair<ImageReference, string>)e.Item.DataItem).Value;

((Literal)e.Item.FindControl("IntValue")).Text = intValue;

((Literal)e.Item.FindControl("StringValue")).Text = stringValue;

}

}