你调用的对象是空的。vb.net 查找字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17728895/
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-09 17:00:52  来源:igfitidea点击:

Object reference not set to an instance of an object. vb.net looking up a string

vb.net

提问by David

I'm getting this error and I don't know how to fix it. I know i'm supposed to write what I've tried, but i have no idea what to try, even after looking for a few hours about how to deal with the error.

我收到此错误,但不知道如何解决。我知道我应该写我尝试过的东西,但我不知道该尝试什么,即使在寻找了几个小时关于如何处理错误之后。

If more information is needed please let me know. Thanks

如果需要更多信息,请告诉我。谢谢

The highlighted part of the code is:

代码中突出显示的部分是:

Dim cdtrabajador As String = dgvr.Cells(0).Value.ToString

Object reference not set to an instance of an object.

你调用的对象是空的。

NullReference Exception was unhandled by user code

用户代码未处理 NullReference 异常

Private Sub PeopleDataGridView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    If DataGridView1.RowCount > 0 AndAlso e.RowIndex > -1 Then
        If e.RowIndex > -1 Then
            Dim dgvr As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
            Dim cdtrabajador As String = dgvr.Cells(0).Value.ToString
            Dim qry = From dr As PersonalObraDataSet.PersonalObRow In PersonalObraDataSet.PersonalOb Where dr.cdTrabajador = cdtrabajador
            If qry.Count > 0 Then
                Dim Nombre As String = qry.First.Nombre1
                dgvr.Cells(1).Value = Nombre
            End If
        End If
    End If
End Sub

回答by Kevin DiTraglia

Hard to say for sure what the root of the issue is, but you may be safe to just null check the cell before you attempt to perform any action on it, and return in the case where the cell is null. Something like:

很难确定问题的根源是什么,但是在尝试对单元格执行任何操作之前先空检查单元格可能是安全的,并在单元格为空的情况下返回。就像是:

Dim cellObj as Object = dgvr.Cells(0).Value
if Not cellObj = Nothing Then
      Dim cdtrabajador As String = cellObj.ToString
     '...
     'Perform the rest of your code
Else
     Return

Also note that if Cells(0)is actually null, invoking Valueon it may also be causing the error. If you use your debugger you should be able to pinpoint which value is null and either handle it, or look into reasons why it is null if you expect a value to be present and it isn't.

另请注意,如果Cells(0)实际上为空,则调用Value它也可能导致错误。如果您使用调试器,您应该能够查明哪个值为 null 并对其进行处理,或者如果您希望某个值存在而该值不存在,则查看其为 null 的原因。