Some time we want to set different background color or apply diffrent CSS to rows of our databound controls like Repeater, Gridview etc. programmatically depending upon some condition. Here I'll show how ho to do that.
1) Create required CSS
Here I have created three diffrent CSS styles for rows.
2) Create Repeater Control
This is the first repeater control. I have bind the repeater with country table having two columns countryName and country Id. To apply diffrent Css to alternate rows. I have used ternary operator on row's "Class" attribute ( ">). This will apply blue class to rows having even index and green class to rows having odd index.
<table>
<tr>
<td>
<b>Sno</b>
</td>
<td>
<b>Country Name</b>
</td>
</tr>
<asp:Repeater ID="RepeaterCountries1" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<tr class="<%#(Container.ItemIndex+1)%2==0?"blueRow":"greenRow"%>">
<td>
<%#Container.ItemIndex+1 %>
</td>
<td>
<%#Eval("countryName") %>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
Using Code behind to apply different rows conditionally
For this demonstration I have created function in codebehind which will return css according to repeater's row index.This will apply blue class to rows having even index and green class to rows having odd index.
1) Repeater Control:
<table>
<tr>
<td>
<b>Sno</b>
</td>
<td>
<b>Country Name</b>
</td>
</tr>
<asp:Repeater ID="RepeaterCountries2" runat="server">
<ItemTemplate>
<tr class="<%#setClass(Convert.ToInt32(Eval("countryId")))%>">
<td>
<%#Container.ItemIndex+1 %>
</td>
<td>
<%#Eval("countryName") %>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
2) Code Behind Function:
//=-=-=-= To return Class name as per condition applied.
//=-=-=-= To set style of the row as per condition.
protected string setClass(int CountryId)
{
string classToApply = string.Empty;
if (CountryId <= 10)
{
classToApply = "blueRow"; //== Here blue row is the name of the CSS class I have created.
}
else if (CountryId > 10 && CountryId <= 20)
{
classToApply = "grayRow"; //== Here blue row is the name of the CSS class I have created.
}
else
{
classToApply = "greenRow"; //== Here blue row is the name of the CSS class I have created.
}
return classToApply;
}
5) Final Output
6) Source Code:
Click to download