将更改从GridView更新到数据库

问题描述:

请帮助我解决冲突.我为解决问题做出了不懈的努力,但真是太遗憾了.

我已经在Windows窗体的GridView中显示了数据.我希望当我在GridView上进行更改时,像使用Excel工作表一样,将更改反映回数据库中.

我目前正在使用此代码:

Please help me out to resolve a conflict. I have made untiring efforts to resolve, but coudln''t.

I have shown my data in a GridView in Windows Forms. I want that when I make chages on the GridView, using it like an Excel sheet, the changes should be reflected back in the database.

I am currently using this code:

da = new SqlDataAdapter();
cb = new SqlCommandBuilder(da);
myGridView.DataSource = ds.Tables["UserDetails"];

ds.AcceptChanges();

da.Update(ds, "UserDetails");
con.Close();



怎么了?如何编辑特定的单元格值?



What''s wrong? How can I edit specific cell values?

首先,DataTable.AcceptChanges方法并没有按照您的想象做.这是DataTable的工作原理的简要提要.最初加载所有数据时,它将每一行的DataRowState设置为Unchanged.每当对DataRow进行更改时,状态都会更改为AddedDeletedModified.记录此状态,以便当DataAdapter需要更新数据库时,它确切知道它需要更新哪些行以及如何更新它们.

您的第一个问题是AcceptChanges方法告诉DataTable将所有DataRowState重置为Unchanged,并告诉它删除状态为Deleted的任何行.这意味着在调用Update命令时,DataAdapter认为它不需要执行任何操作.

第一步是反转这两行代码.这可能会解决您的问题,但也可能不会.如果可行,那就是一个非常简单的解决方案.

但是,如果仍然有问题,则可能需要设置TableMappings.我建议阅读以下内容: ADO.NET中的表映射 [
To begin with, the DataTable.AcceptChanges method doesn''t do what you think it does. Here''s a brief synopsis of how the DataTable works. When it initially loads all of the data, it sets each row''s DataRowState to Unchanged. Whenever a change is made to a DataRow the state changes to either Added, Deleted, or Modified. This state is recorded so that when a DataAdapter needs to update the database, it knows exactly what rows it needs to update and how to update them.

Your first problem is that the AcceptChanges method tells the DataTable to reset all of the DataRowStates to Unchanged and tells it to delete any rows with a state of Deleted. This means that when the Update command is called, the DataAdapter thinks that it doesn''t need to do anything.

The first step is to reverse those two lines of code. This might solve your problem, but it also might not. If it works, then, it''s a pretty simple solution.

However, if you still have issues, you may need to set up the TableMappings. I would suggest reading this: Table Mapping in ADO.NET[^] if you need to do that.