2016-08-18 59 views
-2

我一直在處理這段代碼幾個小時,現在它顯示的信息框已被成功刪除,但它不會刪除數據庫我似乎無法找到我出錯的地方。從數據庫中刪除選定的行數據

private void simpleButton5_Click(object sender, EventArgs e) 
    { 
     for (int i = 0; i < dataGridView1.Rows.Count; i++) 
     { 
      DataGridViewRow delrow = dataGridView1.Rows[i]; 
      if (delrow.Selected == true) 
      { 
       //A YesNo enabled messagebox 
       DialogResult dialogResult = DevExpress.XtraEditors.XtraMessageBox.Show("Are you sure you want delete the selected client's information?", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); 
       //An if statement for a yes selected button on the messagebox 
       if (dialogResult == DialogResult.Yes) 
       { 
        dataGridView1.Rows.RemoveAt(i); 
        try 
        { 
         Conn.Open(); 
         SqlCommand Scd = new SqlCommand("Delete From Client WHERE ClientID=" + i + "" ,Conn); 
         Scd.ExecuteNonQuery(); 
         Conn.Close(); 
         DevExpress.XtraEditors.XtraMessageBox.Show("You have successfully deleted the selected client's information on the system", " ", MessageBoxButtons.OK, MessageBoxIcon.Information); 
        } 
        catch (Exception ex) 
        { 
         DevExpress.XtraEditors.XtraMessageBox.Show(ex.ToString()); 
        } 
        } 
       //An if statement for a no selected button on the messagebox 
       else if (dialogResult == DialogResult.No) 
       { 
        //Closing this form and opening the main menu form 
        this.Hide(); 
        MainMenu mm = new MainMenu(); 
        mm.ShowDialog(); 
        this.Close(); 
        this.Dispose(); 
       } 
      } 
     } 
    } 
+0

您已經將您提供給用戶的數據視圖與實際數據混合在一起。一個DataAdapter可以讓你擺脫所有的代碼:'myDA.Update(myDT);' – Plutonix

回答

4

ClientID很可能不是i(這只是行索引)。從行數據中獲取真實的客戶端ID。

int clientID = (int)dataGridView1.Rows[i].Cells[indexOfClientIDColumn].Value; 
SqlCommand Scd = 
    new SqlCommand("Delete From Client WHERE ClientID=" + clientID , Conn); 

或按名稱獲取

int clientID = (int)dataGridView1.Rows[i].Cells["ClientID"].Value; 

右列,也更好地利用command parameters

+0

非常感謝你 – TheBells

5
"Delete From Client WHERE ClientID=" + i + "" 

您刪除與客戶端ID = i一行。但等待什麼i?它是你的for循環中的臨時變量。因此,除非您的數據網格視圖包含數據庫中的所有行,並且ID以1開頭,並且每次您將刪除其他客戶端的數據時,ID都會加1。

您可能會做類似WHERE ClientID=" + delrow["ClientID"]或其他您可以獲得實際ID的方式。

但作爲一個方面說明。幫你一個忙,並使用Parameterized Sql來防止sql注入。

2

根據你的循環,你的變量i的rowIndex,它總是會爲0,1,2,3,4 ... N

IMO,我不認爲你得到了客戶端ID與您的客戶表中的值。你可以仔細檢查一下你是否擁有和那些相同的鍵值。

你需要從你的「的DataGridViewRow」

2

我相信得到的客戶端ID後面的錯誤是在這裏:

SqlCommand Scd = new SqlCommand("Delete From Client WHERE ClientID=" + i + "" ,Conn);

你傳入的客戶端ID DataGrid的線,而不是真實ID。

+0

好吧,我明白,任何建議,我怎麼可以實際修復代碼 – TheBells