2.6. Displaying Data from a Hashtable

Problem

You have data in a Hashtable, a class that provides the ability to store a collection of key/value pairs, and you want to display the data in a columnar table.

Solution

Use a DataList control and bind the Hashtable to it.

Add a DataList control to the .aspx file, being careful to place it in a Table cell to control its position on the form.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Define the Hashtable as the data source for the DataList control.

  2. Set the control’s key and value.

  3. Bind the Hashtable to the DataList control.

Figure 2-5 shows the appearance of a typical DataList within a browser that has been bound to a Hashtable filled with, in our case, book data. Examples 2-14, 2-15 through 2-16 show the .aspx and code-behind files for an application that produces this result.

Discussion

The DataList control can display almost any data type in various ways using its available templates and styles. Templates are available for the header, footer, items, alternating items, separators, selected items, and edit items to define and organize the data to output. Styles are available for each of the templates to define how the content appears.

In this example, an asp:DataList control is placed in a Table cell to control its position on the form, as shown in Example 2-14. The RepeatColumns attribute of the control defines the number of columns that should be output, which in this case is 4.

Figure 2-5. DataList with ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.