Very often when using either a DataList or Repeater control, you will see folks using an <AlternatingItemTemplate> template section just to change the background color of every other row. While this is perfectly acceptable, it can become time-consuming , especially if the templated row contains a significant amount of HTML. When it does, you have to ensure that any changes to the HTML in either section (<ItemTemplate> or <AlternatingItemTemplage>) are duplicated except for the background color of the table row of course.
If all you are doing is changing the alternating row color but don’t want to have to keep two sets of row level HTML in sync, there is an easier way. You can just use the primary <ItemTemplate> section so you only have one set of HTML to maintain, yet still have the background color of alternating rows change. Here’s how.
For Repeater Controls
First, turn the <tr> tag of the primary ItemTemplate template into a server control by adding ID and runat=”server” attributes.
<tr>
becomes…
<tr id=”row_itemtemplate” runat=”server”>
Next, add the following code to the ItemCreated event of the repeater. Note that it simply locates the row tag you modified above and adds changes the back color.
If e.Item.ItemType=ListItemType.AlternatingItem Then
Dim cTableRowTag As HtmlTableRow = CType (e.Item.FindControl(“row_itemtemplate”), HtmlTableRow)
If cTableRowTag IsNot Nothing Then
cTableRowTag.Attributes.Add(“bgcolor”, “#cccccc”)
End If
The code in the ItemCreated event fires for every row created in the Repeater. It first checks if the row is an alternating row and if it is, it then locates the HTML <tr> tag and adds the alternating bgcolor attribute for you. Presto! Instant color change and all without duplicating your HTML layout in a second section.
For DataList Controls
Since the DataList is rendered as an HTML <table>, its DataListItem instances have style-related properties where you can apply a specific style to the entire item. This this makes it easier to accomplish our goal. Simply create a CSS class that defined your new background color, then reference that class as follows in the same event at above.
e.Item.CSSClass = “myBGColorClass”
You can also use the same approach as the Repeater control if you prefer.
Thanks Don, it really solved my alternating item issue, Cheers!!
Then When should we need to Alternateitem Templete exactly ?