GridView翻页时保持CheckBox选择状态

//定义翻页bool
1 private bool changed = false ;
//定义保存选择项主键集合属性
1 protected List < string > SelectedItems
2     {
3       get { return ViewState["selecteditems"]!=null ? (List<string>)ViewState["selecteditems"] : null; }
4        set { ViewState["selecteditems"] = value; }
5    }
//获取选择项主键
1 private void GetSelectedItem()
2 {
3 List<string> selecteditems = null;
4 if (this.SelectedItems == null)
5 {
6    selecteditems = new List<string>();
7 }

8 else
9 {
10    selecteditems = this.SelectedItems;
11 }

12
13 //获取选择的记录
14     for (int i = 0; i < this.gvwResult.Rows.Count; i++)
15    {
16           CheckBox cbx = (CheckBox)this.gvwResult.Rows[i].FindControl("chkSelect");
17
18            string id = this.gvwResult.DataKeys[i].Values[0].ToString();
19
20            if (selecteditems.Contains(id) && !cbx.Checked)
21                selecteditems.Remove(id);
22            if (!selecteditems.Contains(id) && cbx.Checked)
23                selecteditems.Add(id);
24        }

25        this.SelectedItems = selecteditems;
26}
//在 DataBinding事件中执行GetSelectedItem()
1 protected void gvwResult_DataBinding( object sender, EventArgs e)
2     {
3        GetSelectedItem();
4    changed=true;
5    }
//在行绑定时确定CheckBox选中状态
1 protected void gvwResult_RowDataBound( object sender, GridViewRowEventArgs e)
2     {     
3        if (e.Row.RowIndex > -1 && this.SelectedItems!= null)
4        {          
5            CheckBox cbx = (CheckBox)e.Row.FindControl("chkSelect");
6            string id = this.gvwResult.DataKeys[e.Row.RowIndex].Values[0].ToString();
7            if (SelectedItems.Contains(id))
8                cbx.Checked = true;
9            else
10                cbx.Checked = false;
11        }

12    }
//根据changed确定是否再执行GetSelectedItem(),否则不翻页时选择项获取不到.
1 protected void btnConfirm_Click( object sender, EventArgs e)
2     {
3      if(!changed)
4        GetSelectedItem();
5      foreach (string id in (List<string>)this.SelectedItems)
6        {
7                  //..
8                 }

9     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值