【发布时间】:2013-10-03 18:31:37
【问题描述】:
我一直在几个 VB 和 C# 项目中对几个不同的 datagridvews 进行 DataError 处理。
这些 DataGridView 绑定自从数据库生成的表,处理用户输入并将它们写回数据库。如果用户输入有效数据,一切都很好,但如果他们尝试将主键更改为字符串,则错误很多。
我所拥有的效果很好,但并不完美的是:
Private Sub ChemicalsDataGridViewErrorHandler(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) Handles ChemicalsDataGridView.DataError
e.Cancel = True
ChemicalsDataGridView.EditingControl.Text = Nothing
Call FillChemicalsDataGrid() 'goes back to the DB and just reloads the last valid table, writing back to DB at cell change
Call ErrorLogWriter(e)
End Sub
这行得通,并清除了有问题的问题,并使该人回到可用的数据网格视图。但它也将单元格选择放回(0,0)。有没有办法可以在重新加载 datagridview 时使用DataGridView.CurrentCellAddress 来选择有问题的单元格?
我知道我可以像这样分解为行和列:
Private Sub ChemicalsDataGridViewErrorHandler(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) Handles ChemicalsDataGridView.DataError
e.Cancel = True
ChemicalsDataGridView.EditingControl.Text = Nothing
Dim cRowInt As Int32 = ChemicalsDataGridView.CurrentCell.RowIndex
Dim cColumnInt As Int32 = ChemicalsDataGridView.CurrentCell.ColumnIndex
Call FillChemicalsDataGrid()
ChemicalsDataGridView.CurrentCell = ChemicalsDataGridView(cRowInt, cColumnInt)
Call ErrorLogWriter(e)
End Sub
但是单独调用行和列似乎很笨拙(作为从未上过编程课程的人,我正在努力获得更精简的代码)。特别是当我可以调用 DataGridView.CurrentCellAddress 时。我试过了:
Private Sub ChemicalsDataGridViewErrorHandler(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) Handles ChemicalsDataGridView.DataError
e.Cancel = True
ChemicalsDataGridView.EditingControl.Text = Nothing
Dim cCellLocation As Object = ChemicalsDataGridView.CurrentCellAddress
Call FillChemicalsDataGrid()
ChemicalsDataGridView.CurrentCell = ChemicalsDataGridView(cCellLocation)
Call ErrorLogWriter(e)
End Sub
当然,这还不够。
我还能够将处理程序编写为被调用的通用子程序,但我仍然没有弄清楚如何在任何不同的数据网格视图中出现错误时调用它。有没有办法在一个地方跨表单捕获任何 DatagridView.DataError?
【问题讨论】:
-
我没有把你的问题读到最后,但是每当用户输入
invalid input时reloading a DataGridView不是一个好主意。 -
@KingKing 你知道我把它拿出来了,我认为代码工作根本不需要它。我使用它是因为它在给我的一个例子中。我认为这将有助于防止将来出现错误。
-
如果你想要一行:使用 Dim cCellLocation As Point = ChemicalsDataGridView.CurrentCellAddress 然后 ChemicalsDataGridView.CurrentCell = ChemicalsDataGridView.Rows(cCellLocation.Y).Cells(cCellLocation.x)
-
@KreepN 那是遮阳篷!谢谢。这是我缩短它的方式:
Dim cCellLocation As Object = ChemicalsDataGridView.CurrentCellAddress and then ChemicalsDataGridView.CurrentCell = ChemicalsDataGridView(cCellLocation.X, cCellLocation.Y)...我无法使用 Point,但后期绑定有效...
标签: c# .net vb.net winforms datagridview