问题描述
我在DataGridView中有数据,其数据源来自连接到SqlServer的数据集。
I have data in a DataGridView with it's data source from a dataset connected to a SqlServer.
我希望能够显示我正在管理的数据,但我也希望能够编辑数据并添加行。我如何更新数据(保存)?
I want to be able to show the data which I am managing to do, but I also want to be able to edit the data and add rows. How do I then update the data (save it)?
推荐答案
在DataAdapter或TableAdapter上调用Update方法,传入你绑定了DataGridView的DataTable。
Call the Update method on your DataAdapter or TableAdapter and pass in the DataTable to which you've bound your DataGridView.
如果你在代码中创建DataAdapter,它将不会自动包含更新逻辑。 如果DataAdapter不包含更新逻辑,您将收到InvalidOperationException,其中包含"更新需要有效
UpdateCommand ..."的内容。 您可以通过创建CommandBuilder对象并使用以下代码提供DataAdapter对象,通过代码创建更新逻辑:
If you're creating your DataAdapter in code, it will not automatically include updating logic. If the DataAdapter contains no updating logic, you'll receive an InvalidOperationException saying something along the lines of "Update requires a valid UpdateCommand...". You can create the updating logic via code by creating a CommandBuilder object and supplying the DataAdapter object using code like:
string connectionString =
@"Data Source=.\SQLExpress;Initial Catalog=Northwind;" +
"Integrated Security=True;";
string commandText =
"SELECT TOP 1 CustomerID, CompanyName FROM Customers";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(commandText, connection);
DataTable table = new DataTable();
adapter.Fill(table);
table.Rows[0]["CompanyName"] = "Modified";
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);
try
{
int rowsAffected = adapter.Update(table);
Console.WriteLine("Submitted changes to {0} row(s)", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Visual Studio设计人员创建的TableAdapter包含内置更新逻辑。
The TableAdapters that the Visual Studio designers create include built-in updating logic.
CommandBuilder类非常棒对于快速样本和入门,但通过代码提供自己的更新逻辑将获得更好的性能。 但那是另一个主题。
The CommandBuilder class is great for quick samples and for getting started, but supplying your own updating logic via code will get you better performance. But that's another subject.
我希望这些信息有用。
这篇关于编辑和保存datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!