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

Fur*_*gal 2 .net vb.net datagridview winforms

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

富尔坎

Cod*_*ray 5

您需要检查 的Value属性DataGridViewCell是否为(Nothing相当于nullC# 中的属性)。

您可以使用以下代码来做到这一点:

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


如果您想在用户尝试离开单元格时通知其已留空,则需要在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
Run Code Online (Sandbox Code Playgroud)