How to add a row click event to a gridview

So I ran across the problem of I need a web page to do something if a user clicked a row in a grid.
It wasn’t going to work for the user to click a button, the whole row had to be clickable.

Adding a row data bound event solved the problem.
I also change the background color on mouse over (and mouse out).

When the user clicks the row they get redirected to a page (with a query string parm so I know what row they clicked on).


   1: protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)

   2: {

   3:     if (e.Row.RowType == DataControlRowType.DataRow)

   4:     {

   5:         e.Row.Attributes.Add("onmouseover", "'#ceedfc'");

   6:         e.Row.Attributes.Add("onmouseout", "''");

   7:         e.Row.Attributes.Add("style", "cursor:pointer;");

   8:         e.Row.Attributes.Add("onclick", "location='detail.aspx?id=" + e.Row.Cells[0].Text + "'");

   9:     }

  10: }


Change row color in Gridview on mouse over

If you have the need to change the row color of a row in a gridview when you mouse over (and mouse out) you can add some code to the RowDataBound event.

Here is a sample:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

//Only apply to data rows
if (e.Row.RowType == DataControlRowType.DataRow)

//Add mouse over event to change row background color
e.Row.Attributes.Add(“onmouseover”, “’Yellow'”);

//Add mouse out event to change row background color back to white
e.Row.Attributes.Add(“onmouseout”, “”);



Here is the blog site where I found this sample.