我想在触发此事件时在 datagridview 特定单元格上显示错误文本和图标
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
我该怎么做?
我尝试了以下方法:
if (int.Parse(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) > nbsstatus)
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Max Social Status is " + nbsstatus;
e.cancel=true;
最佳答案
在 DataGridViews 中显示列错误有点奇怪。为了使错误图标出现在单元格中,您不能使用 e.Cancel = true,因为该图标仅在单元格失去焦点后才显示,而为单元格设置 e.Cancel 时可以防止这种情况。
为了解决此问题,RowValidating 事件必须循环遍历所有单元格以确定是否已标记错误,如果是,则必须设置 e.Cancel = true,以便用户无法离开当前行,直到出现错误( s) 已解决。
以下 VB(我没有用于 winforms 的 VS for C# 进行测试,但如果您无法阅读 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
关于c# - 在 Datagridview 中显示错误图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717124/