HTML:
<body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridSign" runat="server" AutoGenerateColumns="False" onselectedindexchanged="GridSign_SelectedIndexChanged" DataSourceID="SqlDataSource1"> <Columns> <asp:TemplateField> <EditItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </EditItemTemplate> <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="ID">//绑定主键的列,可以隐藏 <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("id") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="labid" runat="server" Text='<%# Bind("id") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="name" HeaderText="姓名" /> <asp:BoundField DataField="sex" HeaderText="性别" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:zhenji %>" SelectCommand="SELECT * FROM [tryuser]" DeleteCommand="delete from [tryuser] where id=@id" > <DeleteParameters> <asp:Parameter Type="String" Name="id"/> </DeleteParameters> </asp:SqlDataSource> <asp:Button ID="Button1" runat="server" Text="Delete" onclick="Button1_Click" /> </div> </form> </body>
后台C#:
protected void Button1_Click(object sender, EventArgs e) { foreach (GridViewRow row in GridSign.Rows) { Label id = row.FindControl("labid") as Label;//将主键绑定在一列上 CheckBox chkb=row.FindControl("CheckBox1") as CheckBox; if(chkb.Checked&&chkb!=null) { SqlDataSource1.DeleteParameters["id"].DefaultValue=id.Text; SqlDataSource1.Delete(); } } }