Saturday, January 19, 2013

A Simple List Binding Example in ASP.NET

To try this type of data binding, add a ListBox control to a new web page. Next, import the System.Collections namespace in your code. Finally, use the Page.Load event handler to create an ArrayList collection to use as a data source as follows:

ArrayList fruit = new ArrayList();

Now, you can link this collection to the ListBox control:

lstItems.DataSource = fruit;

Because an ArrayList is a straightforward, unstructured type of object, this is all the information you need to set. If you were using a DataTable (which has more than one field) or a DataSet (which has more than one DataTable), you would have to specify additional information.

To activate the binding, use the DataBind() method:


You could also use lstItems.DataBind() to bind just the ListBox control. Figure shows the resulting web page.

This technique can save quite a few lines of code. This example doesn’t offer a lot of savings because the collection is created just before it’s displayed. In a more realistic application, however, you might be using a function that returns a ready-made collection to you:

ArrayList fruit;

fruit = GetFruitsInSeason("Summer");

In this case, it’s extremely simple to add the extra two lines needed to bind and display the collection in the window:

lstItems.DataSource = fruit;

or you could even change it to the following, even more compact, code: 

lstItems.DataSource = GetFruitsInSeason("Summer");

No comments:
Write comments
Recommended Posts × +