在GridView分页时,维护CheckBoxes控件的选择状态
| [日期:2007-03-16] | 来源:http://www.cnmaster.net 作者:cnmaster | [字体:大 中 小] | 
在GridView分页时,维护CheckBoxes控件的选择状态
    GridView可以在模板里使用CheckBox控件,但是很遗憾的是,如果GridView使用了分页功能,那么在选择不同的分页后,原先选择的CheckBox控件状态,系统将不再维护,本文就来解决这个问题。
下面代码显示了GridView的使用
<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>
请注意这里AllowPaging设置为true,表示启用了分页,而且分页大小为5。DataKeyNames设置为CategoryID,因为他是数据库使用的主键。
下一步,我们看看如何使用后台代码,首先定义一个常量
/* QUERY */
private const string QUERY_SELECT_ALL_CATEGORIES = "SELECT * FROM Categories";
这个常量在BindData里使用用来获取数据源
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();
}
保存CheckBox的值
  GridView在分页过程中并不维护CheckBox的选择状态,幸运的是,我们可以使用Session来维护CheckBox的状态, 这个功能使用RememberOldValues完成
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;
}
还原CheckBox的状态
   下一步,需要定义一个方法来还原Checkbox的状态值
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;
  }
  }
  }
}
最后,在分页事件里调用上面两个方法
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
  RememberOldValues();
  GridView1.PageIndex = e.NewPageIndex;
  BindData();
  RePopulateValues();
}
下图显示了运行结果


 
                    
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号