Changing GridView Row Color OnMouseOver
By AzamSharp
Views: 16512

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!

 

By AzamSharp




Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: fix color problem
Name: Nuno Costa
Date: 3/12/2007 11:18:01 AM
Comment:
Changing the code to the following will make it work for all colors, even named colors.


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 = System.Drawing.ColorTranslator.ToHtml(MyGridView.AlternatingRowStyle.BackColor).ToString();

else rowBackColor = System.Drawing.ColorTranslator.ToHtml(MyGridView.RowStyle.BackColor).ToString();

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

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

}

}


happy programing

NC
Subject: RE: Fix Color Problem
Name: AzamSharp
Date: 3/12/2007 8:34:26 PM
Comment:
Thanks! :)
Subject: Must include RowStyle tags
Name: developerz
Date: 7/18/2007 11:42:54 PM
Comment:
Just a note, that you must include the AlternatingRowStyle tag, and RowStyle tag in your GridView on the asp.net page.

For example:

Subject: Gridviewcolor change
Name: vivekanandan
Date: 8/1/2007 12:23:51 AM
Comment:
Dear sir,

how r u?
this method is very useful and then suddenly run for download format is exallent
thank u sir
regards
vivekanandan.R
Subject: Selectable Rows
Name: Scott
Date: 8/15/2007 3:24:34 PM
Comment:
Very nice code! I've been trying to do this for weeks, but could never get it to work until I found your code. - Thanks.

As an enhancement add the following 2 lines to select rows with mouse click:

Dim onmouseoverStyle As String = "this.style.backgroundColor='#ffffdd'; style.cursor='hand'"

(Note: add next line to end of original code)

e.Row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(Me.GridView1, "Select$" + e.Row.RowIndex.ToString)

- Enjoy!
Subject: Thanks!
Name: Roger
Date: 9/2/2007 12:17:17 AM
Comment:
@NC

Your code was just what I needed. Thanks so much!
Subject: how to change selected row's color
Name: shahid
Date: 11/1/2007 12:08:47 AM
Comment:
Scott
can you explain how to change selected row style even i select it from check box have any idea because when mouseout color back to it orignal.
Subject: Font color
Name: Jeff
Date: 11/28/2007 12:21:32 PM
Comment:
Great piece of code.
Any way to make the font change color as well?

-Thanks!
Subject: Autoformat
Name: Agnes
Date: 1/2/2008 3:42:37 AM
Comment:
1.coding works only for the gridview Autoformat slate. when i used otherthan slate it doesn't works.help me please
2.Can u explain the use of "Select$" in the following line:

e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
Subject: Mouseover effect problem in gridview is solved
Name: Varun Thakur
Date: 2/19/2008 4:10:58 AM
Comment:
Cool article

Thanx:-)
Subject: Hi
Name: Suresh Murugan
Date: 2/25/2008 9:23:13 PM
Comment:
Nice Article..
Subject: further enhancement?
Name: AlBudz
Date: 4/23/2008 1:22:30 PM
Comment:
I thank you all very much for the code here... It's helped a lot!

I have modified it a bit more and made it more 'generic' so that you can drop the code onto the code-behind once and set the PreRender event of any GridView on the page to point to it and it will work -- even if the GridViews use different formatting schemes.

Thanks again!

protected void gvRowSelect_PreRender(object sender, EventArgs e)
{
// Set the MouseOver background color to be the same as the SelectedRow background color
// Change this if you need a different MouseOver color.
string onmouseoverStyle = string.Format("this.style.backgroundColor='{0}'", System.Drawing.ColorTranslator.ToHtml(((GridView)sender).SelectedRowStyle.BackColor).ToString());

// Set the MouseOut background color with a variable (used in the 'if' statement below)
string onmouseoutStyle = "this.style.backgroundColor='@BackColor'";
string rowBackColor = string.Empty;

for (int i = 0; i < ((GridView)sender).Rows.Count; ++i)
{
GridViewRow gvr = ((GridView)sender).Rows[i];
if (gvr.RowType == DataControlRowType.DataRow)
{
// Set the MouseOut background color based on the RowState's style.
if (gvr.RowState.ToString() == "Normal")
rowBackColor = System.Drawing.ColorTranslator.ToHtml(((GridView)sender).RowStyle.BackColor).ToString();
else if (gvr.RowState.ToString() == "Alternate")
rowBackColor = System.Drawing.ColorTranslator.ToHtml(((GridView)sender).AlternatingRowStyle.BackColor).ToString();
else
rowBackColor = System.Drawing.ColorTranslator.ToHtml(((GridView)sender).SelectedRowStyle.BackColor).ToString();

// Add the background color effects OnMouseOver and OnMouseOut to the row
gvr.Attributes.Add("onmouseover", onmouseoverStyle);
gvr.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor));

// Make the row 'clickable'
gvr.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(((GridView)sender), string.Format("Select${0}", gvr.RowIndex.ToString())));
}
}
} // end - gvRowSelect_PreRender()
Subject: Another way using hex color values and deals with no alternating row color
Name: klubell
Date: 7/3/2008 7:47:50 AM
Comment:
protected void grdStations_RowCreated(object sender, GridViewRowEventArgs e)
{
string sColor = System.Drawing.Color.Gainsboro.ToArgb().ToString("x").Substring(2);
string onmouseoverStyle = "this.style.backgroundColor='#" + sColor + "'";
string onmouseoutStyle = "this.style.backgroundColor='#@BackColor'";
string rowBackColor = String.Empty;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Alternate && grdStations.AlternatingRowStyle.BackColor.ToArgb() != 0)
rowBackColor = grdStations.AlternatingRowStyle.BackColor.ToArgb().ToString("x").Substring(2);
else
rowBackColor = grdStations.RowStyle.BackColor.ToArgb().ToString("x").Substring(2);
//if (e.Row.RowState == DataControlRowState.Alternate)
// rowBackColor = grdStations.AlternatingRowStyle.BackColor.Name.Remove(0, 2);
//else
// rowBackColor = grdStations.RowStyle.BackColor.Name.Remove(0, 2);
e.Row.Attributes.Add("onmouseover", onmouseoverStyle);
e.Row.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor));
}
}
Subject: Problem with firefox
Name: Rameshsundar
Date: 7/6/2008 5:20:05 AM
Comment:
It doesn't work in firefox for me...





Join WebHost4Life.com







Copyright GridViewGuy 2007-2008