How to remove GridView columns using jQuery

With continuation with my Grid View series posts, In this post, I will show you how to remove columns in grid view on clicking the column header using jQuery. To achieve this, one need to bind the click event on the header columns of the GridView. For your information, GridView is rendered as table > th > tr > td format. So need to bind the click event on "th" to remove the respective column. So first take a look at complete jQuery code to remove columns from GridView. See below jQuery code.

$(document).ready(function() {
   $("#<%=gdRows.ClientID%> th").click(function() {
       var iIndex = $(this).closest("th").prevAll("th").length;
       $(this).parents("#<%=gdRows.ClientID%>").find("tr").each(function() {
          $(this).find("td:eq(" + iIndex + ")").remove();
          $(this).find("th:eq(" + iIndex + ")").remove();
       });
    });
});

Okay, lets understand this code line by line. This below line will bind the click event to all the "th" of GridView named "gdRows".

$("#<%=gdRows.ClientID%> th").click(function() {

Now, before removing the column, we need to find out the index of the th or index of the header column which is clicked. The below line of jQuery code, will find the index of the click of the clicked th. The code is using two jQuery selectors "closest()" and "prevAll" to find the out index. The jQuery selector .closest() begins with the current element and travels up the DOM tree until it finds a matching element. And the jQuery selector .prevAll() searches all the predecessors of the current element in the DOM tree.

var iIndex = $(this).closest("th").prevAll("th").length;

Now we need to define a callback function on each row of the GridView to remove td from the each row.

$(this).parents("#<%=gdRows.ClientID%>").find("tr").each(function() {

The below code is placed within the callback function of tr and it will remove the GridView Cells based on the value of iIndex. And it will also remove the th.

$(this).find("td:eq(" + iIndex + ")").remove();
$(this).find("th:eq(" + iIndex + ")").remove();

Instead of removing it, you can also hide the td and th by setting the CSS "display:none".

Also, set cursor to hand pointer to let user know that the column header is clickable.

$("#<%=gdRows.ClientID%> th").mouseover(function() {
   $(this).css('cursor','pointer');
});

Hope you have find this useful!!!!!!

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



Responsive Menu
Add more content here...