Get ASP.NET GridView Cell Value on Click using jQuery

I had already posted more than 10 ASP.NET GridView Tips and Tricks with jQuery and today you will see How to Get ASP.NET GridView Cell Value when it is clicked, using jQuery. You might be knowing that ASP.NET GridView is rendered as table -> th -> tr -> td format. All the rows are converted into tr element and values placed in different td elements.

So, when the GridView Cell is clicked, for better user experience it is good to highlight the cell. You can also see the same in image. So Below given CSS class, I have used to highlight the selected cell.

//Code Starts
.selected
{
  background-color: Yellow;
  color : Green;
}
//Code Ends

Before attaching click event to the GridView cell's, it is important to let user know that cell is clickable. So change the mouse cursor style to "Pointer" so user will come to know that cell is clickable. Below code exactly does the same thing.

//Code Starts
$("#<%=gdRows.ClientID%> tr:has(td)").hover(function(e) {
   $(this).css("cursor", "pointer");
});  
//Code Ends

To get the Cell Data, it is important to find out that will cell is clicked. So using "closest()" method, we can find out. The "closest()" method gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

//Code Starts
$("#<%=gdRows.ClientID%> tr:has(td)").click(function(e) {
   var selTD = $(e.target).closest("td");
   $("#<%=gdRows.ClientID%> td").removeClass("selected");
   selTD.addClass("selected");
   $("#<%=lblSelected.ClientID%>").html(
       'Selected Cell Value is: <b> ' + selTD.text() + '</b>');
});
//Code Ends

The above jQuery code does the following things.

  • First assign a click event to all the tds of GridView.
  • After that it gets the clicked cell into a object using "closest()" method.
  • After it removes selected class from all the tds. This is important as if any cell was previously selected then remove the selected class.
  • Assign selected class to currently clicked cell.
  • And in the end, gets the selected cell's text and assign it to label.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...