首页 > 代码库 > Winform中DataGridView多行删除

Winform中DataGridView多行删除

//在DataGridView中删除选中行,从数据库中删除。private void ButtonDelete_Click(object sender, EventArgs e){    if (dataGridView1.DataSource == null || dataGridView1.CurrentRow == null)    {        return;    }    else    {        if (this.dataGridView1.SelectedRows.Count > 0)        {            DialogResult dr = MessageBox.Show("确定删除选中的记录? ", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);            if (dr == DialogResult.OK)            {                try                {                    dbcon.Open(); //打開連接                    string sql = "";                    OracleCommand cmd = dbcon.CreateCommand();                    //遍历所选中的dataGridView记录行                    foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)                    {                        //取dataGridView1中的第三列的值                        string strName = row.Cells[2].Value.ToString();                        sql = "delete from company where name=‘" + strName + "‘";                        cmd.CommandType = System.Data.CommandType.Text;                        cmd.CommandText = sql;                        cmd.ExecuteNonQuery(); //执行删除                    }                    cmd.Dispose();                }                catch (Exception ex)                {                    MessageBox.Show(ex.ToString(), "提示");                }                finally                {                    dbcon.Close(); //關閉連接                    dbcon = null; //釋放資源                }                //删除后执行刷新操作                this.ButtonFresh_Click(null, null);             }            else            {                return;            }        }    }}

  

Winform中DataGridView多行删除