In my previous tutorials, I’d explained bind gridview using executereader, how to export gridview data to word excel text and pdf, get gridview selected rows data from code-behind and other more cracking tutorials on GridView, Asp.net here.
Now here in this tutorial, I’ll explain how you can keep the state of asp.net gridview checked or selected rows during paging or page index change event in asp.net using c# and vb.net with example code and step by step guide.
Gridview Keep Checked or Selected Rows State OnPageIndexChanging Event
Here is the complete HTML markup for .aspx page that I used for gridview keep checked or selected rows state in asp.net:
<head id=”Head1″ runat=”server”>
<title>Keep state of gridview selected rows during paging in asp.net
using c# or vb.net</title>
<style type=”text/css”>
.selected
{
background-color: #f5f5f5;
}
</style>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js”>
</script>
<script type=”text/javascript”>
$(document).ready(function () {
//Checkbox header select all settings
$(‘[id$=chkSelectAll]’).click(function () {
if ($(this).is(“:checked”)) {
$(‘.chkSelect > input[type=”checkbox”]’).prop(‘checked’, true);
//add the selected class from each row
$(‘.chkSelect > input[type=”checkbox”]’).closest(“tr”).addClass(“selected”);
} else {
$(‘.chkSelect > input[type=”checkbox”]’).prop(‘checked’, false);
//remove selected class from each row
$(‘.chkSelect > input[type=”checkbox”]’).closest(“tr”).removeClass(“selected”);
}
});//Checkbox gridview row select settings
$(‘.chkSelect > input[type=”checkbox”]’).click(function () {
//remove chkSelectAll checked when any of the child checkbox clicked
$(‘[id$=chkSelectAll]’).removeAttr(“checked”);
if ($(this).is(“:checked”)) {
//add the selected class to selected row
$($(this).closest(“tr”)).addClass(“selected”);
} else {
//remove the selected class from selected row
$($(this).closest(“tr”)).removeClass(“selected”);
}
});
});
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<h4>
Keep state of gridview selected rows during paging in asp.net</h4>
<asp:GridView ID=”grdResult” runat=”server” AutoGenerateColumns=”false”
AllowPaging=”true” PageSize=”5″ OnPageIndexChanging=”grdResult_PageIndexChanging”
DataKeyNames=”SubjectId”>
<HeaderStyle Font-Bold=”true” BackColor=”#9a9a9a” BorderColor=”#222″
ForeColor=”White” Height=”30″ />
<PagerStyle HorizontalAlign=”Center” />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID=”chkSelectAll” runat=”server” />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID=”chkSelect” runat=”server” CssClass=”chkSelect” />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”SubjectName” HeaderText=”Subject Name”
ItemStyle-Width=”200″ ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField DataField=”Marks” ItemStyle-HorizontalAlign=”Center”
ItemStyle-Width=”200″ HeaderText=”Marks” />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Make sure I’ve used runat=”server” property of checkbox to access and identify selected rows and also declared OnPageIndexChanging=”grdResult_PageIndexChanging” event of asp.net gridview control that fired on page index change.
After adding HTML markup to .aspx page, choose your language (that is C# or Vb.net) and paste it to your code-behind file.
Gridview Keep Checked or Selected Rows State During Paging in C#
Now add the following namespace:
using System.Collections;
After that add the following code in .aspx.cs page to bind gridview:
{
if (!IsPostBack)
{
LoadResultData();
}
}private void LoadResultData()
{
DataTable dt = new DataTable();
//Creating Column
dt.Columns.Add(“SubjectId”);
dt.Columns.Add(“SubjectName”);
dt.Columns.Add(“Marks”);
//Adding Results in rows
dt.Rows.Add(1, “Asp.net”, 95);
dt.Rows.Add(2, “C#”, 88);
dt.Rows.Add(3, “Vb.net”, 78);
dt.Rows.Add(4, “HTML”, 89);
dt.Rows.Add(5, “CSS”, 90);
dt.Rows.Add(6, “JavaScript”, 85);
dt.Rows.Add(7, “jQuery”, 96);
//Binding Results to gridview
grdResult.DataSource = dt;
grdResult.DataBind();
}
And here is the code to keep the grid view selected or checked row state, add following code right after the above code:
protected void grdResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//Save checked rows before page change
SaveCheckedStates();
grdResult.PageIndex = e.NewPageIndex;
LoadResultData();
//Populate cheked items with its checked status
PopulateCheckedStates();
}//Save the state of row checkboxes
private void SaveCheckedStates()
{
ArrayList objAL = new ArrayList();
int rowIndex = -1;
foreach (GridViewRow row in grdResult.Rows)
{
rowIndex = Convert.ToInt32(grdResult.DataKeys[row.RowIndex].Value);
bool isSelected = ((CheckBox)row.FindControl(“chkSelect”)).Checked;
if (ViewState[“SELECTED_ROWS”] != null)
{
objAL = (ArrayList)ViewState[“SELECTED_ROWS”];
}
if (isSelected)
{
if (!objAL.Contains(rowIndex))
{
objAL.Add(rowIndex);
}
}
else
{
objAL.Remove(rowIndex);
}
}
if (objAL != null && objAL.Count > 0)
{
ViewState[“SELECTED_ROWS”] = objAL;
}
}
//Populate the saved checked checkbox status
private void PopulateCheckedStates()
{
ArrayList objAL = (ArrayList)ViewState[“SELECTED_ROWS”];
if (objAL != null && objAL.Count > 0)
{
foreach (GridViewRow row in grdResult.Rows)
{
int rowIndex = Convert.ToInt32(grdResult.DataKeys[row.RowIndex].Value);
if (objAL.Contains(rowIndex))
{
CheckBox chkSelect = (CheckBox)row.FindControl(“chkSelect”);
chkSelect.Checked = true;
row.Attributes.Add(“class”, “selected”);
}
}
}
}
Gridview Keep Checked or Selected Rows State During Paging in Vb.net
Now add the following namespace:
Imports System.Collections
After that add the following code to .aspx.vb page:
If Not IsPostBack Then
LoadResultData()
End If
End SubPrivate Sub LoadResultData()
Dim dt As New DataTable()
‘Creating Column
dt.Columns.Add(“SubjectId”)
dt.Columns.Add(“SubjectName”)
dt.Columns.Add(“Marks”)
‘Adding Results in rows
dt.Rows.Add(1, “Asp.net”, 95)
dt.Rows.Add(2, “C#”, 88)
dt.Rows.Add(3, “Vb.net”, 78)
dt.Rows.Add(4, “HTML”, 89)
dt.Rows.Add(5, “CSS”, 90)
dt.Rows.Add(6, “JavaScript”, 85)
dt.Rows.Add(7, “jQuery”, 96)
‘Binding Results to gridview
grdResult.DataSource = dt
grdResult.DataBind()
End Sub
And here is the code to get selected or checked row values from code-behind, add following code right after the above code:
Protected Sub grdResult_PageIndexChanging(ByVal sender As Object,
ByVal e As GridViewPageEventArgs)
‘Save checked rows before page change
SaveCheckedStates()
grdResult.PageIndex = e.NewPageIndex
LoadResultData()
‘Populate cheked items with its checked status
PopulateCheckedStates()
End Sub‘Save the state of row checkboxes
Private Sub SaveCheckedStates()
Dim objAL As New ArrayList()
Dim rowIndex As Integer = -1
For Each row As GridViewRow In grdResult.Rows
rowIndex = Convert.ToInt32(grdResult.DataKeys(row.RowIndex).Value)
Dim isSelected As Boolean = CType(row.FindControl(“chkSelect”), CheckBox).Checked
If ViewState(“SELECTED_ROWS”) IsNot Nothing Then
objAL = CType(ViewState(“SELECTED_ROWS”), ArrayList)
End If
If isSelected Then
If Not objAL.Contains(rowIndex) Then
objAL.Add(rowIndex)
End If
Else
objAL.Remove(rowIndex)
End If
Next row
If objAL IsNot Nothing AndAlso objAL.Count > 0 Then
ViewState(“SELECTED_ROWS”) = objAL
End If
End Sub
‘Populate the saved checked checkbox status
Private Sub PopulateCheckedStates()
Dim objAL As ArrayList = CType(ViewState(“SELECTED_ROWS”), ArrayList)
If objAL IsNot Nothing AndAlso objAL.Count > 0 Then
For Each row As GridViewRow In grdResult.Rows
Dim rowIndex As Integer = Convert.ToInt32(grdResult.DataKeys(row.RowIndex).Value)
If objAL.Contains(rowIndex) Then
Dim chkSelect As CheckBox = CType(row.FindControl(“chkSelect”), CheckBox)
chkSelect.Checked = True
row.Attributes.Add(“class”, “selected”)
End If
Next row
End If
End Sub