Highlight a Row in GridView without a postback using ASP.NET and JavaScript

Posted by: Suprotim Agarwal , on 3/9/2008, in Category ASP.NET
Views: 108904
Abstract: Selecting a row in the GridView causes a postback. In order to highlight a row in the GridView, you have to set the ‘SelectedRowStyle’ property which takes effect when the postback occurs. In this article, we will see how to highlight a row without causing a postback, using JavaScript.
Highlight a Row in GridView without a postback using ASP.NET and JavaScript
 
Selecting a row in the GridView causes a postback. In order to highlight a row in the GridView, you have to set the ‘SelectedRowStyle’ property which takes effect when the postback occurs. In this article, we will see how to highlight a row without causing a postback.
We will be using the RowCreated event of the GridView. A GridViewRow object is created for each row in the control before the GridView is rendered. Whenever a row in the GridView gets created, the RowCreated event is fired. Using this event, we can customize the behavior of the GridView. For e.g.: adding client script to the row or customizing the content of the row. Let us see an example where we will be adding some client script to the GridView. I assume that you have some experience of creating data sources and binding controls to it.
Perform the following steps:
Step 1: Create an asp.net website. In the Default.aspx page, add a GridView and a SqlDataSource control to it.
Step 2: Configure the connection of SqlDataSource to point to the Northwind database.  Create query for the Select command to fetch records from the Customer table. The resultant code will look similar to the one given below:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City] FROM [Customers]">
        </asp:SqlDataSource>
The web.config will look similar to the following
<connectionStrings>
            <add name="NorthwindConnectionString" connectionString="Data Source =.;Integrated Security = SSPI; Initial Catalog=Northwind;"/>
           
</connectionStrings>
Step 3: Once the SqlDataSource has been configured, bind the GridView to this data source. Also set ‘AllowPaging’ and ‘AllowSorting’ to true. The mark up will look similar to the following:
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
            <Columns>
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
                <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" SortExpression="ContactTitle" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            </Columns>
        </asp:GridView>
   
    </div>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City] FROM [Customers]">
        </asp:SqlDataSource>
    </form>
</body>
Step 4: Now switch to the design mode and select the GridView. Go to the properties window (F4) and click on the lightning like bolt to display the events of the GridView. Double click the RowCreated event to add the event. The mark up will look similar to the following
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" OnRowCreated="GridView1_RowCreated">
 
...
 
</asp:GridView>
 
Step 5: In the code behind of Default.aspx, add the following code to the RowCreated event handler
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        e.Row.Attributes.Add("onMouseOver", "this.style.background='#eeff00'");
        e.Row.Attributes.Add("onMouseOut", "this.style.background='#ffffff'");       
    }
As you are already aware that the GridView is rendered as a HTML table and each row as  <TR>. In the code shown above, we are using the Attributes property of the AttributeCollection to add extra properties to the <TR> element. The onMouseOver and the onMouseOut events are added that enable the row to change its color whenever the mouse is over a particular row.
Run the application and see the color of the rows changing, that too without a postback!!
Well that was a quick overview of the RowCreated event. You can also use the same event to find the index of the row clicked.  Just use e.Row.DataItemIndex.ToString() to retrieve the selected row index information.
I hope you liked the article and I thank you for viewing it.
If you liked the article, please subscribe to my RSS feed over here.
 
 
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Kanchan on Thursday, March 20, 2008 3:12 PM
Nice coding. But there is a problem, if the table is formatted then header row(Col names) color will be changed. So how to check current row number??
Comment posted by Mageswari on Saturday, March 29, 2008 7:27 AM
Wonderful article
Comment posted by Gufran Sheikh on Friday, April 25, 2008 5:31 PM
you can find lots of tutorials on highlighting a row on mouse hover but if you want to make your tutorial different one then take a try to use background images on mouseover and on mouseout instead of simple color ;) if you do it (may be possible) then let me know. best of luck :)
Comment posted by Krishna on Saturday, April 26, 2008 3:21 AM
Nice one Dude
Comment posted by nirvan on Wednesday, June 18, 2008 12:18 PM
To Kanchan:  Use    

itemtype = e.Item.ItemType = ListItemType.Item OR e.Item.ItemType = ListItemType.AlternatingItem
Comment posted by Manav Inder on Saturday, July 5, 2008 1:36 AM
This code rocks and break the limitations, Thanks
Comment posted by shafeer on Saturday, October 18, 2008 8:00 AM
This is very good article pls send following sollutions

1 .Formating numeric value of label text to number
2 .How to add a row below the header row of a grid view in asp.net

byeeee shafeer
Comment posted by kyi kyi on Tuesday, October 21, 2008 10:30 PM
thanks for your coding.although it's not identically with mine,i got the idea to add onRowCreated event in Desing.. and mine is ok.. now..
Comment posted by Simon on Sunday, March 8, 2009 11:29 AM
Nice article and I also read your other one where you achieve this result in Jquery too BUT are you aware that it can be done in CSS with the css pseudo class 'hover'

I tried the CSS method in IE7 and FF3 and it works. I'd take a guess thats in fine in IE6 as I remember doing it ages ago in that browser. I think this way might be better than (a) hardcoding colour values in your code-behind file or (b) inside that Jquery block you use in your other article, the colour info is in the CSS where it should be. Just a thought, I might be missing something ...

e.g.
        tbody tr:hover
        {
           background-color: #788aee;
        }
        
        tbody tr:hover td, tbody tr:hover td a
        {
           color: White;
        }
Comment posted by Suprotim Agarwal on Tuesday, March 10, 2009 8:16 AM
Simon: Very true. CSS rocks! However many a times you want to use jquery/javascript to take decisions while performing operations like highlight. So the intention is just to demonstrate how to use different technologies jquery to do the same task. I recently blogged about a few other ways of making use of the jquery in a GridView over here
http://www.dotnetcurry.com/ShowArticle.aspx?ID=259
Comment posted by sunil on Thursday, February 18, 2010 8:19 AM
This is good. but
I want to get the particular row value whereever the mouse hover in the gridview and I want to display that value in the label below. How can I do this?
Thanks
Comment posted by pallavi seth on Friday, July 16, 2010 2:06 AM
check this site also for changing grid view color
http://gridviewrowcolor.blogspot.com/
Comment posted by dzie25 on Friday, January 28, 2011 1:53 AM
To Sir To Kanchan:

        If (e.Row.RowIndex) >= 0 Then
            e.Row.Attributes.Add("onMouseDown", "this.style.background='#eeff00'")
            e.Row.Attributes.Add("onMouseOut", "this.style.background='#ffffff'")
            e.Row.Attributes.Add("onMouseOver", "this.style.background='black'")
        End If
Comment posted by Pratul on Thursday, February 17, 2011 9:20 AM
@Kanchan.
You can check if the current row is a RowType = DataRow and not a header.
Check out the following:
Private Sub GVCoords_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVCoords.RowCreated
   If e.Row.RowType = DataControlRowType.DataRow Then
      e.Row.Attributes.Add("onMouseOver", "this.style.background='#EEFF00'")
      e.Row.Attributes.Add("onMouseOut", "this.style.background='#FFFFFF'")
   End If
End Sub
Comment posted by Parisa on Wednesday, February 1, 2012 2:06 AM
Nice job!!!thanks.
Comment posted by nebojsa on Tuesday, December 11, 2012 2:56 AM
You can do this while perform RowDataBound.

Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
e.Row.Attributes.Add("class", "rowSel")
End Sub

rowSel is defined in css.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel