将焦点/选定内容返回到数据网格视图中的选定单元格

本文关键字:网格 数据网 视图 单元格 数据 返回 焦点 | 更新日期: 2023-09-27 18:33:44

我一直在几个VB和C#项目中对几个不同的datagridvews进行DataError Handling。

这些 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.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?

将焦点/选定内容返回到数据网格视图中的选定单元格

只是要把我的评论移到一个答案上,因为它对你有帮助:

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