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     }
 

 

你可能感兴趣的:(checkbox)