C# 数据网格视图/数据集更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/299231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:13:39  来源:igfitidea点击:

DataGridView/DataSet update

c#datagridview

提问by SeaDrive

I'm having trouble saving a new row in the DataGridView back to the database. Briefly,

我无法将 DataGridView 中的新行保存回数据库。简要地,

1) I use a SqlDataAdapter to fill a DataTable in a DataSet.

1) 我使用 SqlDataAdapter 来填充 DataSet 中的 DataTable。

2) The DataTable is the DataSource for a Grid View.

2) DataTable 是网格视图的数据源。

3) If the user clicks on the blank "new row" at the bottom of the DataGridView, I capture the new, empty row of in the RowEnter event and populate it with data. The data appears in the DataGridView.

3) 如果用户单击 DataGridView 底部的空白“新行”,我会在 RowEnter 事件中捕获新的空行并用数据填充它。数据出现在 DataGridView 中。

4) When I call Update on the SqlDataAdapter, the new data disappears and is not saved to the database.

4)当我在SqlDataAdapter上调用Update时,新的数据消失了,没有保存到数据库中。

Between steps 3 & 4 I have tried DataGrid.EndEdit, DataSet.AcceptChanges, BindingContext [...].EndCurrentEdit and maybe some other things without success.

在第 3 步和第 4 步之间,我尝试了 DataGrid.EndEdit、DataSet.AcceptChanges、BindingContext [...].EndCurrentEdit 以及其他一些没有成功的方法。

How do I propagate the change from the DataGridView back to the DataSet?

如何将更改从 DataGridView 传播回 DataSet?

And, if I may be permitted a brief whine, why is it so hard to find a simple example of such an obvious thing?

而且,如果我可以简短地抱怨一下,为什么很难找到一个简单的例子来说明如此明显的事情?

采纳答案by SeaDrive

I have success with the approach here:

我在这里的方法取得了成功:

http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx

http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx

I still think it's too hard to find the answers in the documentation, though.

不过,我仍然认为在文档中找到答案太难了。

回答by dkretz

According to this, AcceptChanges may be the problem.

根据,AcceptChanges的可能是问题。

To quote:

报价:

Hey,

嘿,

You can't execute AcceptChanges before the update. AcceptChanges makes the RowState back to Unchanged (which the added rows should be Added RowState value and the updated rows should be Modified RowState value).

The Update statement should call AcceptChanges for you

您不能在更新之前执行 AcceptChanges。AcceptChanges 使 RowState 恢复为 Unchanged(添加的行应该是 Added RowState 值,更新的行应该是 Modified RowState 值)。

Update 语句应该为您调用 AcceptChanges

Notice that I didn't find this anywhere in MSDN.

请注意,我在 MSDN 中的任何地方都没有找到它。

Would you buy a search engine from a company that requires Google to query its own documentation?

您会从要求 Google 查询自己文档的公司购买搜索引擎吗?