To select multiple records from the GridView and persist the selection across different pages, we can follow this approach.
GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data.
Get hundreds of ASP.NET Tips and Tricks and ASP.NET Online training here.
Similar article is also written by Kasarlaravi on this topic with different approach, please click Maintaining State of Checkboxes in a pagination enabled GridView to read.
This article is the part of my series of article that I am keep writing since last several weeks. To demonstrate this example, we are going to create a demo web page and my GridView code looks like below.
ASPX PAGE
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
DataKeyNames="AutoId" OnPageIndexChanging="PaginateTheData" EnablePersistedSelection="true"
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 OnRowDataBound
event
that fires ReSelectSelectedRecords
server side event.
In the page loads, the records are populated into the GridView under Not IsPostback condition.
CODE BEHIND
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GetData();
}
}
/// <summary>
/// Paginates the data.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewPageEventArgs"/> instance containing the event data.</param>
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();
// get the connection
using (SqlConnection conn = new SqlConnection(_connStr))
{
// write the sql statement to execute
string sql = "SELECT AutoId, FirstName, LastName, Age, Active FROM PersonalDetail ORDER By AutoId";
// instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
// get the adapter object and attach the command object to it
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
// fire Fill method to fetch the data and fill into DataTable
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
/// <summary>
/// Gets the selected records.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
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 />");
}
}
}
/// <summary>
/// Looks for selection.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
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;
}
}
}
PaginateTheData()method
When the page numbers links are 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 (Generic List collection of integer data type) and if not we are making sure that it has been removed in case user had checked earlier and unchecked again.
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 user is navigating to other pages, we need to make sure that the selected records id is saved into the
List and ultimately stored into the ViewState
, so for that purpose we have checked for the existing
selected records and added the newly selected records into the collection and saved 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 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, loop
through and prints it on the screen.
OUTPUT


On first page, record with AutoID 3 and 5 have been selected
On second page, record with AutoId 14 has been selected. Now when we navigate to the first page again, notice that the checkbox status is persisted
and record with AutoId 3 and 5 are checked
. On click of the button, all the checked records AutoIds are being printed on the page.
Thanks for reading, hope you liked it.
Keep reading my forth coming articles. To read my series of articles on ASP.NET,
click here.