2013-01-02 51 views
0

我有一個C#中的datagridview顯示查詢數據庫的結果。我想刪除數據,並且此方法使用DataSet。此方法在某個索引中按下按鈕時執行。錯誤刪除C中的數據行#

代碼:

DialogResult _result = MessageBox.Show("Do you want to remove the data?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); 
if (_result == DialogResult.OK) 
{ 
    int idx = dataGridInfo.CurrentRow.Index; 
    this.getInfoFilmDS.sp_getInfo.Rows.RemoveAt(idx); 
    MessageBox.Show("Data Removed", "Processing", MessageBoxButtons.OK, MessageBoxIcon.Information); 
} 

這種方法

this.getInfoFilmDS.sp_getInfo.Rows.RemoveAt(idx); 

在DataGridView中唯一的工作,但數據本身在數據庫中不會被刪除。

如何解決此問題?

在此先感謝。

UPDATE我已經改變語法到這一點:

this.getInfoFilmDS.sp_getInfo.Rows[idx].Delete(); 
sp_getInfoTableAdapter.Adapter.Update(getInfoFilmDS); 

但是編譯器會引發錯誤。

Invalid Operation Exception Update requires a valid DeleteCommand when passed DataRow collection with deleted rows. 
+0

你是否實現了一些使用ado.net在數據庫上刪除的方法? –

+0

你在哪裏處理你的mySql命令從數據庫中刪除行???你沒有做任何事情用後端(MySql)刪除行.. –

+0

@felipe這是基於數據庫中的存儲過程自動生成的xsd文件。 – randytan

回答

0

DataRowCollection.RemoveAt不只是從DataTable刪除行,它不會刪除該行(即使你可以使用一個DataAdapter)。因此,你需要使用DataRow.Delete

getInfoFilmDS.sp_getInfo.Rows[idx].Delete(); 

請注意,您現在需要使用DataAdapter提交的DataSet更改到數據庫。

更新

i've change the syntax into this:

this.getInfoFilmDS.sp_getInfo.Rows[idx].Delete(); 
sp_getInfoTableAdapter.Adapter.Update(getInfoFilmDS); 

但是編譯器會引發錯誤:

Invalid Operation Exception. Update requires a valid DeleteCommand when passed DataRow collection with deleted rows.

所以,你需要定義DeleteCommand這通常是從DataSet自動生成的,當你只能選擇一張桌子,也許你只需要重新配置TableAdapter,它會自動創建刪除命令。否則,您必須手動創建它:

TableAdapter Overview

+0

然後,因爲它來自自動xsd,我無法找到我的DataAdapter。如何解決這個問題? – randytan

+0

有一個自動生成的名稱空間「xzyTableAdapters」。你必須爲這張桌子尋找合適的桌子適配器。創建一個實例並使用它來更新數據集或數據表或數據行。它將提交對數據庫的所有更改(RowState的所有行都是!=不變)。 –

+0

好吧,我已將語法更改爲: this.getInfoFilmDS.sp_getInfo.Rows [idx] .Delete(); sp_getInfoTableAdapter.Adapter.Update(getInfoFilmDS); – randytan

0

研究,並要求@Tim的支持後,好吧,這表明,基於存儲過程的DataSet不產生查詢(請告訴我,如果我錯了: D)所以,我需要生成另一個存儲過程的基礎上JOIN表..

有三個表在我的MySQL數據庫,我創建另一個存儲過程刪除數據。然後我的刪除存儲過程分配到數據集的配置

然後應用這個代碼

try 
      { 
       int idx = dataGridInfo.CurrentRow.Index; 
       this.getInfoFilmDS.sp_getInfo.Rows[idx].Delete(); 
       sp_getInfoTableAdapter.Adapter.Update(getInfoFilmDS); 
       MessageBox.Show("Data removed", "Process", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error Delete Data" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 

它就像一個魅力。