Tuesday, October 23, 2012

Check uncheck all rows of gridview (select or deselect all rows at once)



The asp.net gridview data control offers lots of features, that we all know. Adding some cool effects may make this control more usable. For instance, we could check or uncheck all the checkboxes in a column of the gridview control. A column [leftmost column usually] consisting of checkbox control is generally used to select a row. Sometimes we may need to check (and uncheck) all the rows of the gridview. Purpose of doing so may be different depending upon the business requirement. And if we need to do so, we can!

Fig. Check Uncheck all rows in a gridview


Let's be quick to implement check/uncheck all the rows of gridview at once in asp.net gridview. Let's have the markup for the gridview first.
  1. <asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="false">  
  2.   
  3.         <Columns>  
  4.   
  5.             <asp:TemplateField HeaderText="Select" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center">  
  6.   
  7.                 <HeaderTemplate >  
  8.   
  9.                     <input id="chkAll" onclick="javascript:SelectDeselectAllCheckboxes(this);"   
  10.   
  11.                           runat="server" type="checkbox" />  
  12.   
  13.                 </HeaderTemplate>  
  14.   
  15.             <ItemTemplate>  
  16.   
  17.                 <asp:CheckBox ID="chkSelect" runat="server" />  
  18.   
  19.             </ItemTemplate>  
  20.   
  21.             </asp:TemplateField>  
  22.   
  23.             <asp:BoundField HeaderText="Name" DataField="Name" ItemStyle-Width="100" />  
  24.   
  25.             <asp:BoundField HeaderText="Address" DataField="Address" />              
  26.   
  27.         </Columns>  
  28.   
  29.     </asp:GridView>  

Watched the checkbox control in the header template of the first column? We will use this checkbox to select or deselect all the rows in the gridview. Also mark that clicking this checkbox will call the javascript function SelectDeselectAllCheckboxes. Now is the time to define some javascript snippets to get help from.
  1.   

The task done by the javascript function is simple. It takes the checkbox itself as the input. If it is checked, it searches for all the checkboxes in the gridview and checks them. And reversely, if it is unchecked, all those checkboxes will be consequently unchecked.
There is no need of any codebehind just for this functionality. So I am leaving other parts including databinding code. In fact, for most of the test purposes I do Create DataTable Programmatically and bind the gridview, formview or detailsview to that DataTable.
The only drawback with this technique is that it treats all the checkboxes in or outside the gridview control equal.
You can post your comment, rate this post or add this post to your favourites or share it. Happy Programming!