Method 1:
Background code:
Copy codeThe Code is as follows: protected void btn_delete_Click (object sender, EventArgs e)
{
For (int I = 0; I <this. GridView1.Rows. Count; I ++)
{
Int id = Convert. ToInt32 (this. GridView1.DataKeys [I]. Value );
If (this. GridView1.Rows [I]. Cells [0]. FindControl ("CheckBox1") as CheckBox). Checked = true)
{
Delete (id );
ClientScript. RegisterStartupScript (GetType (), "prompt", "<script> alert ('deleted successfully! ') </Script> ");
}
}
This. GridView1.DataBind ();
} // Delete
Private void Delete (int id)
{
Using (SqlConnection conn = new SqlConnection (str ))
{
Conn. Open ();
SqlCommand comm = conn. CreateCommand ();
Comm. CommandText = "delete from Notice_Msg where id = @ id ";
Comm. Parameters. Add (new SqlParameter ("@ id", id ));
Comm. ExecuteNonQuery ();
}
}
Front-end code:Copy codeThe Code is as follows: <asp: GridView ID = "GridView1" runat = "server" DataKeyNames = "id">
In addition, you must add a column so that the bound field is id and set the visable attribute of this column to false.
Method 2:
Background:Copy codeThe Code is as follows: protected void btn_delete_Click (object sender, EventArgs e)
{
Foreach (GridViewRow row in this. GridView1.Rows)
{
If (row. RowType = DataControlRowType. DataRow)
{
CheckBox ckb = row. Cells [2]. FindControl ("CheckBox1") as CheckBox;
If (ckb. Checked)
{
Using (SqlConnection sqlCnn = new SqlConnection (str ))
{
Using (SqlCommand sqlCmm = sqlCnn. CreateCommand ())
{
SqlCmm. CommandText = "delete from Regime_Table where id = '" + row. Cells [0]. Text + "'";
SqlCnn. Open ();
Int a = sqlCmm. ExecuteNonQuery ();
If (a> 0)
{
ClientScript. RegisterStartupScript (GetType (), "prompt", "<script> alert ('deleted successfully! ') </Script> ");
}
Else
{
ClientScript. RegisterStartupScript (GetType (), "prompt", "<script> alert ('deletion failed! ') </Script> ");
}
This. DataBind ();
}
}
}
}
}
}
Front-end:Copy codeThe Code is as follows: <style type = "text/css">
. Hidden
{
Display: none;
}
</Style>
<Asp: BoundField DataField = "id" HeaderText = "no.">
<HeaderStyle CssClass = "Hidden"/>
<ItemStyle CssClass = "Hidden"/>
</Asp: BoundField>
Add one column. This column is bound to the id field. The value of the visable attribute cannot be false. Otherwise, no value can be obtained.
All checkbox functions:Copy codeThe Code is as follows: <script type = "text/jscript">
Function change (sender ){
Var table = document. getElementById ("GridView1 ");
For (var I = 1; I <table. rows. length; I ++ ){
Table. rows [I]. cells [1]. getElementsByTagName ("input") [0]. checked = sender. checked;
}
}
</Script>
<HeaderTemplate>
<Input id = "Checkbox2" type = "checkbox" onclick = "change (this)"/>
Select All
</HeaderTemplate>