在 DataGridViews 中显示列错误有点奇怪。为了使错误图标出现在单元格中,您不能使用 e.Cancel = true ,因为该图标仅在单元格失去焦点后显示,当为单元格设置 e.Cancel 时会阻止该图标。
为了解决这个问题,RowValidating 事件必须循环遍历所有单元格以确定是否已标记错误,如果是,则必须设置 e.Cancel = true 以便用户在错误出现之前不能离开当前行已解决。
以下 VB(我没有用于 C# 的 VS 用于 winforms 进行测试,但如果您无法阅读 VB,则可以使用免费的 VB 到 C# 转换器之一):
Private Sub DataGridView1_CellBeginEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
Dim dgv As DataGridView = sender
dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = ""
dgv.Rows(e.RowIndex).ErrorText = ""
End Sub
Private Sub DataGridView1_CellValidating(sender As Object, e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
Dim dgv As DataGridView = sender
' these edits are for illustration purposes only
Select Case e.ColumnIndex
Case 0
If e.FormattedValue = "NO" Then
dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = "No - Column Error Message"
dgv.Rows(e.RowIndex).ErrorText = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText
End If
Case 1
If e.FormattedValue = "YES" Then
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = "Yes - Column Error Message"
dgv.Rows(e.RowIndex).ErrorText = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText
End If
Case Else
e.Cancel = False
End Select
End Sub
Private Sub DataGridView1_RowValidating(sender As Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.RowValidating
Dim dgv As DataGridView = sender
For Each Col As DataGridViewColumn In dgv.Columns
If Not String.IsNullOrEmpty(dgv.Rows(e.RowIndex).Cells(Col.Index).ErrorText) Then
dgv.CurrentCell = dgv(Col.Index, e.RowIndex) 'set focus
e.Cancel = True
End If
Next
End Sub