How to highlight a GridView's row on hover

4.5 (6 votes)

As the user hovers over each row, it becomes highlighted, with the help of a small amount of javascript.

The javascript:

    
function highlight(tableRow, active)
{
if (active)
{
tableRow.style.backgroundColor = '#cfc';
}
else
{
tableRow.style.backgroundColor = '#fff';
}
}

function link(Url)
{
document.location.href = Url;
}

The Databound event of the GridView:

protected void GridView1_DataBound(object sender, EventArgs e)
{
  foreach (GridViewRow grow in GridView1.Rows)
  {
    grow.Attributes["onmouseover"] = "highlight(this, true);";
    grow.Attributes["onmouseout"] = "highlight(this, false);";
    HttpResponse myHttpResponse = Response;
    HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
    grow.Attributes.AddAttributes(myHtmlTextWriter);
  }
}

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 18268

2 Comments

- Scott

What is the advantage of this method over just using grow.Attributes.Add("onmouseover","highlight(this,true);"); ?

- Mike

@Scott

In some browsers, unless you reset the colour using the onmouseout event, it doesn't change back.

Recent Comments

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...

Harris Boyce 04/07/2017 04:17
In response to Razor Pages - The Elevator Pitch
As a developer of a couple "trivial" web pages applications used by non-profits that wouldn't have I...

Cyrus 28/06/2017 20:25
In response to Razor Pages - Getting Started With The Preview
.net core 2.0 preview 2: <a...

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...