如何获取WPF DataGrid以将更改保存回数据库? [英] How do I Get a WPF DataGrid to Save Changes Back to the DataBase?

查看:1944
本文介绍了如何获取WPF DataGrid以将更改保存回数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取WPF DataGrid将更改保存到数据库?

How do I get a WPF DataGrid to save changes back to the database?

我将DataGrid控件数据绑定到DataTable对象,并使用非常简单的SELECT查询填充该表,以检索一些基本信息。控件中的数据显示正确。

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.

但是当我使用控件来编辑数据时,更改不会被推回到数据库。

But when I use the control to edit the data, the changes are not pushed back to the DB.

有谁知道我缺少什么?

推荐答案

更新

当用户编辑DataGrid中的Customers数据时,绑定的内存中DataTable将相应更新。但是,这些更新不会自动写回数据库。根据应用程序的要求,开发人员决定何时将DataTable的更改写回数据库。例如,在某些情况下,您可能希望通过提交按钮提交一批更改,或者您可能希望在用户提交每行编辑时更新数据库。为了支持这些,DataTable包含的行有一个RowState属性,指示它们是否包含应与数据库同步的更改。通过TableAdapter的Update方法可轻松实现同步过程。
url:
WPF DataGrid示例

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

以下示例显示如何处理RowChanged和RowDeleted事件,以便每次用户更改一行时,DataTable状态的更改都将写入数据库:

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:

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);
}

这篇关于如何获取WPF DataGrid以将更改保存回数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆