Search This Blog

Thursday, August 26, 2010

Maintaining State of CheckBoxes While Paging in a GridView Control

Every time its difficult to work with the checkbox control inside the gridview with paging, In this article, I will demonstrate how you can maintain the state of Check Boxes while paging in a GridView control.

You need to bind your gridview using your own method.
Here, I have used the method to bind the gridview is "BindData();"

Your grid view may want to be like this

<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" AllowPaging="True" 
PageSize="5" Width="324px" DataKeyNames="CategoryID"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Save Checked Values

private void GetOldValues()
{
  ArrayList categoryIDList = new ArrayList();
  int index = -1;
  foreach (GridViewRow row in GridView1.Rows)
  {
   index = (int) GridView1.DataKeys[row.RowIndex].Value;
   bool result = ((CheckBox)row.FindControl("CheckBox1")).Checked;

  // Check in the Session
  if (Session[CHECKED_ITEMS] != null)
   categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
  if (result)
  {
  if (!categoryIDList.Contains(index))
   categoryIDList.Add(index);
  }
  else
   categoryIDList.Remove(index);
  }
  if (categoryIDList != null && categoryIDList.Count > 0)
   Session[CHECKED_ITEMS] = categoryIDList;
}

Re-Populate CheckBoxes

private void PopulateValues()
{
  ArrayList categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
  if (categoryIDList != null && categoryIDList.Count > 0)
  {
  foreach (GridViewRow row in GridView1.Rows)
  {
   int index = (int)GridView1.DataKeys[row.RowIndex].Value;
  if (categoryIDList.Contains(index))
  {
   CheckBox myCheckBox = (CheckBox) row.FindControl("CheckBox1");
   myCheckBox.Checked = true;
  }
  }
  }
}

GridView Page_IndexChanging Event

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
  GetOldValues();
  GridView1.PageIndex = e.NewPageIndex;
  BindData();
  PopulateValues();
}

The above method first calls GetOldValues so that all primary keys of the checked CheckBoxes will be saved in a Session object. Next ,the page goes to the new GridView page, and finally, we populate the CheckBoxes using the PopulateValues method.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.