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.
The data used to illustrate the problem is shown below by placing a GridView
on the page and simply databinding to the available DataSource.
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.
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.
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.
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.
From the above code, the desired effect is achieved as shown below: