ASP.NET

Representing Collections without Databinding

One of the most common problems encountered in building any software (and Web sites in particular) is representing collections as user interface elements. Think about some of the sites you have recently visited. If you ordered something from a commercial site, you no doubt hit a page that asked you to enter your address. What happened when you reached the State field? Most Web sites display a drop-down list box from which you may choose a state abbreviation.

How was that drop-down list filled? In HTML, the <selection> tag nests several <option> tags that represent the elements to be listed. The state abbreviations probably came from a database or some other well-established source. Somewhere (most likely at the server), some piece of code had to go through the collection of states and render <selection> and <output> tags for it.

ASP.NET server-side controls, such as the ListBox and the DropDownList, include Items collections. For example, one way to render a collection as a combo box is to declare a combo box on your ASP.NET page and add the items individually via the Items.Add method like so:

protected void BuildComboBox(IList techList)
{
   for(int i = 0; i < techList.Count; i++)
   {
         this.DropDownList2.Items.Add(techList[i]);
   }
}

Because representing collections as UI elements is such a prevalent programming task, it makes a lot of sense to push that down into the framework if at all possible. ASP.NET includes a number of databound controls that are capable of taking collections and rendering the correct tags for you. Let's see how this works.