GridView中添加一个CheckBox列,翻页后保存选中状态


 2 using  System;
 3 using  System.Data;
 4 using  System.Configuration;
 5 using  System.Collections;
 6 using  System.Web;
 7 using  System.Web.Security;
 8 using  System.Web.UI;
 9 using  System.Web.UI.WebControls;
10 using  System.Web.UI.WebControls.WebParts;
11 using  System.Web.UI.HtmlControls;
12
13 public   partial   class  GridSamples_GridView_CheckBoxColumn : System.Web.UI.Page
14 {
15    /**//// <summary>
16    /// 获取或设置选中项的集合
17    /// </summary>

18    protected ArrayList SelectedItems
19    {
20        get
21        {
22            return (ViewState["mySelectedItems"!= null? (ArrayList)ViewState["mySelectedItems"] : null;
23        }

24        set
25        {
26            ViewState["mySelectedItems"= value;
27        }

28    }

29
30    protected void Page_Load(object sender, EventArgs e)
31   {
32        
33    }

34
35
36    protected void GridView1_DataBinding(object sender, EventArgs e)
37    {
38        //在每一次重新绑定之前,需要调用CollectSelected方法从当前页收集选中项的情况
39        CollectSelected();
40    }

41
42   
43    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
44    {
45        //这里的处理是为了回显之前选中的情况
46        if (e.Row.RowIndex > -1 && this.SelectedItems!=null)
47        {
48            DataRowView row = e.Row.DataItem as DataRowView;
49            CheckBox cb = e.Row.FindControl("CheckBox1"as CheckBox;
50            if(this.SelectedItems.Contains(row["id"].ToString()))
51                cb.Checked = true;
52            else
53                cb.Checked = false;
54        }

55    }

56    /**//// <summary>
57    /// 从当前页收集选中项的情况
58    /// </summary>

59    protected void CollectSelected()
60    {
61        ArrayList selectedItems = null;
62        if (this.SelectedItems == null)
63            selectedItems = new ArrayList();
64        else
65            selectedItems = this.SelectedItems;
66
67        for (int i = 0; i < this.GridView1.Rows.Count; i++)
68        {
69            string id = this.GridView1.Rows[i].Cells[1].Text;
70            CheckBox cb = this.GridView1.Rows[i].FindControl("CheckBox1"as CheckBox;
71            if (selectedItems.Contains(id) && !cb.Checked)
72                selectedItems.Remove(id);
73            if (!selectedItems.Contains(id) && cb.Checked)
74                selectedItems.Add(id);
75        }

76        this.SelectedItems = selectedItems;
77    }

78
79    protected void Button1_Click(object sender, EventArgs e)
80    {
81        //最后,需要对选中项进行操作之前,不能忘了还要最后一次收集当前页的选中情况
82        CollectSelected();
83
84       this.TextBox1.Text = string.Empty;
85        foreach (object tmp in this.SelectedItems)
86            this.TextBox1.Text += tmp.ToString() + ",";
87    }

88}

89

你可能感兴趣的:(checkbox)