如何删除含有CheckBox的GridView选定记录

protected void Button2_Click(object sender, EventArgs e)
    {
        System.Web.UI.WebControls.CheckBox chkEport;
        if (Button2.Text == "全选")
        {
            foreach (GridViewRow gridviewrow in GridView1.Rows)
            {
                chkEport = (CheckBox)gridviewrow.FindControl("chkEport");
                chkEport.Checked = true;
            }
            Button2.Text = "取消";
        }
        else
        {
            foreach (GridViewRow gridviewrow in GridView1.Rows)
            {
                chkEport = (CheckBox)gridviewrow.FindControl("chkEport");
                chkEport.Checked = false;
            }
            Button2.Text = "全选";

        }
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        System.Web.UI.WebControls.CheckBox chkEport;
        foreach (GridViewRow gridviewrow in GridView1.Rows)
        {
            chkEport = (CheckBox)gridviewrow.FindControl("chkEport");
            if (chkEport.Checked)
            {
                int x = Convert.ToInt32(this.GridView1.DataKeys[gridviewrow.RowIndex].Value);
                string deleteStr = "delete from news where ID='" +x+ "'";
                SqlConnection myCon = DB.createConnection();
                SqlCommand myCom = new SqlCommand(deleteStr,myCon);
                myCon.Open();
                myCom.ExecuteNonQuery();
                myCon.Close();
            }
        }
        BindData();
    }


<asp:GridView ID="GridView1" runat="server" CellPadding="4" AutoGenerateColumns="False" ForeColor="#333333" GridLines="None" OnRowDeleting="GridView1_RowDeleting" DataKeyNames="id" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" Width="541px">
        <FooterStyle BackColor="#990000" ForeColor="White" Font-Bold="True" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <Columns>
            <asp:TemplateField ShowHeader="False">
                <ItemTemplate>
                    <asp:CheckBox ID="chkEport" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="id" HeaderText="新闻ID" />
            <asp:BoundField DataField="title" HeaderText="新闻标题" />
            <asp:BoundField DataField="releasetime" HeaderText="发表时间" />
        </Columns>
        <EmptyDataTemplate>
            没有任何数据!
        </EmptyDataTemplate>
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>


 

注意设置Button和CheckBox和GridView

你可能感兴趣的:(checkbox)