Maintain Checkbox state while GridView Paging in ASP.Net
In ASP.Net, GridView paging does not maintain the checkbox state whether it was in checked or unchecked state before firing the paging event of GridView control. Yes its easy to get and set the checkbox states i.e. checked or unchecked inside the ASP.Net GridView control based on the values retrieved from the database. This process is easy only if you have set the AllowPaging property of GridView control "false" means when you are not using the paging feature of GridView. But, to maintain the checkbox state placed inside the GridView control while paging needs some extra logic and code. Here we will learn how to maintain the checkbox state while GridView paging using ASP.Net C# as well as VB code. In this tutorial we have used the categories table of SQL Northwind database to explain the functionality.
You can see the live samples and examples of GridView from the following links:
HTML Code for ASP.Net GridView Checkbox Controls
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderStyle="Solid" CellPadding="4" DataKeyNames="CategoryID" BorderColor="Silver" BorderWidth="1px" Width="300px" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="4" ShowHeader="False"> <Columns> <asp:TemplateField> <ItemTemplate> <%# DataBinder.Eval( Container.DataItem, "categoryID") %> <asp:CheckBox ID="chk1" runat="server" Text='<%# DataBinder.Eval( Container.DataItem, "categoryName") %>' /> </ItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle HorizontalAlign="Left" /> </asp:GridView>
To remember the checkbox previous state while paging postback event of GridView control, ASP.Net HiddenField control is used in this tutorial.
<asp:HiddenField ID="hiddenCatIDs" runat="server" />
By Default categories table of Northwind database contains only 8 records that’s why pageSize property of GridView control has been set to "4" and AllowPaging property has been set to "True". This will render the GridView control with paging template along with 2 pages. DataKeyNames property of GridView control has been set to CategoryID column of the categories table to store the unique associated value for each row of GridView control. You can see that ASP.Net Checkbox server control is used in the above GridView HTML code so that it could be accessed inside the C# or VB server end code to set the unchecked or checked state of the checkbox placed inside the ItemTemplate of TemplateField Column of ASP.Net GridView control.
Continue to next tutorial: maintaining the checkbox state after postback event of GridView paging to get the C# code for preserving the checkbox state in a gridview control while paging.