Click here to Skip to main content
15,881,600 members
Articles / Web Development / ASP.NET
Tip/Trick

FAQ: Highlight GridView Row on Click and Retain Selected Row on Postback

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
1 Jul 2016CPOL2 min read 12.9K   3   2
A quick example on how to implement GridView row highlighting and retain selected row on postbacks.

Introduction

Many years ago I’ve written a simple demo about “Highlighting GridView Row on MouseOver”. I’ve noticed many members in the forums are asking how to highlight row in GridView and retain the selected row across postbacks. So I’ve decided to write this post to demonstrate how to implement it as reference to others who might need it.

In this demo, I’m going to use a combination of plain JavaScript and jQuery to do the client-side manipulation. I presumed that you already know how to bind the grid with data because I will not include the codes for populating the GridView here. For binding a GridView, you can refer this post: Binding GridView with Data the ADO.Net Way or this one: GridView Custom Paging with LINQ.

Using the code

Now let’s implement the highlighting of GridView row on row click and retain the selected row on postback.  For simplicity I set up the page like this:

ASP.NET
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>You have selected Row: (<asp:Label ID="Label1" runat="server" />)</h2>
    <asp:HiddenField ID="hfCurrentRowIndex" runat="server"></asp:HiddenField>
    <asp:HiddenField ID="hfParentContainer" runat="server"></asp:HiddenField>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Trigger Postback" />
    <asp:GridView ID="grdCustomer" runat="server" AutoGenerateColumns="false" 
        onrowdatabound="grdCustomer_RowDataBound">
        <Columns>
            <asp:BoundField DataField="Company" HeaderText="Company" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="Title" HeaderText="Title" />
            <asp:BoundField DataField="Address" HeaderText="Address" />
        </Columns>
    </asp:GridView>
</asp:Content>

Note: Since the action is done at the client-side, when we do a postback like (clicking on a button) the page will be re-created and you will lose the highlighted row. This is normal because the server doesn't know anything about the client/browser not unless if you do something to notify the server that something has changed. To retain the settings we will use some HiddenFields control to store the data so that when it postback we can reference the value from there.

Here are the JavaScript functions below:

JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript" />
<script type="text/javascript"> 
      var prevRowIndex; 
      function ChangeRowColor(row, rowIndex) { 
          var parent = document.getElementById(row); 
          var currentRowIndex = parseInt(rowIndex) + 1; 
      
          if (prevRowIndex == currentRowIndex) { 
              return; 
          } 
          else if (prevRowIndex != null) { 
              parent.rows[prevRowIndex].style.backgroundColor = "#FFFFFF"; 
          } 
      
          parent.rows[currentRowIndex].style.backgroundColor = "#FFFFD6"; 
          prevRowIndex = currentRowIndex; 
      
          $('#<%= Label1.ClientID %>').text(currentRowIndex); 
      
          $('#<%= hfParentContainer.ClientID %>').val(row); 
          $('#<%= hfCurrentRowIndex.ClientID %>').val(rowIndex); 
      } 
      
      $(function () { 
          RetainSelectedRow(); 
      }); 
      
      function RetainSelectedRow() { 
          var parent = $('#<%= hfParentContainer.ClientID %>').val(); 
          var currentIndex = $('#<%= hfCurrentRowIndex.ClientID %>').val(); 
          if (parent != null) { 
              ChangeRowColor(parent, currentIndex); 
          } 
      } 
      
</script>

The ChangeRowColor() is a function that sets the background color of the selected row. It is also where we set the previous row and rowIndex values in HiddenFields.  The $(function(){}); is a short-hand for the jQuery document.ready event. This event will be fired once the page is posted back to the server that’s why we call the function RetainSelectedRow(). The RetainSelectedRow() function is where we referenced the current selected values stored from the HiddenFields and pass these values to the ChangeRowColor() function to retain the highlighted row.

Finally, here’s the code behind part:

C#
protected void grdCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow){
        e.Row.Attributes.Add("onclick", string.Format("ChangeRowColor('{0}','{1}');", e.Row.ClientID, e.Row.RowIndex));
    }
}

The code above is responsible for attaching the JavaScript onclick event for each row and call the ChangeRowColor() function and passing the e.Row.ClientID and e.Row.RowIndex to the function.

Here’s the sample output below:

Image 1

That's it! I hope someone find this post useful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
A code monkey who loves to drink beer, play guitar and listen to music.

My Tech Blog: https://vmsdurano.com/
My Youtube Channel: https://www.youtube.com/channel/UCuabaYm8QH4b1MAclaRp-3Q

I currently work as a Solutions Architect and we build "cool things" to help people improve their health.

With over 14 years of professional experience working as a Sr. Software Engineer specializing mainly on Web and Mobile apps using Microsoft technologies. My exploration into programming began at the age of 15;Turbo PASCAL, C, C++, JAVA, VB6, Action Scripts and a variety of other equally obscure acronyms, mainly as a hobby. After several detours, I am here today on the VB.NET to C# channel. I have worked on Web Apps + Client-side technologies + Mobile Apps + Micro-services + REST APIs + Event Communication + Databases + Cloud + Containers , which go together like coffee crumble ice cream.

I have been awarded Microsoft MVP each year since 2009, awarded C# Corner MVP for 2015, 2016,2017 and 2018, CodeProject MVP, MVA, MVE, Microsoft Influencer, Dzone MVB, Microsoft ASP.NET Site Hall of Famer with All-Star level and a regular contributor at various technical community websites such as CSharpCorner, CodeProject, ASP.NET and TechNet.

Books written:
" Book: Understanding Game Application Development with Xamarin.Forms and ASP.NET
" Book (Technical Reviewer): ASP.NET Core and Angular 2
" EBook: Dockerizing ASP.NET Core and Blazor Applications on Mac
" EBook: ASP.NET MVC 5- A Beginner's Guide
" EBook: ASP.NET GridView Control Pocket Guide

Comments and Discussions

 
BugError in Code behind Pin
Dani Pazos2-Apr-17 23:34
Dani Pazos2-Apr-17 23:34 
GeneralRe: Error in Code behind Pin
Vincent Maverick Durano12-Apr-17 1:01
professionalVincent Maverick Durano12-Apr-17 1:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.