AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=774&pId=-1
Maintaining State of CheckBoxes While Paging in a GridView Control
page
by Mohammad Azam
Feedback
Average Rating: 
Views (Total / Last 10 Days): 111429/ 61

Creating the GridView Control

Checkbox selection inside the GridView control with no paging can be accomplished by writing a few lines of code. In this article, I will demonstrate how you can maintain the state of the CheckBoxes that are present inside the GridView with paging enabled.

The first thing you need to do is to create the GridView control. This can be done simply by dragging and dropping the GridView from the Toolbox onto the web form. Once you have the GridView, you can edit its columns using the smart tag or the HTML view of the page. I will add two bound columns and one template column. The bound columns "CategoryID" and "CategoryName" will be bound to the database fields "CategoryID" and "CategoryName" respectively. The template column will be used to display the CheckBoxes in the GridView control.

After adding the columns, the html source of the GridView control looks like this.

Listing 1: GridView HTML Code

<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>

Please also note that the paging is enabled in the GridView control, and the DataKeyNames property has been set to "CategoryID," since it’s the primary key in the database. The PageSize property has been set to 5, which means that after one page of the GridView can only contain 5 records/rows. The ItemTemplate tag contains the CheckBox whose ID is "CheckBox1," which means that CheckBoxes will be displayed for the last column.

Populating the GridView Control

Let’s first see how I am populating the GridView control. I have defined a query as a private string constant, which is shown below.

Listing 2: Query to Retrieve Information from the Categories Table

/* QUERY */
private const string QUERY_SELECT_ALL_CATEGORIES = "SELECT * FROM Categories";

The above query is used in the BindData method, which simply populates the GridView control with the DataSet object.

Listing 3: BindData Method to Populate the GridView Control

private void BindData()
{
  SqlConnection myConnection = new SqlConnection(ConnectionString);
  SqlDataAdapter ad = new SqlDataAdapter(QUERY_SELECT_ALL_CATEGORIES,
  myConnection);
  DataSet ds = new DataSet();
  ad.Fill(ds, "Categories");
  GridView1.DataSource = ds;
  GridView1.DataBind();
}
Remember Checked Values

The application will work fine if the number of pages is less than the page size. As soon as the paging kicks in, the GridView control will forget all the checked values of the old pages. You need some mechanism to store the previously checked values of the CheckBoxes. Fortunately, the Session variable can be used to store the checked values between postbacks.

Below, I have created a method, RememberOldValues, which iterates through the GridView rows and finds which values are checked. Once it gets the checked value, it stores the primary key of the table inside the Session object.

Listing 4: Save Checked Values

private void RememberOldValues()
{
  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;
}

Analysis

The first thing I did is to make an object of the ArrayList so that I can store the primary keys in it. You will need to include the System.Collections namespace in order to work with an ArrayList. After that, I loop through the GridView rows, checking to see which CheckBox is checked. Once I find the CheckBox that is checked, I insert the primary key, which in this case is "CategoryID," into the ArrayList. If the row is not checked, I get the "CategoryID" and remove it from the ArrayList. If the ArrayList is not null, then I put the ArrayList inside the Session object.

Re-Populate CheckBoxes

In the last method, RememberOldValues, we captured and saved the primary keys of all the rows that were checked. In the RePopulateValues method, we will retrieve the saved values and assign them to the CheckBoxes.

Listing 5: Re-Populate CheckBoxes

private void RePopulateValues()
{
  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;
  }
  }
  }
}

Analysis

The RePopulateValues method is quite simple. All we do is retrieve the ArrayList that is stored inside the Session object. After checking that the ArrayList is not null and contains some items, we iterate through the GridView control row by row. If the ArrayList contains the primary key of the row, then it means that row should have its CheckBox in a checked state. This is done by using the Contains method of the ArrayList. If the ArrayList contains the primary key, then we extract the control using the row.FindControl method and assign its checked property to true.

Implementing GridView Page_IndexChangingEvent

The last thing that we need to implement is the Page_IndexChangingEvent of the GridView control. Page_IndexChangingEvent is fired whenever paging occurs. The implementation of this method is given below.

Listing 6: GridView Page_IndexChanging Event

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

Analysis

The above method first calls RememberOldValues 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 RePopulateValues method.

You can see the effect in the screen shot below.

Figure 1: CheckBox Checked On First Page

Figure 2: CheckBox Checked On Second Page

Downloads

[Download Sample]

Summary

In this article, you learned how you can save the control properties that are lost because of the server calls. I have used the Session object to hold the values, but you can do the same with the ViewState object.

I hope you liked the article; happy coding!


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 10:31:52 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search