Buttonを使用してGridViewのCheckBox選択行を削除

1216 ワード

protected void Button3_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in this.GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox ckb = row.Cells[0].FindControl("CheckBox1") as CheckBox;
                if (ckb.Checked)
                {
                    int i = Convert.ToInt32(row.Cells[1].Text);
                    string str = ConfigurationManager.ConnectionStrings["studentConnectionString"].ConnectionString;
                    using (SqlConnection cnn = new SqlConnection(str))
                    {
                        SqlCommand cmm = cnn.CreateCommand();
                        cmm.CommandText = "delete from student where sid=@id";
                        SqlParameter param = new SqlParameter("@id", i);
                        cmm.Parameters.Add(param);
                        SqlDataAdapter da = new SqlDataAdapter(cmm);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        this.GridView1.DataBind();
                    }
                }
            }
        }
    }