使用复选框删除gridview中的多个行

我使用以下代码执行我的查询,使用复选框删除gridview中的多个值,但当我执行以下时,它说checkbox1.checked是假但我检查。 它不会删除我选择的值

这是我的代码和脚本部分

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { grd_bnd(); } } private void grd_bnd() { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString); SqlCommand cmd = new SqlCommand("select * from student", con); con.Open(); SqlDataAdapter adp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adp.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); con.Close(); } protected void Button3_Click(object sender, EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete"); if (checkbox1.Checked) { int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString()); //CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1"); SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString); SqlCommand cmd = new SqlCommand("delete from student where rollno = @rollno ", con); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@rollno", SqlDbType.Int).Value = rollno.ToString(); con.Open(); cmd.ExecuteNonQuery(); con.Close(); cmd.Dispose(); } } grd_bnd(); } } 

这是脚本

           <asp:Label ID="lblname" runat ="server" Text='' />     <asp:Label ID="lblrollno" runat ="server" Text='' />     <asp:Label ID="lblbatch" runat ="server" Text='' />     <asp:Label ID="lblcourse" runat ="server" Text='' />       

试试这种方式

  for (int i = 0; i < GridView1.Rows.Count; i++) { CheckBox checkboxdelete = ((CheckBox)GridView1.Rows[i].FindControl("checkboxdelete")); if (checkboxdelete.Checked == true) { Label lblrollno = ((Label)GridView1.Rows[i].FindControl("lblrollno")); int rolNo = Convert.ToInt32(lblrollno.Text); SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString); SqlCommand cmd = new SqlCommand("delete from student where rollno = @rollno ", con); cmd.CommandType = CommandType.Text; SqlParameter param = new SqlParameter("@rollno", SqlDbType.Int); param.Value = rolNo; cmd.Parameters.Add(param); con.Open(); cmd.ExecuteNonQuery(); con.Close(); cmd.Dispose(); } } 

对我有用的是按钮点击事件的代码:

  foreach (GridViewRow row in GridView1.Rows) { CheckBox checkboxdelete = (CheckBox)row.FindControl("checkboxdelete"); if (checkboxdelete.Checked == true) { using (SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["CS"].ConnectionString)) { scon.Open(); Label LblId = (Label)row.FindControl("rollno"); int rollno = Convert.ToInt32(LblId.Text); SqlCommand scmd = new SqlCommand("delete from student where rollno = @rollno", scon); scmd.Parameters.AddWithValue("@rollno", rollno); scmd.ExecuteNonQuery(); scon.Close(); BindGrid(); Label4.Text = ""; } } else { Label4.Text = "No record is selected to delete !"; Label4.ForeColor = System.Drawing.Color.Red; } }