Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Formatting TABLE items in a GridView or DataList through declarative syntax

4.34/5 (13 votes)
25 Feb 2007CPOL2 min read 1   850  
The article explores a solution to maintain formatting when using HTML TABLE rows inside ItemTemplate tag for a GridView or a DataList.

Introduction

When displaying multiple records in a GridView or a DataList the control renders an HTML Table element for the complete control and individual <TR> elements for each row. The format options selected in the Visual Studio Properties window for item, alternate items, etc., are rendered as attributes and styles for the TABLE, TR, and TD elements. This poses a typical problem when we try to fit a table inside a GridView or DataList control's item templates. To illustrate this issue, let us look at a business case.

Problem

Say we are building a directory application (like yellow pages) and have records of different companies which have to be displayed in the following format, changing the background color for alternate items.

Business Requirement

The data used to illustrate the problem is shown below by placing a GridView on the page and simply databinding to the available DataSource.

Simple databind

Solution

Since there are multiple rows required for each row inside the GridView, it is obvious we have to set AutoGenerateColumns="False" and add an ItemTemplate with TABLE layout to get the desired effect.

HTML Code

Since a table is introduced into each row of the DataView, columns of every table have their own alignment. This problem can be seen with the address line stretching the table in the second row. See the code and results below.

Effect

The trick is to remove the <TABLE> tag inside the ItemTemplate. This will carry over the column alignment through all rows of the GridView. But once we do this, the GridView header and alternate items have a problem. The style for the alternate items do not propagate to the inner <TR> elements we have created. The figure below shows the problem.

Effect

To overcome this issue, remove the header. Anyhow we are not dealing with individual columns here; if that is the case, we will not even be here! Next determine what to do with the alternate items in the code. In our case, to have a different color for alternate items, use Container.ItemIndex and determine the even rows. Apply the required styles to the even rows. Use Container.ItemIndex for DataList and Contrainer.DisplayIndex for GridView. The final code for GridView is shown below. For DataList, this code is even simpler because you do not need the <Columns> tag and the <asp:TemplateField> tags.

Effect

From the above code, the desired effect is achieved as shown below:

Effect

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)