SQL 如何获取 WPF DataGrid 以将更改保存回数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1156731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I Get a WPF DataGrid to Save Changes Back to the DataBase?
提问by Giffyguy
How do I get a WPF DataGrid to save changes back to the database?
如何获取 WPF DataGrid 以将更改保存回数据库?
I've data-bound my DataGrid control to a DataTable object, and populated that table with a very simple SELECT query that retrieves some basic information. The data shows up just fine in the control.
我已将我的 DataGrid 控件数据绑定到一个 DataTable 对象,并使用一个非常简单的 SELECT 查询填充该表,该查询检索一些基本信息。数据在控件中显示得很好。
But when I use the control to edit the data, the changes are not pushed back to the DB.
但是当我使用控件编辑数据时,更改不会推送回数据库。
Does anyone know what I'm missing?
有谁知道我错过了什么?
回答by Vincent De Smet
Performing Updates
执行更新
When the user edits the Customers data within the DataGrid, the bound in-memory DataTable is updated accordingly. However, these updates are not automatically written back to the database. It is up to the developer to decide when changes to the DataTable are written back to the database depending on the requirements of the application. For example, in some cases, you might wish to submit a batch of changes via a "Submit" button, or you may wish to have the database updated as the user commits each row edit. In order to support these, the rows that the DataTable contains have a RowState property which indicates whether they contain changes which should be synchronized with the database. The synchronization process is easily achieved via the TableAdapter's Update method. url: WPF DataGrid examples
当用户在 DataGrid 中编辑客户数据时,绑定的内存中的 DataTable 会相应地更新。但是,这些更新不会自动写回数据库。开发人员可以根据应用程序的要求决定何时将 DataTable 的更改写回数据库。例如,在某些情况下,您可能希望通过“提交”按钮提交一批更改,或者您可能希望在用户提交每一行编辑时更新数据库。为了支持这些,DataTable 包含的行具有 RowState 属性,该属性指示它们是否包含应与数据库同步的更改。通过 TableAdapter 的 Update 方法可以轻松实现同步过程。url: WPF DataGrid 示例
The following example shows how the RowChanged and RowDeleted events can be handled so that changes in the DataTable state are written to the database each time the user changes a row:
以下示例显示如何处理 RowChanged 和 RowDeleted 事件,以便在用户每次更改行时将 DataTable 状态的更改写入数据库:
public CustomerDataProvider()
{
NorthwindDataSet dataset = new NorthwindDataSet();
adapter = new CustomersTableAdapter();
adapter.Fill(dataset.Customers);
dataset.Customers.CustomersRowChanged +=
new NorthwindDataSet.CustomersRowChangeEventHandler(CustomersRowModified);
dataset.Customers.CustomersRowDeleted +=
new NorthwindDataSet.CustomersRowChangeEventHandler(CustomersRowModified);
}
void CustomersRowModified(object sender, NorthwindDataSet.CustomersRowChangeEvent e)
{
adapter.Update(dataset.Customers);
}