如何使用 Datagridview 绑定源 C# 更新 SQL Server 数据库 [英] How to update SQL Server database using Datagridview binding source C#
问题描述
我正在用 C# 编写一个 Winforms 应用程序,它使用户能够使用 datagridview 编辑和更新数据库.
I'm writing a Winforms app in C# that enables the user to edit and update database using the datagridview.
问题是,我无法让它工作.我唯一设法实现的是更新 datagridview 显示的内容,但是当我进入数据库表时,数据没有变化.我搜索了很多讨论这个问题的网站,但还没有对我有用.
The problem is, I can't make it to work. The only thing that I managed to achieve is updating what the datagridview is showing, but when I go into the database table, there is no change in the data. I have search a lot of sites discussing about that problem but nothing yet worked for me.
到目前为止我尝试过的事情:
Things I have tried so far:
- 将数据库绑定到datagridview
- 将
Copy to Output Directory
属性更改为Copy if newer
- 使用
dataAdapter.Update((DataTable)bindingSource1.DataSource)
执行或不执行任何更新查询. - 在没有
dataAdapter.update(...)
的情况下执行更新查询.
- binding the database to the datagridview
- changing the
Copy to Output Directory
property toCopy if newer
- using the
dataAdapter.Update((DataTable)bindingSource1.DataSource)
with or without any update query execute. - execute update query without
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 命令没有任何要更新的内容.
Without calling bindingSource1.EndEdit
your underlying DataTable doesn't see any change and thus the Update command has nothing to 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);
}
这篇关于如何使用 Datagridview 绑定源 C# 更新 SQL Server 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!