Monday, November 12, 2012

Highligh GridView Row on click in ASP.NET (REPOST)

This is based from the article of Vincent Maverick Durano's blog on HIGHLIGHT GRIDVIEW ROW ON CLICK AND RETAIN SELECTED ROW ON POST BACK.

I just added some statements on javascript to check if the selected row is less than total gridview row count and server side code for paging.
JAVASCRIPT CODE:
1:  <script type="text/javascript">  
2:    var prevRowIndex;  
3:    function ChangeRowColor(row, rowIndex) {  
4:      var parent = document.getElementById(row);  
5:      var currentRowIndex = parseInt(rowIndex) + 1;  
6:      //count number of gridview rows  
7:      var rowscount = $("#<%=grdCustomer.ClientID %> tr").length;  
8:      if (prevRowIndex == currentRowIndex) {  
9:        return;  
10:      }  
11:      else if (prevRowIndex != null) {  
12:        parent.rows[prevRowIndex].style.backgroundColor = "#FFFFFF";  
13:      }  
14:      //check if current index is a number...  
15:      if (IsNumeric(currentRowIndex)) {  
16:        //check if row index is less or equal to rowcount...  
17:        if (currentRowIndex <= rowscount) {  
18:          parent.rows[currentRowIndex].style.backgroundColor = "#FFFFD6";  
19:          prevRowIndex = currentRowIndex;  
20:          $('#<%= Label1.ClientID %>').text(currentRowIndex);  
21:        }  
22:      }  
23:      else {  
24:        $('#<%= Label1.ClientID %>').text("No row selected...");  
25:      }      
26:      $('#<%= hfParentContainer.ClientID %>').val(row);  
27:      $('#<%= hfCurrentRowIndex.ClientID %>').val(rowIndex);  
28:    }  
29:    function IsNumeric(num) {  
30:      return (num >= 0 || num < 0);  
31:    }  
32:    $(function () {  
33:      RetainSelectedRow();  
34:    });  
35:    function RetainSelectedRow() {  
36:      var parent = $('#<%= hfParentContainer.ClientID %>').val();  
37:      var currentIndex = $('#<%= hfCurrentRowIndex.ClientID %>').val();  
38:      if (parent != null) {  
39:        ChangeRowColor(parent, currentIndex);  
40:      }  
41:    }   
42:    </script>  
ASPX Markup.
1:  <asp:HiddenField ID="hfCurrentRowIndex" runat="server"></asp:HiddenField>  
2:    <asp:HiddenField ID="hfParentContainer" runat="server"></asp:HiddenField>  
3:    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Trigger Postback" />  
4:    <asp:GridView ID="grdCustomer" runat="server" AutoGenerateColumns="false"   
5:      onrowdatabound="grdCustomer_RowDataBound" AllowPaging="True"   
6:      onpageindexchanging="grdCustomer_PageIndexChanging">  
7:      <Columns>  
8:        <asp:BoundField DataField="CompanyName" HeaderText="Company" />  
9:        <asp:BoundField DataField="ContactName" HeaderText="Name" />  
10:        <asp:BoundField DataField="ContactTitle" HeaderText="Title" />  
11:        <asp:BoundField DataField="Address" HeaderText="Address" />  
12:      </Columns>  
13:    </asp:GridView>  

0 comments:

Post a Comment