GridView Row Color Change On MouseOver
A need little feature that can jazz up any Gridview is adding a color-change when the mouse is over a row. Thanks to our good friend (or nemesis depending on your point of view) JavaScript, setting up such a thing is only a few lines of code away.
First, setup your Gridview. I’m sure you’ve done this thousands of times, so I won’t bore you with the code of setting up or populating this guy. Add an OnRowCreated event to your GridView. This will run for each row created in your Gridview and allow you to add the necessary JavaScript.
<asp:GridView ID="gvNews"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="BlogID"
DataSourceID="SqlDataSource1"
AllowPaging="True"
PageSize="20"
BorderStyle="None"
BorderWidth="0px"
Width="100%"
CellPadding="10"
CellSpacing="4"
ShowHeader="False"
OnRowCreated="gvNews_OnRowCreated"
>
</asp:GridView>
In your code behind, you will need to add a handler for this event. For my example, I’m using alternating background colors on rows (which you should do too, it makes things so much more readable). This causes me to add a couple extra lines so that I make sure I’m setting my rows back to the correct color on MouseOut.
protected void gvNews_OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Alternate)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#FFFFE1';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#f7fff8';");
}
else
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#FFFFE1';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#eefef0';");
}
}
}
That’s all there is to it. If you want to see this in action, check out the news section on the main page here.
There is room for improvement here… you could assign a CSS class instead of hard coding the colors. I believe there is also a way you could also get the background color that is assigned in the RowStyle/AlternatingRowStyle section. That would make this much more portable.
This article has been view 21364 times.
|