C#问题:如何将DataGridView中所做的更改保存回使用的DataTable?

One*_*hot 9 c# datatable binding datagrid dataset

我从DataSet获取DataTable,然后将该DataTable绑定到DataGridView.一旦用户编辑DataGridView上的信息,我该如何处理这些更改并将它们放回到使用的DataTable中,然后我可以将其放回到我的DataSet中?

我想在我的DataGrid上创建一个Save Button,当按下时实际上保存了更改.

如果我能得到更具体的话,我不会,因为这是一个相当简单的问题.

提前致谢!

如果您需要我详细说明,请告诉我.

Mar*_*ell 6

如果您使用数据绑定到a DataGridView,那么您已经在更新DataTable/ DataSet.如果您的意思是更改数据库,那么这就是适配器发挥作用的地方.

这是一个例子:

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();

        DataSet set = new DataSet();
        DataTable table = set.Tables.Add("MyTable");
        table.Columns.Add("Foo", typeof(int));
        table.Columns.Add("Bar", typeof(string));

        Button btn;
        using (Form form = new Form
        {
            Text = "DataGridView binding sample",
            Controls =
            {
                new DataGridView {
                    Dock = DockStyle.Fill,
                    DataMember = "MyTable",
                    DataSource = set
                },
                (btn = new Button {
                    Dock = DockStyle.Bottom,
                    Text = "Total"
                })
            }
        })
        {
            btn.Click += delegate
            {
                form.Text = table.AsEnumerable().Sum(
                    row => row.Field<int>("Foo")).ToString();
            };
            Application.Run(form);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)