Ok, this is one of those "cute" questions. Great for learning.
Ok, so assume this markup for the grid view:
<asp:GridView ID="GVHotels" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" OnRowDataBound="GVHotels_RowDataBound"
width="50%" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" />
</Columns>
</asp:GridView>
And our code behind to load the gridview is this:
Dim Lastcity As String = ""
Dim ColorToggle As Boolean = False
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
GVHotels.DataSource =
MyRst("SELECT * FROM tblHotelsA ORDER BY City, HotelName")
GVHotels.DataBind()
End Sub
Protected Sub GVHotels_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
If Lastcity <> e.Row.Cells(2).Text Then
ColorToggle = Not (ColorToggle)
Lastcity = e.Row.Cells(2).Text
End If
If ColorToggle Then
e.Row.BackColor = System.Drawing.Color.LightSkyBlue
Else
e.Row.BackColor = System.Drawing.Color.LightBlue
End If
End If
End Sub
And the result is this:
Ah, at the very end the poster notes:
using c#
I missed that part. However, I'm fluent either way, so this is the above vb code in c#:
string Lastcity = "";
bool ColorToggle = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
GVHotels.DataSource =
General.MyRst("SELECT * FROM tblHotelsA ORDER BY City, HotelName");
GVHotels.DataBind();
}
protected void GVHotels_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Lastcity != e.Row.Cells[2].Text)
{
ColorToggle = !ColorToggle;
Lastcity = e.Row.Cells[2].Text;
}
if (ColorToggle)
e.Row.BackColor = System.Drawing.Color.LightSkyBlue;
else
e.Row.BackColor = System.Drawing.Color.LightBlue;
}
}