ASP.NET2.0下含有CheckBox的GridView删除选定记录实例

  前台代码 :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" PageSize="5"                       Width="726px" AllowPaging="True" AllowSorting="True"
  DataKeyNames="DB1_1,DB1_2"        Height="279px" >
                        <Columns>
                           <asp:TemplateField HeaderText="序号" >
                              <ItemTemplate>
             <%# this.GridView1.PageIndex * this.GridView1.PageSize + this.GridView1.Rows.Count + 1%>
                               </ItemTemplate>
                         </asp:TemplateField>
                          <asp:TemplateField  HeaderText="选择" >
                                <ItemTemplate>
                                   <asp:CheckBox ID="chkSelect" runat="server" ></asp:CheckBox>
                                </ItemTemplate>
                            </asp:TemplateField>
                         <asp:TemplateField HeaderText="操作" ShowHeader="False">
                            <ItemTemplate>
              <asp:LinkButton ID="lbtnDelete" runat="server" CausesValidation="False" CommandName="Delete"
                                Text="删除" ></asp:LinkButton>
                         </ItemTemplate>
                        </asp:TemplateField>
                      </Columns>
                     <AlternatingRowStyle BackColor="Aquamarine" />
                    </asp:GridView>

 <asp:CheckBox ID="chkSelectAll" runat="server" Text="全部选中"  AutoPostBack="True" ></asp:CheckBox>
    <asp:Button ID="btnDelete" runat="server" Text="删除"   />

后台代码:
   protected void btnDelete_Click(object sender, EventArgs e)
     {
        string strDelete = "";
4         for (int i = 0; i < this.GridView1.Rows.Count; i++)
5         {
6             string Label;
7             bool isChecked = ((CheckBox)GridView1.Rows[i].FindControl("chkSelect")).Checked;
8             Label = ((Label)GridView1.Rows[i].FindControl("labXH")).Text;
9             if (isChecked)
10             {
11                strDelete = "DB1_1" + "=" + Label;
12             }
13         }
14         conn.RunSql("Delete from DB1 where " + strDelete
15         this.chkSelectAll.Checked = false;
16         GridViewBind();
17     }
18 
19   protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
20     {
21         //遍历GridView行获取CheckBox属性
22     for (int i = 0; i < this.GridView1.Rows.Count; i++)
23         {
24             ((CheckBox)GridView1.Rows[i].FindControl("chkSelect")).Checked = this.chkSelectAll.Checked;
25         }
26     }

你可能感兴趣的:(checkbox)