Programming Journal C#, Java, SQL and to a lesser extent HTML, CSS, XML, and regex. I made this so other programmers could benefit from my experience.

Saturday, August 15, 2009

Highlight Rows in a GridView

To highlight rows in a GridView you will want to use the GridView DataBound event to add the onmouseover and onmouseout attributes. While CSS methods may work in FireFox browsers, they do not work in Internet Explorer. For the associated javascript method, you can directly set it with this.style.backgroundColor, but this is inflexible. Instead, change the CSS class.

Here is the CSS for the highlighted and normal row (see reference for source of the simple CSS):

<style type="text/css">

.normalRow
{
background-color:white;/* You can update the background Color to normal Gridview Back Color */
cursor:pointer;/* You can change cursor pointer to default, Pointer etc */
}

.highlightRow
{
background-color:Gray;/* You can change the background Color of the row to whatever color you want. You can also give Hexadecimal color code also */
cursor:pointer;/* You can change cursor pointer to default, Pointer etc */
}

</style>


Here is the CodeBehind for the GridView DataBound event:

protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Attributes.Add("onmouseout", "this.className='normalRow'");
row.Attributes.Add("onmouseover", "this.className='highlightRow'");
}
}
}


Further modifications for multiple class rows can be made by checking the original CssClass (or checking implicitly by rowCount%currentRow for alternating rows) in the CodeBehind and setting the onmouseout event to switch back to that original class. Another example where this may be necessary is with check box rows that can be selected.


References:

No comments: