Wednesday, July 25, 2012

Asp.Net jQuery GridView Selected Row Values


The click event on the row of a GridView can be tracked using the click event handler of jQuery and the cell values of the selected row can be obtained by referring to the nth cell in the row as follows.

$("#grdEmployee tr").click(function(event) {
   var ID = $(this).find("td:nth-child(1)").html();
   var Name = $(this).find("td:nth-child(2)").html();
   alert('ID: ' + ID + '\nName: ' + Name);
});


When we click on any of the rows in the GridView, the click event gets triggered and the values of the cells in the row are displayed in a message box.

Example

<script type="text/javascript"
src="JavaScript/jquery-1.7.2.js"></script>
<link type="text/css"
href="Stylesheet.css"
rel="Stylesheet" />
<script type="text/javascript">
$(document).ready(function() {
//
// Add Grid Style
$("#grdEmployee").addClass("Grid");
//
// Add Grid Cell Style
$("#grdEmployee td").addClass("GridCell");
      //
      // Add Header Style
$("#grdEmployee th").addClass("GridHeader");
      //
      // Add Row Style
      $("#grdEmployee tr").addClass("GridRow");
      //     
// Selected Row Values
$("#grdEmployee tr").click(function(event) {
   var ID = $(this).find("td:nth-child(1)").html();
   var Name = $(this).find("td:nth-child(2)").html();
   alert('ID: ' + ID + '\nName: ' + Name);
}); 
});
</script>   
<asp:GridView
   ID="grdEmployee"
   runat="server"
   AutoGenerateColumns="true"></asp:GridView>

Add your logic in codebehind to populate the Grid with data.

Stylesheet.css

.Grid
{
      border: 1px solid #000000;
}
.GridCell
{
    padding: 3px 3px 3px 3px; /* Cellpadding */
    border: 1px solid #000000;
    font-family:Verdana;
    font-size:10pt;   
}
.GridHeader
{
      background-color:#999966;
}
.GridRow
{
    background-color:#ffffcc;

Search Flipkart Products:
Flipkart.com