当前位置:编程学习 > C#/ASP.NET >>

Winform中DataGridView多行删除

在DataGridView中删除选中行,从数据库中删除。
        #region 在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.OpenConn(); //打开Oracle连接
                                foreach (DataGridViewRow row in this.dataGridView1.SelectedRows) //遍历所选中的dataGridView记录行
                                {
                                    string strName = row.Cells[2].Value.ToString();  //取dataGridView1中的第三列的值
                                    string sql = string.Format("delete from company where dname='{0}'", strName); //SQL语句
                                    OracleCommand cmd = new OracleCommand(sql, conn);
                                    cmd.ExecuteNonQuery();  //执行删除操作
                                    cmd.Dispose();
                                }                      
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString(), "提示");
                        }
                        finally
                        {
                            dbcon.CloseConn();  //关闭Oracle连接
                        }
                        this.ButtonFresh_Click(null,null); //删除后执行刷新操作  //ButtonFresh是刷新按钮的名字  ,刷新方法在此就不写了。
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
        #endregion


摘自 白云飘飘
补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,