如何检查datagridview单元格是否为空

时间:2011-02-09 08:14:19

标签: .net vb.net winforms datagridview

如果我的datagridview的单元格值为Null,我想显示一条消息。 请告知如何做到这一点。 谢谢和最诚挚的问候,

Furqan

1 个答案:

答案 0 :(得分:3)

您需要检查Value propertyDataGridViewCellNothing(相当于C#中的null)。

您可以使用以下代码执行此操作:

If myDataGridView.CurrentCell.Value Is Nothing Then
    MessageBox.Show("Cell is empty")
Else
    MessageBox.Show("Cell contains a value")
End If


如果要在用户尝试离开单元格时将其保留为空,请通知用户,您需要在CellValidating事件处理程序方法中使用类似的代码。例如:

Private Sub myDataGridView_CellValidating(ByVal sender As Object,
               ByVal e As DataGridViewCellValidatingEventArgs)
               Handles myDataGridView.CellValidating
    If myDataGridView.Item(e.ColumnIndex, e.RowIndex).Value Is Nothing Then
        ' Show the user a message
        MessageBox.Show("You have left the cell empty")

        ' Fail validation (prevent them from leaving the cell)
        e.Cancel = True
    End If
End Sub
相关问题