编辑和保存datagridview [英] editing and saving in datagridview

查看:108
本文介绍了编辑和保存datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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, Visual Studio设计者生成的类似类,用于从SQL Server检索数据并将其存储在DataSet中。   DataAdapter(和TableAdapter)也被设计为用于将挂起的更改提交回数据库的起始
点。

My guess is that you're using a DataAdapter (or TableAdapter, a similar class generated by Visual Studio designers) to retrieve the data from SQL Server and store it in your DataSet.  The DataAdapter (and TableAdapter) is also designed to be the starting point for submitting pending changes back to the database.

在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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