2012-02-16 156 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!"; 
}