如何使用Datagridview绑定源C#更新SQL Server数据库

一些人

我正在用C#编写Winforms应用程序,该应用程序使用户可以使用datagridview编辑和更新数据库。

问题是,我无法使其正常工作。我唯一要做的就是更新datagridview显示的内容,但是当我进入数据库表时,数据没有任何变化。我搜索了很多讨论该问题的站点,但对我而言仍然没有任何作用。

到目前为止我尝试过的事情:

  • 将数据库绑定到datagridview
  • Copy to Output Directory属性更改Copy if newer
  • 使用dataAdapter.Update((DataTable)bindingSource1.DataSource)带或不带任何更新查询执行。
  • 不执行更新查询dataAdapter.update(...)

这是我的代码:

public Form1()
{
    InitializeComponent();
    GetData("SELECT * FROM Table1");
}

void GetData(string selectCommand)
{
    SqlConnection conn = new SqlConnection(Properties.Settings.Default.NewDBTESTConnectionString);

    dataAdapter = new SqlDataAdapter(selectCommand, conn);
    commandBuilder = new SqlCommandBuilder(dataAdapter);

    table = new DataTable();
    dataAdapter.Fill(table);

    bindingSource1.DataSource = table;
    dataGridView1.DataSource = bindingSource1;
}

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
        dataAdapter.Update((DataTable)bindingSource1.DataSource);    
}
史蒂夫

不调用bindingSource1.EndEdit您的基础DataTable不会看到任何更改,因此Update命令没有任何更新。

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    bindingSource1.EndEdit();
    DataTable dt = (DataTable)bindingSource1.DataSource;

    // Just for test.... Try this with or without the EndEdit....
    DataTable changedTable = dt.GetChanges();
    Console.WriteLine(changedTable.Rows.Count);

    int rowsUpdated = da.Update(dt);    
    Console.WriteLine(rowsUpdated);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章