从gridview更新数据库

时间:2012-02-16 16:50:43

标签: c# sql-server datagridview

我在winform项目上有以下表格,我在里面有一个datagridview,我有一个更新按钮,我希望通过推送它来更新datagridview更改中的相应表格。标签告诉我记录更新成功,但当我查询数据库时,它不起作用。有什么想法吗? :

              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"

2 个答案:

答案 0 :(得分: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!";
}

答案 1 :(得分:0)

会添加评论,但我的代表不够高。无论如何,如果您单步执行并调试,是否在调用更新之前在数据集中显示更新?我想知道在调用更新之前,datagridview中所做的更改是否未反映在数据集中。并且update语句可能只是在所有行上运行更新。单步执行时,单击更新时rowCust的值是什么?