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

Posted by Vincent Maverick Durano on Geeks with Blogs See other posts from Geeks with Blogs or by Vincent Maverick Durano
Published on Fri, 07 Sep 2012 10:46:54 GMT Indexed on 2012/09/07 21:39 UTC
Read the original article Hit count: 289

Filed under:

A couple of months ago I’ve written a simple demo about “Highlighting GridView Row on MouseOver”. I’ve noticed many members in the forums (http://forums.asp.net) 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 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 the gridview you can refer this post: Binding GridView with Data the ADO.Net way or this one: GridView Custom Paging with LINQ.

To get started 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: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 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 persist the settings we will use some HiddenFields control to store the data so that when it postback we can reference the value from there.

Now here’s the JavaScript functions below:

<asp:content id="Content1" runat="server" contentplaceholderid="HeadContent">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>

<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>

</asp:content>

 

The ChangeRowColor() is the 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 function. This function 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:

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:

highlightrow

 

That’s it! I hope someone find this post useful!

© Geeks with Blogs or respective owner