Tuesday, August 26, 2008

Highlighting GridView Rows using C# .NET with Javascript

I've been wondering for some time how to do that neat trick of changing the color of a data grid row when the mouse hovers over it. I'm sure its just a Javascript routine, but how do I integrate it with my C# .NET code and not really have to now Javascript (yes, I don't know how to write Javascript).

I did the usual Google search and found several answers. I tried them but could not seem to get it to work. Some of the explanations talk about trapping the ItemDataCreated event, but Visual Studio 2005 does not seem to have that event for the GridView object.

After a while, I realized that my search phrase in Google is wrong. I've been looking for ways to change the highlighting of a DataGrid row, when instead, I should have been looking for ways to change the highlight of a GridView row. The GridView is a newer construct introduced in VS2005 and is supposed to be more flexible than the older DataGrid model. So I reconstructed my query and found the answer I was looking for:
protected void TxnGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover",
"this.orig=this.style.backgroundColor;this.style.backgroundColor='#cccccc'");
e.Row.Attributes.Add("onmouseout",
"this.style.backgroundColor=this.orig;");
}
}

Some programmers suggest using the styles and doing something like:

e.Row.Attributes.Add("onMouseOver", "this.className='highlightrow'");
e.Row.Attributes.Add("onMouseOut", "this.className='normalrow'");

I can't seem to get it to work, however. The previous one worked better for me. Its not as elegant as the second one, admittedly. It would require changing the code just to change the background color, whereas the latter implementation only need a change in the stylesheet.

No comments: