Few months ago I wrote an article about how you can change the row color of the GridView control when the user puts his mouse over the row. In this article I will create the same scenario and solve it in a different way.

Introduction:

Few months ago I wrote an article about how you can change the row color of the GridView control when the user puts his mouse over the row. In this article I will create the same scenario and solve it in a different way.

Populating the GridView Control:

The first task is to populate the GridView control with some data. Take a look at the method below which is used to populate the GridView.

private void BindData()

{

string connectionString = @"Server=localhost;Database=TaskDatabase;Trusted_Connection=true";

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Contacts", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds);

MyGridView.DataSource = ds;

MyGridView.DataBind();

}

Attaching the OnMouseOver event to the GridViewRow:

The next task is to attach the onmouseover event to the GridView rows. The best place to do this is the RowCreated event of the GridView control which is fired every time a row is created. Take a look at the method below:

protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e)

{

string onmouseoverStyle = "this.style.backgroundColor='blue'";

string onmouseoutStyle = "this.style.backgroundColor='#@BackColor'";

string rowBackColor = String.Empty;

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

{

if (e.Row.RowState == DataControlRowState.Alternate)

rowBackColor = MyGridView.AlternatingRowStyle.BackColor.Name.Remove(0, 2);

else rowBackColor = MyGridView.RowStyle.BackColor.Name.Remove(0, 2);

e.Row.Attributes.Add("onmouseover", onmouseoverStyle);

e.Row.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor",rowBackColor));

}

}

The first thing I did is to create the styles of the onmouseover and onmouseout. Next I check that if the row is of DataControlRowType.DataRow if it is then I check that if the row is an alternating row. If the row is alternate row then I get the back color from the AlternatingRowStyle.BackColor property. If the row is not the alternating row then I simply get the row style. At the end I attach the attributes to the row by using e.Row.Attributes.Add(key,value)  method.

Special Note:

The above method will perform correctly if you are defining the colors in the form of the color codes like #df45600 and so on. So, use the color codes in the HTML view of the code instead of the color name and the above example will work correctly.

I hope you liked the article, happy coding!