In this article I will explain with an example, how to preserve state of CheckBoxes while paging in ASP.Net GridView using C# and VB.Net.
This article will also covers, how to change the row color when the CheckBox is checked.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The following HTML Markup consists of:
GridView:– For displaying data.
Columns
The GridView consists of one TemplateField column and four BoundField columns.
TemplateField
The TemplateField column consists of HeaderTemplate and ItemTemplate which contains of ASP.Net CheckBox controls.
Inside the
HeaderTemplate CheckBox is assigned with a
JavaScript onclick event handler which calls the
SelectAll JavaScript function.
And then,
ItemTemplate CheckBox is assigned with a
JavaScript onclick event handler which calls the
SelectOne JavaScript function.
Properties
AutoGenerateColumns – Indicates whether bound fields are automatically created for each field in the data source or not. By default is to set to TRUE if not specified.
PageSize – For permitting maximum number of rows to be displayed per page.
AllowPaging – For enabling paging in the GridView control.
Events
The GridView has been assigned with an OnPageIndexChanging event handler.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
AllowPaging="true" OnPageIndexChanging="OnPaging" PageSize="10">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick="SelectAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="SelectOne(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CustomerID" HeaderText="Customer Id" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Collections.Generic
Populating GridView with records from the Database
Inside the Page Load event handler, the BindGrid method is called.
Inside the BindGrid method, the GridView is populated with the records fetched from Customers table of Northwind database.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT CustomerID, City, Country, PostalCode FROM Customers";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Dim query As String = "SELECT CustomerID, City, Country, PostalCode FROM Customers"
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Sub
Paging
Inside the OnPageIndexChanging event handler, the GetCheckedCheckBoxes method is called.
Then, the PageIndex property of the GridView is updated with the new Page Number which was clicked and the GridView is populated using the BindGrid method which in-turn displays the new GridView page.
Finally, the SetCheckedCheckBoxes method is called.
Note: The GetCheckedCheckBoxes and SetCheckedCheckBoxes methods will be described later in the article.
protected void OnPaging(object sender, GridViewPageEventArgse)
{
this.GetCheckedCheckBoxes();
gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
this.SetCheckedCheckBoxes();
}
VB.Net
Protected Sub OnPaging(sender As Object, e As GridViewPageEventArgs)
Me.GetCheckedCheckBoxes()
gvCustomers.PageIndex = e.NewPageIndex
Me.BindGrid()
Me.SetCheckedCheckBoxes()
End Sub
Maintaining state of the CheckBoxes
To maintain the state of CheckBoxes following property and methods are used.
Property:
CheckBoxArray – For storing the details of checked CheckBoxes.
Inside this getter, ViewState is checked for null, if it is not null then the value of ViewState is returned as generic lis collection of integers.
If ViewState is found null, then the empty generic List collection of integer type is returned.
Finally, inside the setter, the value is set in the ViewState.
Methods:
GetCheckedCheckBoxes – For getting checked CheckBoxes details.
SetCheckedCheckBoxes – To mark check or uncheck row CheckBoxes and HeaderRow CheckBox.
GetCheckedCheckBoxes
Inside the GetCheckedCheckBoxes method, first the CheckBoxArray property is called.
A FOR EACH loop is executed over the GridView rows and if the RowType is DataRow then the current row CheckBox is referenced.
Then, the CheckBox Index is determined using following line of code:
CheckBoxIndex = GridView1.PageSize * GridView1.PageIndex + (RowIndex + 1)
RowIndex and PageIndex are zero based indexes i.e. the first row or first page starts from 0.
Then, a check is performed if the CheckBox is checked or not. If the CheckBox is checked, it is added to the ArrayList and if it unchecked or it is already present in the ArrayList then it is removed from the ArrayList.
C#
private void GetCheckedCheckBoxes()
{
int checkBoxIndex;
List<int> checkBoxArray = this.CheckBoxArray;
//Loop through the GridView rows.
int i = 0;
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
//Reference the CheckBox and calculate its Index.
CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
checkBoxIndex = gvCustomers.PageSize * gvCustomers.PageIndex + (i + 1);
if (chk.Checked)
{
//If CheckBox is checked, add it to the ArrayList.
if (checkBoxArray.IndexOf(checkBoxIndex) == -1)
{
checkBoxArray.Add(checkBoxIndex);
}
}
else
{
//If CheckBox is unchecked, remove it from the ArrayList.
if (checkBoxArray.IndexOf(checkBoxIndex) != -1)
{
checkBoxArray.Remove(checkBoxIndex);
}
}
}
i++;
}
this.CheckBoxArray = checkBoxArray;
}
private List<int> CheckBoxArray
{
get
{
if (ViewState["CheckBoxArray"] != null)
{
return (List<int>)ViewState["CheckBoxArray"];
}
return new List<int>();
}
set
{
ViewState["CheckBoxArray"] = value;
}
}
VB.Net
Private Sub GetCheckedCheckBoxes()
Dim checkBoxIndex As Integer
Dim checkBoxArray As List(Of Integer) = Me.CheckBoxArray
'Loop through the GridView rows.
Dim i As Integer = 0
For Each row As GridViewRow In gvCustomers.Rows
If row.RowType = DataControlRowType.DataRow Then
'Reference the CheckBox and calculate its Index.
Dim chk As CheckBox = CType(row.FindControl("CheckBox1"), CheckBox)
checkBoxIndex = gvCustomers.PageSize * gvCustomers.PageIndex + (i + 1)
If chk.Checked Then
'If CheckBox is checked, add it to the ArrayList.
If checkBoxArray.IndexOf(checkBoxIndex) = -1 Then
checkBoxArray.Add(checkBoxIndex)
End If
Else
'If CheckBox is unchecked, remove it from the ArrayList.
If checkBoxArray.IndexOf(checkBoxIndex) <> -1 Then
checkBoxArray.Remove(checkBoxIndex)
End If
End If
End If
i += 1
Next
Me.CheckBoxArray = checkBoxArray
End Sub
Private Property CheckBoxArray As List(Of Integer)
Get
If ViewState("CheckBoxArray") IsNot Nothing Then
Return CType(ViewState("CheckBoxArray"), List(Of Integer))
End If
Return New List(Of Integer)()
End Get
Set(value As List(Of Integer))
ViewState("CheckBoxArray") = value
End Set
End Property
SetCheckedCheckBoxes
Inside this method, a Boolean type isAllChecked variable is created with value TRUE.
Note: isAllChecked variable will be used to check or uncheck the HeaderRow CheckBox.
A FOR EACH loop is executed over the GridView rows and a check is performed by calling CheckBoxArray property, if the current index is present in the ArrayList.
If it is present, then the CheckBox of the current row is checked and the selected class is added to the current row which will be used to change the background colour.
If the current index is not present in the ArrayList then, the isAllChecked variable is set to FALSE.
Finally, the reference of the HeaderRow CheckBox is referenced and isAllChecked variable is assigned to its Checked property.
C#
private void SetCheckedCheckBoxes()
{
int i = 0;
bool isAllChecked = true;
foreach (GridViewRowrow in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
//Check if Index is present in ArrayList.
int checkBoxIndex = gvCustomers.PageSize * (gvCustomers.PageIndex) + (i + 1);
if (this.CheckBoxArray.IndexOf(checkBoxIndex) != -1)
{
//If present, check it.
CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
chk.Checked = true;
row.Attributes.Add("class", "selected");
}
else
{
isAllChecked = false;
}
}
i++;
}
//If present, check it.
CheckBox chkAll = (CheckBox)gvCustomers.HeaderRow.FindControl("chkAll");
chkAll.Checked = isAllChecked;
}
VB.Net
Private Sub SetCheckedCheckBoxes()
Dim i As Integer = 0
Dim isAllChecked As Boolean = True
For Each row As GridViewRow In gvCustomers.Rows
If row.RowType = DataControlRowType.DataRow Then
'Check if Index is present in ArrayList.
Dim checkBoxIndex As Integer = gvCustomers.PageSize * (gvCustomers.PageIndex) + (i + 1)
If Me.CheckBoxArray.IndexOf(checkBoxIndex) <> -1 Then
'If present, check it.
Dim chk As CheckBox = CType(row.FindControl("CheckBox1"), CheckBox)
chk.Checked = True
row.Attributes.Add("class", "selected")
Else
isAllChecked = False
End If
End If
i += 1
Next
'If present, check it.
Dim chkAll As CheckBox = CType(gvCustomers.HeaderRow.FindControl("chkAll"), CheckBox)
chkAll.Checked = isAllChecked
End Sub
Client Side JavaScript
Follow
JavaScript functions are used to check and uncheck all CheckBoxes in GridView.
<script type="text/javascript">
function SelectOne(chk) {
//Get the reference of GridView.
var grid = chk.parentNode.parentNode.parentNode;
//Get the reference of GridView Row.
var row = chk.parentNode.parentNode;
//Set the color of Row.
row.className = "selected";
//Reference the Header CheckBox.
var headerCheckBox = grid.rows[0].cells[0].getElementsByTagName("input")[0];;
var checked = true;
//Loop through all GridView Rows.
for (var i = 1; i < grid.rows.length - 1; i++) {
//Reference the CheckBox.
var checkBox = grid.rows[i].cells[0].getElementsByTagName("input")[0];
if (!checkBox.checked) {
checked = false;
break;
}
}
headerCheckBox.checked = checked;
};
function SelectAll(headerCheckBox) {
//Get the reference of GridView.
var GridView = headerCheckBox.parentNode.parentNode.parentNode;
//Loop through all GridView Rows except first row.
for (var i = 1; i < GridView.rows.length - 1; i++) {
//Reference the CheckBox.
var checkBox = GridView.rows[i].cells[0].getElementsByTagName("input")[0];
//If CheckBox is checked, change background color the GridView Row.
if (headerCheckBox.checked) {
checkBox.checked = true;
GridView.rows[i].className = "selected";
} else {
checkBox.checked = false;
GridView.rows[i].className = "";
}
}
};
</script>
Screenshot
Demo
Downloads