|
Highlighting Rows in a GridView...
Highlighting the row of a GridView as the mouse moves over it can help the user find a particular row by making its items stand out. This
article demonstrates an easy way to do the highlighting.
By: John Kilgo
Date: May 23, 2009
Printer Friendly Version
I like the idea of highlighting rows in a GridView as the user scrolls the mouse up and down. The effect can be achieved using the RowDataBound
event handler to add OnMouseOver and OnMouseOut attributes to handle the color change.
The aspx page code for the GridView and its attributes is shown below. Notice that the OnRowDataBound event is defined. RowDataBound is
a GridView method that fires as each row of data is added to the GridView. It allows us make changes, additions, etc to the contents of each
row of data as they are created.
<asp:GridView
id="GridView1"
runat="server"
BackColor="White"
BorderColor="#999999"
BorderStyle="Solid"
BorderWidth="1px"
CellPadding="3"
DataSourceID="SqlDataSource1"
ForeColor="Black"
GridLines="Vertical"
AutoGenerateColumns="False" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
<asp:SqlDataSource
id="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>"
SelectCommand="SELECT TOP 20 CompanyName, LastName, FirstName, Phone FROM AdventureWorksLT.SalesLT.Customer ORDER BY LastName, FirstName">
</asp:SqlDataSource>
In the RowDataBound event in the codebehind we add javascript attributes to each row which control the background color of the row as the mouse
passes over it. Notice that we capture the existing color of each row before we change it for the mouseover and then restore that color
upon mouseout. If we don't do this then all rows will be permanently set to the mouseover color.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load ( object sender, EventArgs e )
{
}
protected void GridView1_RowDataBound ( object sender, GridViewRowEventArgs e )
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
e.Row.Attributes.Add ( "onmouseover", "this.savedColor=this.style.backgroundColor;this.style.backgroundColor='Yellow'" );
e.Row.Attributes.Add ( "onmouseout", "this.style.backgroundColor=this.savedColor;" );
}
}
}
}
|