DataList分页,保存CheckBox控件状态

1、DataList中嵌套CheckBox

<asp:DataList ID="dlNews" runat="server">                
    <HeaderTemplate>
      <table cellpadding="0" cellspacing="0"><tr><td align="center">复选框</td></tr></table>
    </HeaderTemplate>
    <ItemTemplate>
      <table cellpadding="0" cellspacing="0"><tr><td align="center">
        <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox1_CheckedChanged" />
      </td></tr></table>
    </ItemTemplate>
    <HeaderStyle HorizontalAlign="Center" />
 </asp:DataList>

2、CheckBox1_CheckedChanged函数

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
    RememberOldValues();
}

3、RememberOldValues()函数

using System.Collections;
 
 public void RememberOldValues()
 {
     ArrayList categoryIDList = new ArrayList();
     if (Session[subTable] != null)
     {
         categoryIDList = (ArrayList)Session[subTable];
     }
     int index = 0;
     foreach (DataListItem item in dlNews.Items)
     {
         index = item.ItemIndex + (Int32.Parse(labPage.Text) - 1) * 7;
         bool result = ((CheckBox)item.FindControl("CheckBox1")).Checked;
         if (result)
         {
             if (!categoryIDList.Contains(index))
             {
                 categoryIDList.Add(index);
             }
         }
         else
         {
             categoryIDList.Remove(index);
         }
     }
     if (categoryIDList != null && categoryIDList.Count > 0)
     {
         Session[subTable] = categoryIDList;
     }
 }
 
 其中:labPage.Text为当前页,数字“7”为一页显示的数量

4、复现保存的选择结果

private void RePopulateValues()
 {
     ArrayList categoryIDList = (ArrayList)Session[subTable];
     if (categoryIDList != null && categoryIDList.Count > 0)
     {
         foreach (DataListItem item in dlNews.Items)
         {
             int index = item.ItemIndex;
             if (categoryIDList.Contains(index + (Int32.Parse(labPage.Text) - 1) * 7))
             {
                 CheckBox myCheckBox = (CheckBox)item.FindControl("CheckBox1");
                 myCheckBox.Checked = true;
             }
         }
     }
 }
 此函数可以放在DataList的数据绑定函数中bind()
 protected void bind()
 {
     ......
     RePopulateValues();
 }

参考: 
http://zxianf.blog.163.com/blog/static/301207012010101112317730/
Asp.Net获取Session、Cookies、Application中值:
http://www.cnblogs.com/ZHF/archive/2009/11/12/1601486.html

posted on 2012-06-24 10:16  lianshisxq  阅读(166)  评论(0编辑  收藏  举报

导航