Simplest possible DataBinding to an array of data

Posted: (EET/GMT+2)

 

Sometimes, people as me what was the syntax to bind ASP.NET web controls to a data source (datasource) that doesn't contain any named elements. For example, you might want to bind to an array of data, but you cannot use the Eval method to do this, since there are no named properties to evaluate.

For example, you might want to use the new ASP.NET 3.5 control ListView to an array of interegers, for instance like this:

int[] numbers = { 12,6,14,9,3,7,11 };
ListView1.DataSource = numbers;
ListView1.DataBind();

Then the question is: how do you refer to the elements of the array in your HTML code? The answer is: referring to the Container.DataItem property. Like this, for example:

<asp:ListView ID="ListView1" runat="server">
  <LayoutTemplate>
    <ul>
      <asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
    </ul>
  </LayoutTemplate>
  <ItemTemplate>
    <li>
      <%# Container.DataItem %>
    </li>
  </ItemTemplate>
</asp:ListView>

Keywords: How to data bind to an array, databind to array, C#, ASP.NET.