Create new account I forgot my password    

Using ASP.NET and jQuery to Highlight a Row in GridView without a PostBack
Rating: 23 user(s) have rated this article Average rating: 3.9
Posted by: Suprotim Agarwal, on 12/30/2008, in category "jQuery and ASP.NET"
Views: this article has been read 57023 times
Abstract: In one of our previous articles, we had seen how to highlight a row in GridView using JavaScript without causing a postback. In this article, we will simplify the approach using jQuery, without the need of handling any of the GridView events.



Using ASP.NET and jQuery to Highlight a Row in GridView without a PostBack
 
In one of our previous articles Highlight a Row in GridView without a postback using ASP.NET and JavaScript, we had seen how to highlight a row in GridView without causing a postback. We had made use of the GridView ‘RowCreated’ event and added the onMouseOver and the onMouseOut events to enable the row to change its color whenever the mouse is over a particular row.
In this article, we will simplify the approach using jQuery, without the need of handling any of the GridView events. If you are new to jQuery, I would strongly suggest you to check this: Using jQuery with ASP.NET - A Beginner's Guide
Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.
Right click the Scripts folder > Add Existing Item > Browse to the path where you downloaded the jQuery library (jquery-1.2.6.js) and the intellisense documentation (jquery-1.2.6-vsdoc.js) > Select the files and click Add.
Now drag and drop the jquery-1.2.6.js file from the Solution Explorer to the <head> section of your page to create a reference as shown below:
<head runat="server">
    <title></title>
    <script src="Script/jquery-1.2.6.js" type="text/javascript"></script>
   
Drag and drop a SqlDataSource Control to the Default.aspx page and use the wizard to connect to the Northwind database. Select the CustomerId, CompanyName, ContactName, Address and City from the Customers table. The wizard will also prompt you to save the connection string in the web.config file. Choose to do so. The design code will look similar to the following:
           <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
            </asp:SqlDataSource>
An entry will be added to the web.config file as shown below:
 <connectionStrings>
    <add name="NorthwindConnectionString"
         connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
 </connectionStrings>
Now add a GridView control to the page and using the smart tag, select the DataSource to be SqlDataSource1 in the GridView tasks panel. Using the same panel, click on the Enable Paging and Enable Sorting checkboxes. The source will look similar to the following. Observe that the DataKeyNames is set to ‘CustomerId’, that is the primary key of the Customers table
       <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="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            </Columns>
        </asp:GridView>
To enable row highlighting, we will follow two approaches. In the first approach we will make the GridView generate the <thead> so that the header is not highlighted. GridView by default generates the header as a <th> inside a <tr>.
First Approach
All we need to do is to add the following lines of jQuery code in the <head> section of the page
   <script type="text/javascript">
 
        $(document).ready(function() {       
            $("table tr:has(td)").css({ background: "ffffff" }).hover(
                function() { $(this).css({ background: "#C1DAD7" }); },
                function() { $(this).css({ background: "#ffffff" }); }
                );
        });
    </script>
We have used the ‘hover’ event in jQuery. More about the hover event can be read over here.
In order to prevent the Column Header to be highlighted, use the following code to generate the <thead>:
C#
        if (GridView1.Rows.Count > 0)
        {
            GridView1.UseAccessibleHeader = true;           
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
            //GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
        }
VB.NET
            If GridView1.Rows.Count > 0 Then
                  GridView1.UseAccessibleHeader = True
                  GridView1.HeaderRow.TableSection = TableRowSection.TableHeader
                  'GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
            End If
The code above generates the <thead> tag for us instead of generating the <th> in the <tr> (which is the default html generated). I have on purpose commented out the FooterRow code, since it gives me a strange error. I have used a second approach to solve that to a certain extent. Read on.
Second Approach
If you do not want to write all that code to generate the <thead> and then filter it out, here's a pure jQuery solution to it. I found this solution in a jQuery forum where a user had posted a similar issue. Karl Swedberg proposed the solution as given below. Add the following lines of jQuery code in the <head> section of the page:
<script type="text/javascript">
$(document).ready(function() {
$("tr").filter(function() {
return $('td', this).length && !$('table', this).length
}).css({ background: "ffffff" }).hover(
function() { $(this).css({ background: "#C1DAD7" }); },
function() { $(this).css({ background: "#ffffff" }); }
);
});
That’s it. Run the application and you will observe that the row gets highlighted when the user hovers the mouse on a row.
jQuery Highlight
I hope this article was useful and I thank you for viewing it.


Give me a +1 if you think it was a good article. Thanks!





You Also Might Like



About the Author
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, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal





Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by dec853 on Tuesday, December 30, 2008 6:01 PM
hovering highlights all rows one at a time until all rows are highlighted including the header row.
Comment posted by John Boker on Thursday, January 01, 2009 9:48 AM
This method will highlight any row of any table on the page, if that's not what's wanted you might want to wrap the gridview in a <div class="gridview"> or something then use $(".gridview table tr").css(...) for the row highlighting.
Comment posted by Suprotim Agarwal on Tuesday, January 06, 2009 1:02 AM
dec853, John: Thanks for your comments. To avoid highlighting the header row, there is a simple solution. Just make the GridView generate <thead> instead of the <th>
by using the following line of code:

GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
Comment posted by http://www.java2s.com/Code/JavaScript/GUI-Components/Checkboxtreenodecheckeduncheckedgetthecheckeditems.htm on Friday, January 09, 2009 5:56 AM
http://www.java2s.com/Code/JavaScript/GUI-Components/Checkboxtreenodecheckeduncheckedgetthecheckeditems.htm
Comment posted by http://www.java2s.com/Code/JavaScript/GUI-Components/Checkboxtreenodecheckeduncheckedgetthecheckeditems.htm on Friday, January 09, 2009 5:56 AM
http://www.java2s.com/Code/JavaScript/GUI-Components/Checkboxtreenodecheckeduncheckedgetthecheckeditems.htm
Comment posted by Janko on Saturday, January 17, 2009 5:38 AM
Fantastic! I was searching for something like this and both your solutions work well. I find a problem though when I hover over the pager control. Any solutions?
Comment posted by Muhammad Iqbal on Sunday, January 18, 2009 12:27 PM
This functionality can be done very easly as below mentioned.
At gridview row databound event determine the row type and register the javascript code for that row.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            #region HighLight Row on MouseOver

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
               e.Row.Attributes.Add("onMouseOver", "Highlight(this)");
               e.Row.Attributes.Add("onMouseOut", "UnHighlight(this)");
            }
            #endregion
        }
Add it in Page html file...
<script type="text/javascript">
    
     /***** HightLight Gridview Rows on MouseOver ****/
     function Highlight(row)
     {
        row.style.backgroundColor = '#e7f2fd';
     }
     function UnHighlight(row)
     {
        row.style.backgroundColor ='#FFF';        
     }
</script>

lool enjoy it..
Comment posted by John Harcourt on Tuesday, February 24, 2009 4:29 PM
Nice. However, my gridview has alternating colors for the odd rows. How can this work, maintaining the original background of the rows?
Comment posted by KansasCoder on Wednesday, March 18, 2009 11:09 AM
How could something like this be donw when the original grid uses Alternating Row  Styles?
Comment posted by KansasCoder on Wednesday, March 18, 2009 11:11 AM
It would just call a jquery function that would capture the initial rowcolor onmouseover before changing it and then pass that to the onmouseout.
Comment posted by atlantic on Monday, March 23, 2009 3:10 AM
i have a question,when i use Repeater or DataList,i think this way could not do that,how can i do that,thank you very much.
Comment posted by jimmyc on Monday, March 23, 2009 5:55 PM
Is anyone else experiencing this failing after a page postbacks?
Comment posted by Suprotim Agarwal on Tuesday, March 24, 2009 2:58 AM
Jimmyc: Yes the rows will no longer remain highlighted if there is a postback. That's the default behavior. To persist the highlight during a postback, you would need to keep track of the rows that were highlighted (in a collection) and then re-highlight them using code.
Comment posted by jimmyc on Tuesday, March 24, 2009 9:35 AM
If you are experiencing a problem with the jquery not working after a postback try this code instead for the second approach:
[code]
    protected void Register_JQueryScripts()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(@"<script type=""text/javascript"">");
        sb.Append(@"function pageLoad() {");
        sb.Append(@"$(""#gridView table tr"").filter(function() {");
        sb.Append(@"return $('td', this).length && !$('table', this).length");
        sb.Append(@"}).css({ background: ""ffffff"" }).hover(");
        sb.Append(@"function() { $(this).css({ background: ""#C1DAD7"" }); },");
        sb.Append(@"function() { $(this).css({ background: ""#ffffff"" }); }");
        sb.Append(@");");
        sb.Append(@"}");
        sb.Append(@"</script>");

        if (!ClientScript.IsStartupScriptRegistered("JSScript"))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb.ToString());
        }
    }
[/code]
Comment posted by Suprotim Agarwal on Thursday, March 26, 2009 8:47 AM
jimmc: Thanks. I will try this out!
Comment posted by Jerry Hong on Thursday, May 14, 2009 9:46 PM
First, thanks your post, it's useful for me, recently, I'm just finding some simple code to do the 'Height' effect, and I found you're using the 'table' DOM factor, but I just want the GridView or someone type of control to do this, but not all, I think it will have some problems sometimes. I'm interesting in the 'Skin', it seems can do so, but need to add some custom event to GridView, like 'onmouseover' etc., and that's the problem, event I have correctly add some script but it seems the effect is strange. Do anyone have some other good idea? Thanks in advance.
Comment posted by Nimesh on Monday, July 06, 2009 5:32 AM
That's a nice code. I used jQuery for the first time and I liked it. Thanks.
Comment posted by Nimesh on Monday, July 06, 2009 6:37 AM
I'm using the second method mentioned above. How can we restrict this hover functionality only for a specific table, with the id gdReports?
Comment posted by Suprotim Agarwal on Friday, July 17, 2009 2:55 AM
Nimesh: You can select the table using $('#gdReports')
Comment posted by lavanya on Sunday, December 20, 2009 11:28 PM
very useful
Comment posted by Aleena Leon on Friday, April 16, 2010 9:01 AM
Will u help me to select more than one row at a time.

Thank U!
Comment posted by Nilay on Saturday, July 24, 2010 4:25 AM
Hey,pal....
thanks a lot for this post..
really amazing...

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