我的其中一个表单上有一个 DataGridView,用户可以编辑然后更新它,以便对其链接到的数据库进行更改。因此,我不希望任何单元格留空。目前我正在使用此代码:
If datagrdSnippets.Item(e.ColumnIndex, e.RowIndex).Value Is Nothing Then
' Show the user a message
MsgBox("Please ensure the cell has been given a value")
' Fail validation (prevent them from leaving the cell)
e.Cancel = True
End If
在 DSG 的单元格验证属性中,但是当我编辑单元格并将其留空时,什么也没有发生。我的代码有问题还是需要使用其他方法?
请注意:这是在 VB.NET 中,我当前正在使用 CellValidating 事件。
谢谢:)
最佳答案
Value
不是CellValidating Event
中要检查的属性,而是e.FormattedValue
。您在代码中使用的 Value
属性并不反射(reflect)当前单元格值,而是反射(reflect)最后验证的值。示例代码:
Private Sub datagrdSnippets_CellValidating(sender As System.Object, e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles datagrdSnippets.CellValidating
If (e.FormattedValue = "Value I want to avoid") Then e.Cancel = True
End Sub
请注意,此事件不仅仅在用户输入值时被调用,因此“没有任何限制”的 MsgBox
不应该放在这里(您必须设置一些东西( bool 标志,例如)确保用户是调用此方法的人)。
关于vb.net - 停止 datagridview 中的空白单元格 - VB.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20241969/