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.