Introduction
The GridView
control has a property called AllowPaging
which enables us to paginate GridView
records. So to enable pagination for a GridView
, set the AllowPaging
property to true
and we will need to also handle the OnPageIndexChanging
event. The PagerSettings-Mode
property displays the page numbers to navigate through different pages of the GridView
records.
The OnRowDataBound
event is raised when the data is bound to the GridView
control. This enables us to provide an event-handling method that can be used to access the GridView
rows one by one and perform the desired operation.
This solution is one of many solutions provided in .NET How to's.
The following code snippet from the ASPX page shows how these properties and events are set.
ASPX Page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
AllowPaging="true" DataKeyNames="AutoId" OnPageIndexChanging="PaginateTheData"
PageSize="5" PagerSettings-Mode="Numeric
OnRowDataBound="ReSelectSelectedRecords">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Last Name" DataField="LastName" />
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p><asp:Button ID="btnGetSelected" runat="server"
Text="Get Selected Records" OnClick="GetSelectedRecords" /></p>
In the above code snippet, we have a GridView
and a Button
. In the GridView
, we have added the OnRowDataBound
event that fires the ReSelectSelectedRecords
server side event. As we have set AutoGenerateColumns
to false
, we are explicitly writing the columns of the GridView
. The first column will have the CheckBox
that will be used by the user to select the GridView
record.
Code Behind
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GetData();
}
}
protected void PaginateTheData(object sender, GridViewPageEventArgs e)
{
List<int> list = new List<int>();
if (ViewState["SelectedRecords"] != null)
{
list = (List<int>)ViewState["SelectedRecords"];
}
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkSelect");
var selectedKey =
int.Parse(GridView1.DataKeys[row.RowIndex].Value.ToString());
if (chk.Checked)
{
if (!list.Contains(selectedKey))
{
list.Add(selectedKey);
}
}
else
{
if (list.Contains(selectedKey))
{
list.Remove(selectedKey);
}
}
}
ViewState["SelectedRecords"] = list;
GridView1.PageIndex = e.NewPageIndex;
this.GetData();
}
private void GetData()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "SELECT AutoId, FirstName, LastName, Age, Active " +
"FROM PersonalDetail ORDER By AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void GetSelectedRecords(object sender, EventArgs e)
{
Response.Write("<h3>Selected records</h3>");
List<int> list = ViewState["SelectedRecords"] as List<int>;
if (list != null)
{
foreach (int id in list)
{
Response.Write(id.ToString() + "<br />");
}
}
}
protected void ReSelectSelectedRecords(object sender, GridViewRowEventArgs e)
{
List<int> list = ViewState["SelectedRecords"] as List<int>;
if (e.Row.RowType == DataControlRowType.DataRow && list != null)
{
var autoId = int.Parse(GridView1.DataKeys[e.Row.RowIndex].Value.ToString());
if (list.Contains(autoId))
{
CheckBox chk = (CheckBox)e.Row.FindControl("chkSelect");
chk.Checked = true;
}
}
}
When the page loads, the records are populated into the GridView
under the Not IsPostBack
condition.
PaginateTheData() method
When the page numbers link of the GridView
is clicked, the PaginateTheData
method fires that checks for the selected records by looping through all the rows of the GridView
and finding the checkbox checked status. If the checkbox is checked, that item is added into the list (a Generic List
collection of integer data type) and if not, we are making sure that it has been removed in case the user had checked earlier and paginated and now has unchecked.
To persist the checkbox checked status, we need a mechanism to save the selected records so that in the next paging post back, we can retrieve it. For this purpose, we have saved the checked (selected) records into the Generic collection (list) and saved into the ViewState.
If the user is navigating to other pages, we need to make sure that the selected record's ID is saved into the List
and ultimately stored into the ViewState, so for that purpose, we check for the existing selected records and add the newly selected records into the collection and save into the ViewState.
The last part of this method sets the newly selected page index and re-populates the data to the GridView
.
ReSelectSelectedRecords() method
This method fires on the OnRowDataBound
event and retrieves the currently selected records from the ViewState and checks the checkbox of the records if it was previously selected.
GetSelectedRecords() method
This method fires on the click of the button and retrieves the selected records from the ViewState, loops through, and prints it on the screen.
Now when we run this page, we get output as shown below:
On the first page, the records with AutoID 3 and 5 have been selected.
On the second page, the record with AutoId 14 has been selected. Now when we navigate to the first page again, notice that the checkbox status is persisted and the records with AutoId 3 and 5 are checked. On the click of the button, all the checked records' AutoIds are printed on the page.
This article has been written based on this ITFunda.com article.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.