2010-01-10 34 views
1

我是一個數據庫編程noob。我需要從文本框字段中填充數據庫,但是當我嘗試將其提交到數據庫時,我會查看數據庫,看到的所有內容都爲空...沒有任何內容正在保存...請幫助..數據集不會提交到數據庫

謝謝

private void btnSubmit_Click(object sender, EventArgs e) 
    { 
     TradesDataSet.TradesRow newTradesRow = tradesDataSet.Trades.NewTradesRow(); 

     newTradesRow.ID = textBoxTradeID.Text; 
     newTradesRow.EntryPrice = textBoxEntryPrice.Text; 
     newTradesRow.ExitPrice = textBoxExitPrice.Text;    

     tradesDataSet.Trades.Rows.Add(newTradesRow); 
     tradesDataSet.Trades.AcceptChanges(); 

     try 
     { 

      this.Validate(); 
      this.tradesBindingSource.EndEdit(); 
      this.tradesTableAdapter.Update(this.tradesDataSet.Trades);     
      MessageBox.Show("Update successful"); 
     } 
     catch (System.Exception ex) 
     { 
      MessageBox.Show("Update failed"); 
     } 
    }   
+0

你爲什麼要明確由一個文本框設置ID?不應該是由數據庫設置的自動遞增字段嗎? – mpen 2010-01-10 06:15:06

+0

是的。我想最終這樣做。我甚至無法將任何東西保存到數據庫中... – Woody 2010-01-10 06:16:16

+1

作爲提示:DataSets arn'構建數據庫驅動應用程序的最佳方式。我一直在那裏,嘗試過它,並且它有很多缺點......使用System.Data.SqlClient namesace處理數據庫事務有一個更簡單和更好的方法。更容易控制acions並使用帶有參數的存儲過程,創建sql事務,從數據庫獲取daa等等,你應該閱讀它。 – GxG 2010-01-10 06:30:20

回答

7

刪除AcceptChanges呼叫。數據適配器的Update方法查看數據庫中的更改並使用更改列表更新實際數據庫。它會在更新後自動接受DataSet中的更改。如果您在更新之前手動撥打DataSet上的AcceptChangesDataAdapter會認爲沒有任何更改,並且不執行任何操作。

+0

我試過了。它仍然不起作用... :(謝謝,但我想我會採取GxG的建議和結帳SqlClient ... – Woody 2010-01-10 06:46:54

0
private void btnSubmit_Click(object sender, EventArgs e) 
{ 
    TradesDataSet.TradesRow newTradesRow = tradesDataSet.Trades.NewTradesRow(); 

    newTradesRow.ID = textBoxTradeID.Text; 
    newTradesRow.EntryPrice = textBoxEntryPrice.Text; 
    newTradesRow.ExitPrice = textBoxExitPrice.Text;    

    tradesDataSet.Trades.Rows.Add(newTradesRow); 
    //Wrong, this command says that what I have in the dataset is what is in 
    //the database. You only use this if you manually update the dataset in 
    //the background. 
    //tradesDataSet.Trades.AcceptChanges(); 

    try 
    { 
     //EndEdit then force a validate. 
     this.tradesBindingSource.EndEdit(); 
     this.Validate(); 
     //Internally this method calls .AcceptChanges(); 
     this.tradesTableAdapter.Update(this.tradesDataSet.Trades);     
     MessageBox.Show("Update successful"); 
    } 
    catch (System.Exception ex) 
    { 
     MessageBox.Show("Update failed"); 
    } 
}   
1

還有另一種可能性。如果您已將數據庫添加到項目中,並將其「複製到輸出目錄」屬性設置爲「始終」,那麼對數據庫所做的任何更改都將被恢復,因爲較新的副本被舊副本取代。

爲了防止這種設置該屬性爲「複製,如果新」或「不要複製」