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

查看:17
本文介绍了如何获取 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.

有人知道我错过了什么吗?

Does anyone know what I'm missing?

推荐答案

执行更新

当用户在 DataGrid 中编辑客户数据时,绑定的内存数据表会相应更新.但是,这些更新不会自动写回数据库.开发人员可以根据应用程序的要求决定何时将 DataTable 的更改写回数据库.例如,在某些情况下,您可能希望通过提交"按钮提交一批更改,或者您可能希望在用户提交每一行编辑时更新数据库.为了支持这些,DataTable 包含的行具有 RowState 属性,该属性指示它们是否包含应与数据库同步的更改.通过 TableAdapter 的 Update 方法可以轻松实现同步过程.网址: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天全站免登陆