How To Highlight GridView Row On Click In ASP.NET Web Forms
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:
ASPX Markup.
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:
<script type="text/javascript"> var prevRowIndex; function ChangeRowColor(row, rowIndex) { var parent = document.getElementById(row); var currentRowIndex = parseInt(rowIndex) + 1; //count number of gridview rows var rowscount = $("#<%=grdCustomer.ClientID %> tr").length; if (prevRowIndex == currentRowIndex) { return; } else if (prevRowIndex != null) { parent.rows[prevRowIndex].style.backgroundColor = "#FFFFFF"; } //check if current index is a number... if (IsNumeric(currentRowIndex)) { //check if row index is less or equal to rowcount... if (currentRowIndex <= rowscount) { parent.rows[currentRowIndex].style.backgroundColor = "#FFFFD6"; prevRowIndex = currentRowIndex; $('#<%= Label1.ClientID %>').text(currentRowIndex); } } else { $('#<%= Label1.ClientID %>').text("No row selected..."); } $('#<%= hfParentContainer.ClientID %>').val(row); $('#<%= hfCurrentRowIndex.ClientID %>').val(rowIndex); } function IsNumeric(num) { return (num >= 0 || num < 0); } $(function () { RetainSelectedRow(); }); function RetainSelectedRow() { var parent = $('#<%= hfParentContainer.ClientID %>').val(); var currentIndex = $('#<%= hfCurrentRowIndex.ClientID %>').val(); if (parent != null) { ChangeRowColor(parent, currentIndex); } } <script />
<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" AllowPaging="True" onpageindexchanging="grdCustomer_PageIndexChanging"> <Columns> <asp:BoundField DataField="CompanyName" HeaderText="Company" /> <asp:BoundField DataField="ContactName" HeaderText="Name" /> <asp:BoundField DataField="ContactTitle" HeaderText="Title" /> <asp:BoundField DataField="Address" HeaderText="Address" /> </Columns> </asp:GridView>
Comments
Post a Comment