处理DataGridView中的并发异常(Handling concurrency exceptions in DataGridView)

编程入门 行业动态 更新时间:2024-10-20 01:22:11
处理DataGridView中的并发异常(Handling concurrency exceptions in DataGridView)

这篇文章描述了处理并发异常。 重现问题的步骤是:

创建一个新的Windows应用程序项目。 基于Northwind Customers表创建新数据集。 使用DataGridView创建表单以显示数据。 使用Northwind数据库中Customers表中的数据填充数据集。 填充数据集后,使用Visual Studio中的Visual Database Tools直接访问Customers数据表并更改记录。 然后在表单上,​​将相同的记录更改为不同的值,更新数据集,并尝试将更改写入数据库,这会导致引发并发错误。 捕获错误,然后显示记录的不同版本,允许用户确定是继续和更新数据库,还是取消更新。

我的问题是,为什么会发生这种情况? 为什么我不能只从DataGridView保存和编辑记录而不会导致任何错误? 我正在使用DataGridView创建一个应用程序,我正面临着这个问题。 我需要一些方法来避免或解决此错误而不通知用户,因此他们在DataGridView中看到的任何内容都会以您看到它的方式保存。 这个错误的原因是什么?

This article here describes handling concurrency exceptions. The steps to reproduce the problem are:

Create a new Windows Application project. Create a new dataset based on the Northwind Customers table. Create a form with a DataGridView to display the data. Fill a dataset with data from the Customers table in the Northwind database. After filling the dataset, use the Visual Database Tools in Visual Studio to directly access the Customers data table and change a record. Then on the form, change the same record to a different value, update the dataset, and attempt to write the changes to the database, which results in a concurrency error being raised. Catch the error, then display the different versions of the record, allowing the user to determine whether to continue and update the database, or to cancel the update.

My question is, why does this even happen? Why can't I just save and edit the record from the DataGridView without causing any errors? I'm creating an app with a DataGridView and I'm facing this problem. I need some way to avoid or resolve this error without notifying the user, so whatever they see in the DataGridView gets saved exactly the way thy see it. What's the cause of that error?

最满意答案

解决方案结果非常简单。

您需要做的就是在每次保存后再次将数据重新加载到DataGridView中。

所以BindingNavigator保存按钮的代码现在是:

this.Validate(); this.maintableBindingSource.EndEdit(); this.tableAdapterManager.UpdateAll(this.yourDataSet); this.maintableTableAdapter.Fill(this.yourDataSet.yourtable);

我不知道为什么会这样,所以我需要专家来证实这一点。 工作解决方案。

感谢E-Bat将这个想法植入我的脑海。

The solution turned out to be pretty simple.

All you need to do is reload the data into the DataGridView again after every save.

So the code for the BindingNavigator save button is now:

this.Validate(); this.maintableBindingSource.EndEdit(); this.tableAdapterManager.UpdateAll(this.yourDataSet); this.maintableTableAdapter.Fill(this.yourDataSet.yourtable);

I have no idea why this works, so I need an expert to confirm this. Working solution though.

Thanks to E-Bat for planting this idea in my head.

更多推荐

本文发布于:2023-07-31 00:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340514.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   DataGridView   Handling   exceptions   concurrency

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!