检查 vb.net 中的 Datagridview 是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36540186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:11:55  来源:igfitidea点击:

Check the Datagridview is empty in vb.net

vb.net

提问by sanjeewa

I want to check Datagridview is empty.If empty then should want be close the window.I used this code.But occurs "nullreferenceexception was unhandled ".How should I fixed it.

我想检查 Datagridview 是否为空。如果为空,则应该关闭窗口。我使用了此代码。但是发生“未处理 nullreferenceexception”。我应该如何修复它。

If DataGridViewReInfor.CurrentCell.Value Is Nothing Then
           Me.Close()
        Else
            MessageBox.Show("Cell contains a value")
        End If

回答by ehh

DataGridView is like matrix containing Rows, Columns and Cells. A cell is represented by a specific row in a specific column.

DataGridView 就像包含行、列和单元格的矩阵。单元格由特定列中的特定行表示。

The following, that you have done, is checking whenever a value in a specific cell is null:

您已完成的以下操作是在特定单元格中的值为空时进行检查:

If DataGridViewReInfor.CurrentCell.Value Is Nothing Then

Note: Before checking if the Value is Nothing, you need to check if the CurrentCell is Nothing. And this may be the reason you got the exception.

注意:在检查 Value 是否为 Nothing 之前,您需要检查 CurrentCell 是否为 Nothing。这可能是您获得异常的原因。

If DataGridViewReInfor.CurrentCell Is Nothing Then 

But if you purpose is to check whenever your DataGridView contains rows, you need to ask on the rowcount:

但是,如果您的目的是检查 DataGridView 何时包含行,则需要询问行数:

If DataGridViewReInfor.RowCount>0 Then

or Rows.Count

或 Rows.Count

If DataGridViewReInfor.Rows.Count > 0 Then

回答by Joey

You get the exception because either a variable or a property of an object you were accessing was Nothing. This is an exception that's trivial to find with a debugger (just hover over your expressions), in this case I'm fairly sure that CurrentCellis Nothingbecause there is no selection. This is the sort of thing that you should train yourself to check first because few of the common exceptions are actually surprising.

您会收到异常,因为您正在访问的对象的变量或属性是Nothing. 这是一个使用调试器很容易找到的异常(只需将鼠标悬停在您的表达式上),在这种情况下,我相当确定这CurrentCellNothing因为没有选择。这是你应该训练自己首先检查的那种事情,因为很少有常见的异常是令人惊讶的。

As for checking whether the DataGridView is empty: If there is no IsEmptyproperty you may have to look at other things. Maybe looking at RowCountand ColumnCountwould help here.

至于检查DataGridView是否为空:如果没有IsEmpty属性,你可能要看看其他的东西。也许在寻找RowCountColumnCount将有助于在这里。