0

我一直在几个 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?

4

1 回答 1

1

只是将我的评论移至答案,因为它可以帮助您:

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.Rows(cCellLocation.Y).Cells(cCellLocation.x) 
    Call ErrorLogWriter(e)
End Sub

要回答关于在单个位置处理错误的其他问题,您需要在应用程序中添加事件处理程序并让它们都指向一个方法:

AddHandler MyBuChemicalsDataGridViewtton.DataError, AddressOf DGVDataError
AddHandler OtherDGV.DataError, AddressOf DGVDataError

private Sub DGVDataError(ByVal sender As Object, ByVal e As DataGridViewDataErrorEventArgs)

''dynamicly do things here for each DGV error

End Sub
于 2013-10-03T20:43:40.033 回答