2012-02-16 154 views
0

我在winform項目中有以下形式,我有一個datagridview裏面,我有一個更新按鈕,我想推它來更新datagridview更改相應的表。標籤告訴我,記錄更新成功,但是當我查詢數據庫它不起作用。請有任何想法嗎? :從gridview更新數據庫

   private SqlConnection con; 
    private SqlCommandBuilder scbCust; 
    private SqlCommandBuilder scbOrd; 
    private DataSet dsCommon; 
    private SqlDataAdapter custAdapter; 
     private void MainForm_Load(object sender, EventArgs e) 
    { 
      con = new SqlConnection(ConfigurationManager.ConnectionStrings["EbosPr.Properties.Settings.Database1ConnectionString1"].ConnectionString); 

     // Creating bridge between Server and DataSet 
     custAdapter = new SqlDataAdapter("SELECT * FROM dbo.CustCalls", con); 


     // SqlCommandBuilder that can create Update commands 
     scbCust = new SqlCommandBuilder(custAdapter); 
     con.Open(); 

     // Filling dataset by respective adapter 
     dsCommon = new DataSet(); 
     custAdapter.Fill(dsCommon, "CustCalls"); 


     // Set datagridview datasource 
     dataGridView1.DataSource = dsCommon.Tables["CustCalls"]; 

     con.Close();    
     } 
    private void update_Click(object sender, EventArgs e) 
    { 

       con.Open(); 
     dsCommon.AcceptChanges(); 
     this.custAdapter.UpdateCommand = this.scbCust.GetUpdateCommand(true); 
     int rowCust = this.custAdapter.Update(dsCommon.Tables["CustCalls"]); 


     if (rowCust > 0) 
     { 
      lblMessage.Text = "INFO: Record updated successfully!"; 
     } 
     con.Close(); 
    } 

這是app.config中

connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True" 

回答

0

我的連接字符串將添加評論,但我代表的不是足夠高。無論如何,如果您逐步進行調試,在調用更新之前數據集中顯示的更新是否已更新?我想知道在更新被調用之前,datagridview中所做的更改是否未反映在數據集中。更新語句可能只是在所有行上運行更新。逐步完成時,單擊update時rowCust的值是多少?

1

我確實不記得了,但我認爲這可能是因爲您在更新之前調用了AcceptChanges。您告訴您的DataSet接受所有您的編輯和更改,這會導致您更新的行具有未更改的RowState。然後你做你的更新,但它說,「嘿,這些數據行不變,所以不需要更新!」

至少,我認爲這就是我如何記住這個工作。

這是未經測試的,但我認爲這有效?

DataSet dataSet; 
SqlDataAdapter adapter; 
string connectionString = "my connection string"; 

using (var connection = new SqlConnection(connectionString)) 
{ 
    dataSet = new DataSet(); 
    connection.Open(); 

    adapter = new SqlDataAdapter("SELECT * FROM dbo.MyTable", connection); 
    var commandBuilder = new SqlCommandBuilder(adapter); 

    adapter.Fill(dataSet, "MyTable"); 

    dataGridView1.DataSource = dataSet.Tables["MyTable"]; 
} 

//Whenever you update 
using (var connection = new SqlConnection(connectionString)) 
{ 
    connection.Open(); 

    if (adapter.Update(dataSet.Tables["MyTable"]) > 0) 
     lblMessage.Text = "INFO: Record updated successfully!"; 
}