程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Winform中DataGridView多行刪除

Winform中DataGridView多行刪除

編輯:C#入門知識

在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


摘自 白雲飄飄

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved