How to: Bind Jagged array or Single dimension array to repeater control

In this article I will show you how you can bind Jagged array or single dimension array to the repeater control.

1) Jagged array

Let’s create Jagged array first.

string[][] output = new string[3][];
output[0] = new string[]{"1", "Nirvana", "Smells Like Teen Spirit"};
output[1] = new string[]{"2", "Alan Jackson","Buicks to the Moon"};
output[2] = new string[]{"3", "Tool","Schism"};

Create repeater control on the aspx page.

<asp:Repeater runat="server" ID="demo"/>

Bind Jagged array to that repeater control.

demo.DataSource = output;
demo.DataBind();

Run the page and see the output.  By default AutoGenerate property of the repeater control is true.  Repeater control should generate column by itself.  Bu it’s not the case with array, because you have to explicitly specify which index of array you need to bind.


Let’s specify ItemTemplate in the repeater control and bind array index explicitly.

<asp:Repeater runat="server" ID="demo"/>
<HeaderTemplate>
  <tr>
      <td>ID</td> <td>Artist Name</td> <td>Track Name</td>
</tr>
</HeaderTemplate>

<ItemTemplate>
  <tr>
     <td><%#DataBinder.Eval(Container,"DataItem[0]")></td>
     <td><%#DataBinder.Eval(Container,"DataItem[1]")></td>
     <td><%#DataBinder.Eval(Container,"DataItem[2]")></td>
</tr>
</ItemTemplate>

</asp:Repeater>

To display array value we use <%#DataBinder.Eval(Container,”DataItem[0]”)%>.  You can assume DataItem[0] = output[rowIndex] where rowIndex is the row number of the repeater item.

We specify DataItem[0] (0 index) that means we are binding first element of the output[rowIndex] array.
That means DataItem[0] = output[rowIndex][0] where rowIndex is the row number of the repeater.

That’s how you can bind Jagged array to the repeater control.

2) Now let’s bind single dimension array to the repeater control.

.aspx page

<asp:Repeater runat="server" ID="demo">

<HeaderTemplate>
  <tr>
      <td>Artist Name</td>
   </tr>
</HeaderTemplate>

<ItemTemplate>
  <tr>
     <td><%#DataBinder.Eval(Container,"DataItem")%></td>
  </tr>
</ItemTemplate>

</asp:Repeater>

code behind page

protected void Page_Load(object sender, EventArgs e)
{

string[] output = new string[3];
output[0] = new string[]{ "Nirvana"};
output[1] = new string[]{"Alan Jackson"};
output[2] = new string[]{"Tool"};

demo.DataSource = output;
demo.DataBind();
}

The only difference here is that we use <%#DataBinder.Eval(Container,”DataItem”)%>.
Hope this helps.
Shailesh

Posted in Microsoft Technology Tagged with:

Ads