关于Gridview中CheckBox全选的取消

时间:2022-02-21 09:53:24

在Gridview中经常会用到CheckBox,选中单行或者多行,在Gridview下面又增加一个CheckBox,点击全选,如图

关于Gridview中CheckBox全选的取消

但是,我遇到的问题是,全选之后又单击其中一个Checkbox,但是下面的全选checkbox并没有取消。上网查找解决方法,直接上代码:

前台代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:GridView ID="gv" runat="server" AutoGenerateColumns="False">
    <Columns>
      <asp:TemplateField>
      <ItemTemplate>
      <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True"
        oncheckedchanged="chk1_CheckedChanged"/>
      </ItemTemplate>
      </asp:TemplateField>
      <asp:BoundField DataField="no" HeaderText="学号" SortExpression="no" />
      <asp:BoundField DataField="name" HeaderText="姓名"/>
      <asp:BoundField DataField="age" HeaderText="年龄"/> 
      <asp:BoundField DataField="sex" HeaderText="性别"/>                
      <asp:BoundField DataField="addr" HeaderText="住址" />
  </Columns>
    </asp:GridView>
    全选<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True"
        oncheckedchanged="CheckBox2_CheckedChanged" />
    <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
    <asp:Button ID="btnDelete" runat="server" Text="Delete" />
    </form>
</body>
</html>

后台代码:

 public partial class Gridview : System.Web.UI.Page
    {
        string constr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bind();
            }
        }
        protected void bind()
        {
            string sql="select stu_no as no ,stu_name as name ,stu_age as age ,stu_sex as sex,stu_addr as addr from StudentInfo";
            gv.DataSource = SqlHelper.ExecuteDataset(constr,CommandType.Text,sql).Tables[0];
            gv.DataBind();
        }

        protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i <= gv.Rows.Count - 1; i++)
            {
                CheckBox cbox = (CheckBox)gv.Rows[i].FindControl("CheckBox1");
                if (CheckBox2.Checked == true)
                {
                    cbox.Checked = true;
                }
                else
                {
                    cbox.Checked = false;
                }
            }
        }
        protected void chk1_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkbox = (CheckBox)sender;
            if (checkbox.Checked == false)
            {
                CheckBox2.Checked = false;
            }
        }
    }
}