When you switch to a different page, all of the controls for the current page are destroyed. The
GridView
does not maintain any state for pages which are not displayed.
You will need to handle the
PageIndexChanging event[
^], extract the selected rows from the current page, and store them somewhere. Then, when you want to get all selected rows, retrieve the stored selection from the other pages and combine it with the selected rows on the current page.
For example:
private Dictionary<int, List<string>> PageSelections
{
get
{
var value = (Dictionary<int, List<string>>)Session["SelectedPIDs"];
if (value == null)
{
value = new Dictionary<int, List<string>>();
Session["SelectedPIDs"] = value;
}
return value;
}
}
private List<string> ExtractSelectedRows()
{
var result = new List<string>();
foreach (GridViewRow row in datatable.Rows)
{
if (row.RowType != DataControlRowType.DataRow) continue;
CheckBox check = (CheckBox)row.FindControl("chkSelect");
if (!check.IsSelected) continue;
Label lbl_productid = (Label)row.FindControl("lbl_productid");
result.Add(lbl_productid.Text);
}
return result;
}
protected void datatable_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
PageSelections[datatable.PageIndex] = ExtractSelectedRows();
}
protected void datatable_DataBound(object sender, EventArgs e)
{
List<string> selectedRows;
if (!PageSelections.TryGetValue(datatable.PageIndex, out selectedRows)) return;
if (selectedRows.Count == 0) return;
foreach (GridViewRow row in datatable.Rows)
{
if (row.RowType != DataControlRowType.DataRow) continue;
CheckBox check = (CheckBox)row.FindControl("chkSelect");
Label lbl_productid = (Label)row.FindControl("lbl_productid");
check.IsSelected = selectedRows.Contains(lbl_productid.Text);
}
}
private IEnumerable<string> GetAllSelectedRows()
{
Dictionary<int, List<string>> pageSelections = PageSelections;
pageSelections[datatable.PageIndex] = ExtractSelectedRows();
return pageSelections.SelectMany(pair => pair.Value);
}