我在一些VB和C#项目中的几个不同的datagridvews上一直在处理我的DataError Handling。
这些DataGridViews是从数据库生成的表中绑定的,处理用户输入并将它们写回数据库。如果用户输入有效数据,一切都很好,但如果他们尝试将主键更改为字符串,则错误很多。
我所拥有的效果很好但不完美的是:
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
但当然这还不够。
我也能够将处理程序编写为一个被调用的泛型子程序,但是我仍然没有想到如何在任何不同的datagridviews中出现错误时调用它。有没有办法在一个地方跨表单捕获任何DatagridView.DataError?
答案 0 :(得分: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