.NET - DataGridView - 当用户添加行时更新到数据库

发布于 2024-10-06 03:45:33 字数 542 浏览 0 评论 0原文

嘿伙计们。我在使用 datagridview 让用户输入保存到数据库的数据时遇到问题。基本上,我只是希望他们将东西扔到一行中,然后我的代码将插入数据。我知道必须有一些事件来实现我想要做的事情,但我就是想不通。

我尝试了LeavingRow事件,但问题是当该事件触发时,最终值尚未更新。我的意思是,假设我们有一行四列,并且用户已将数据输入到前三列中。他们在最后一列中输入信息,然后向下推以输入新行。插入失败,因为它认为最后一列仍然是空的。

我还尝试了 UserAddsRow,但失败了,因为它会在用户开始键入添加行时触发,因此我尝试添加的行的第一列中只有一个字符。

有没有人有关于让这些或其他一些活动为我的目的工作的建议?

我正在权衡的两个不雅的替代方案是a)将一些标签/文本框和添加按钮串在一起或b)使用DataGridCell_ValueChanged事件,通过一些嵌套的try/catch来尝试首先插入,然后如果失败尝试更新,然后如果更新不起作用,则不执行任何操作。这是非常低效的,但我认为它可以完成工作,因为在这个 datagridview 中一次只会有几十行顶部。

感谢您抽出时间。

Hey guys. I'm having an issue with using a datagridview for a user entering data that's saved to a database. Basically, I just want them to throw stuff into a row and then my code will insert the data. I know there has to be some event for what I'm trying to and I just can't figure it out.

I tried the LeavingRow event, but the problem with that is that the final value hasn't updated when this event triggers. What I mean is, say we have a row with four columns, and the user has entered data into the first three columns. They enter info in the last column, then push down to enter a new row. The insert fails, because it thinks the last column is still empty.

I also tried UserAddsRow, but had that fail because it triggers as soon as the user starts typing to add a row, so there would be only a single character in the first column of the row I was trying to add.

Does anyone have suggestions for getting these, or some other event working for my purposes?

The two inelegant alternatives I'm weighing are a) stringing together some labels/textboxes and an add button or b) using the DataGridCell_ValueChanged event, by having some nested try/catch that will try to insert first, then if it fails try to update, and then do nothing if the update doesn't work. It's grossly inefficient, but I think it would get the job done since there's only going to be a couple dozen rows tops at one time in this datagridview.

Thank you for your time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

楠木可依 2024-10-13 03:45:33

我通常使用 RowValidated 事件。我使用此事件是因为它允许在尝试保存更改之前输入/编辑整行。

处理事件时,我获取已从数据集中添加、更新或删除的行 (DataSet.GetChanges),然后针对每种类型执行适当的操作(添加、更新、删除)。

I typically use the RowValidated Event. I use this event because it allows for a whole row to be entered / edited before trying to save the changes.

When handling the event I get the rows that have been added, updated or deleted from the dataset (DataSet.GetChanges) and then perform the appropriate actions per type (Add, Update, Delete).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文