c# - 如何使用Datagridview绑定(bind)源C#更新SQL Server数据库

标签 c# sql sql-server database datagridview

我正在用 C# 编写一个 Winforms 应用程序,使用户能够使用数据 GridView 编辑和更新数据库。

问题是,我无法让它工作。我唯一设法实现的是更新 datagridview 显示的内容,但是当我进入数据库表时,数据没有变化。 我搜索了很多讨论该问题的网站,但对我来说还没有任何效果。

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

  • 将数据库绑定(bind)到datagridview
  • Copy to Output Directory 属性更改为 Copy if newer
  • 使用 dataAdapter.Update((DataTable)b​​indingSource1.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);
}

关于c# - 如何使用Datagridview绑定(bind)源C#更新SQL Server数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26946397/

相关文章:

c# - 持续引用的最佳方法或替代方案是什么?

sql - 使用 NEW 为触发器创建函数时出错

sql - 拥有条款面临的问题

SQL递归逻辑

sql-server - 如何在 SQL Server Docker 容器中使用 Windows 身份验证

c# - ASP.NET MVC 在创建对象时读取属性

c# - 重写抽象方法时,我重新设置抽象是否正确?

c# - 将字典值转换为数组

mysql - 将多个查询合并为一个查询时,如何将列求和

java - 使用java将Mysql数据库转为Nosql hbase