Add Row Highlighting to your GridView

By | October 25, 2007

I’m going to show you a quick and easy way that hopefully will help liven up your plain old GridView.

kick it on DotNetKicks.com

Before I begin, I want to apologize for my real lack of creativity in the intro. Creative writing was never one of my strong points.

Step 1: Since we are going to be using a GridView, we need a collection of something to populate the control. For this example I’ve created a simple Person class, which has a FirstName, LastName, PhoneNumber and PostalCode property, an empty constructor, and another constructor that takes in a value for each of the properties, and lastly, there’s one static method called GetPeople() which returns a List<Person>. The class can be found here.

Step 2: Next, I created an empty aspx page, and added an ObjectDataSource to retrieve the List of Person from Person.GetPeople(), and then added a simple GridView with its DataSourceId set to the same name as the Id of the ObjectDataSource (dsPerson).

I’ve also added a bit of styling to the GridView so that it wouldn’t be so blah.

<form id="form1" runat="server">
  <div>
   <asp:objectdatasource id="dsPerson"
typename="Person"
selectmethod="GetPeople"
runat="server" />
 
<asp:GridView id="gdvPeople"
 datasourceid="dsPerson"
 bordercolor="black" 
borderstyle="solid"
borderwidth="1"
width="500px"
cellpadding="5"
headerstyle-font-bold="true"
headerstyle-backcolor="Navy"
headerstyle-forecolor="white" 
runat="server"> 
</asp:GridView> 
</div> 
</form>

Step 3: For the row highlighting to work, we need to be able to detect when the user places their mouse over, and takes their mouse off of a row. To do this we will need to go into the Code Beside ("Code Behind" is so ASP.Net 1.1) , and add JavaScript to each row when it’s created. The GridView event that we are looking for is RowDataBound.

To accomplish this, in the RowDataBound event we need to determine whether the row that is being created is a DataControlRowType.DataRow and ignore all of the others (EmptyDataRow, Footer, Header, Pager and Seperator), and add a "onmouseover" and "onmouseout" attribute to the row, and a JavaScript method to call.

protected void gdvPeople_RowDataBound
(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "Highlight_On(this);");
e.Row.Attributes.Add("onmouseout", "Highlight_Off(this);");
}
}

 

Step 4: This is probably the shortest step. For the RowDataBound to work, we need to tell the GridView to use it. Go back into your aspx page, and add onrowdatabound="gdvPeople_RowDataBound" to the GridView. This can be added anywhere in the opening tag. I’ve added it just above the runat.

<asp:GridView id="gdvPeople" 
datasourceid="dsPerson"
 bordercolor="black"
 borderstyle="solid"
 borderwidth="1"
width="500px"
cellpadding="5"
 headerstyle-font-bold="true"
headerstyle-backcolor="Navy" 
 headerstyle-forecolor="white"
 onrowdatabound="gdvPeople_RowDataBound"
 runat="server">
</asp:GridView>

Step 5: If you tried to run it in its current state and ran your mouse over the rows, your browser of choice will probably tell you that there is a JavaScript error. It’s a good thing if you get the error. It means that your RowDataBound worked, and added the JavaScript to each row.

Don’t worry, I won’t bore you for much longer, we’re almost done.

Step 6: Let’s fix that JavaScript error that you should have gotten. Go back to your aspx page, and in the head section add the following code.

<script type="text/javascript">
function Highlight_On(obj)
{
if(obj != null)
{
obj.originalBgColor = obj.style.backgroundColor;
obj.style.backgroundColor='#DBE7F6';
}
}
 
function Highlight_Off(obj)
{
if(obj != null)
{
obj.style.backgroundColor = obj.originalBgColor;
}
}
</script>

 

If you remember in Step 3 (if you don’t remember, scroll up), we added a "onmouseover" and "onmouseout" attribute to each row, and set the values to "Highlight_On(this)" and "Highlight_Off(this)".

When the mouse is positioned above a row, the Highlight_On() method is called, which is passed the current row. The method then checks to see if the object being passed in is null or not, and if not, it stores the current backgroundColor (obj.style.backgroundColor) into a "pseudo property" and then changes the row’s backgroundColor to #DBE7F6.

When the mouse moves off of the row, the Highlight_Off() method is called which is again passed the row that it. It then checks if the object being passed in is not null, and if it isn’t, it then sets the row’s backgroundColor to the value we stored into the "pseudo property".

Now save the changes and re-run the page. If all goes well, you should see something very similar to the image below.

Are we done yet? Well, we could be. However, I don’t really like the idea of placing my background colors into the JavaScript. I would prefer to have it in an external style sheet, so that I can easily modify it in one place, or change it from theme to theme.

For this example I’m just going to place the styling in a <style></style> in the head section of the page. I’m also going to make a small addition to the GridView to give each row a cssclass name.

Add the following into your GridView:

<rowstyle cssclass="row1" />

<alternatingrowstyle cssclass="row2" />

Now for the CSS styling. Add this to the top of the head section:

<style type="text/css">
.row1 {background-color: White;}
.row1HL {background-color: #DBE7F6;}
.row2 {background-color: #EEEEEE;}
.row2HL {background-color: #e1e1e1;}
</style>

All that I’ve done here is say that all rows with a cssclass name of row1 should have a background color of White, and all rows with a cssclass name of row2 should have a background color of #EEEEEE, which is a light gray.

The row1HL and row2HL class names are for the rows when the mouse is positioned over them (HL is for ‘HighLight’).

Now one small modification to our JavaScript, and that should be it. Instead of storing the original background color, we’ll store the original CSS class name. This approach is a bit simpler and has less code than checking if the class name is "row1" or if it’s "row2", and then changing the name, then doing the opposite for the mouseout.

Replace your existing JavaScript with this one:

function Highlight_On(obj)
{
if(obj != null)
{
obj.originalClassName = obj.className;
obj.className = obj.className + 'HL';
}
}
 
function Highlight_Off(obj)
{
if(obj != null)
{
obj.className = obj.originalClassName;
}
}

 

Once that is done, this is what you should get.

The left side is with the row1 being highlighted, and the right side is the row2 being highlighted. If you didn’t get something similar, don’t worry, you can download the complete source from here. I’ve also added an example with a Repeater.

If you have any comments, suggestions or question, feel free to leave a comment.

15 thoughts on “Add Row Highlighting to your GridView

  1. carlj Post author

    btw, if you thought that this was “Nifty neat-o”, wait till my I’m done the Theming post, which I’m working on now … that I think, is Nifty neat-o^10

  2. shahab

    How about just calculating if the rowindex is even or odd then change the back colour to the original alternating style color. It saves all the client side html/javascript.

    If e.Row.RowType = DataControlRowType.DataRow Then

    e.Row.Attributes.Add(“onmouseover”, “this.style.backgroundColor=’ivory’;”)
    If CInt(e.Row.RowIndex) Mod 2 = 0 Then ‘the row is even
    e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=’transparent’”)
    Else
    e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=’whitesmoke’”)
    End If
    End If

  3. carlj Post author

    but then you’re placing your styling in your code.
    and what if you have another page that uses the gridview, then you need to rewrite your calculations again.

  4. FelixPerro

    Thanks. Creating a pseudo-property was clever!

    BTW, you don’t really need a Highlight_Off() function. Within Highlight_On()yYou can just compare the row’s current color against the highlighted color to determine if it’s highlighted. Well, that works for me and keeps the code terse.

    Thanks again.

  5. FelixPerro

    …OK nevermind my last suggestion. That only works in IE. In other browsers you can still do it but requires some different comparison methods, which would create more code, blah, blah, blah.

    Anywho, thanks.

  6. carlj Post author

    FelixPerro, to compare the colours, your code needs to know the default background color for a regular row and an alternating row, and also know the highlight colour for both of the rows too.

    It’s best if there is a separation between code and design. By using the “pseudo property”, your code knows nothing about the design, so the design is easy to change. Also, by using CSS you can apply other styles such us font-weight, color, text-decoration …. to the row. To do this in code would be too much of a pain in the you-know-what.

  7. Gufran Sheikh

    ok i have a condition you didn’t describe one condition when any row is selected then it should left that selected row i.e. dont apply row hover css to it and another one is how we handle the row click event. i have solution but i want your code as may be my code is not good. thnx for the post it also helps other.

  8. carlj Post author

    Hey Gufran …
    For part 1 of your question, you want to be able to use the row highlighting, BUT, when a row is selected, then keep the default row colour?

    The only way that I can see it being done, is to change the background color back to the default, after the user clicks on the row. Because the rows have “onmouseover”, “Highlight_On(this)” is called as soon as the mouse touches the row.

    For part 2, are you wondering how to handle if the user clicks anywhere in the row? Or when the user clicks on some sort of a Select button, or a link? Also, what do you want to do when the user clicks on a row? Redirect to another page? Process some information?

  9. Pingback: Carl J » January 2008 Stats

  10. Pingback: Carl J » February 2008 Stats

  11. Abid Farooq Bhutta

    Thanks Man you are the great person for the date

  12. Gurjit Singh

    beautiful and very nicely explained, thanks Carl :)

Leave a Reply

Your email address will not be published. Required fields are marked *