我从 DataSet 中获取 DataTable,然后将该 DataTable 绑定(bind)到 DataGridView。一旦用户编辑了 DataGridView 上的信息,我如何进行这些更改并将它们放回使用过的 DataTable 中,然后我可以将其放回我的 DataSet 中?
我想在我的 DataGrid 上创建一个保存按钮,当按下它时实际上会保存更改。
如果我能得到比这更具体的信息,我不知道,因为这是一个相当简单的问题。
提前致谢!
如果您需要我详细说明,请告诉我。
最佳答案
如果您使用数据绑定(bind)到 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);
}
}
}
关于C# 问题 : How do I save changes made in a DataGridView back to the DataTable used?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/520051/