Wednesday, 20 July 2011

Bind an ArrayList to a Repeater with ASP.NET 4.0 and C#


This tutorial will demonstrate how to use a repeater to display the data from an array list with ASP.NET 4.0 and C#.

Adding the Repeater
To demonstrate how to bind an array list to a repeater, we will need to create a simple web site with a repeater on it. To do this, create a new ASP.NET Empty Web Site and:

Need help with cloud hosting? Try Server Intellect. We used them for our cloud hosting services and we are very happy with the results!

  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'Default.aspx'.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a repeater onto the web form.
  8. Open Default.aspx up to source mode.
  9. Add the following item template to the repeater:
    <ItemTemplate>
        <%# Container.DataItem %><br />
    </ItemTemplate>
We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

This simply adds an item template to our repeater that will display the values of our array list. Notice that instead of accessing the data using the eval method with an index of a column name, we use Container.DataItem. This is because the array list we will bind to the repeater does not have specifications for rows and columns, it simply contains a list of data items.

Binding the ArrayList
Now that we have our repeater setup to output the appropriate data, we need to bind some data to it. To do this, add the following code to the Page_Load event method:
if (!Page.IsPostBack)
{
    //create an array list
    ArrayList arrList = new ArrayList();
    //populate the list with some temp values
    arrList.Add("One");
    arrList.Add("Two");
    arrList.Add("Three");
    arrList.Add("Four");

    //databind the list to our repeater
    Repeater1.DataSource = arrList;
    Repeater1.DataBind();
}

If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

This simply creates an array list and populates it with temporary values. Then, we bind it to our repeater. To test this out, simply load up the web site and ensure that the values of your array list are being displayed on the page. The repeater is an extremely dynamic control that is able to conform to a number of different unique data sources. However, the repeater code to access its data is unique based on what type of data source you are binding to it.

No comments:

Post a Comment