不管理NullReferenceException。 “表”什么都不返回。为什么?

时间:2013-04-18 03:03:32

标签: vb.net-2010

这是我的代码。这是我第一次来vb.net。

Private Sub Accountnum_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Accountnum.KeyPress
    Dim index As Long = 0
    If Asc(e.KeyChar) = 13 Then
        Do While index <= 111000
            If Accountnum.Text = ds.Tables("dbo.AccountMaster").Rows(index).Item("AccountNumber").ToString Then
                Nameconsumer.Text = ds.Tables("dbo.AccountMaster").Rows(index).Item("ConsumerName")
                Address.Text = ds.Tables("dbo.AccountMaster").Rows(index).Item("ConsumerAddress")
            End If
        Loop
    End If

End Sub

1 个答案:

答案 0 :(得分:0)

Null Reference错误只是意味着您尝试对尚未设置其值的对象执行某些操作。当使用带有便利点符号的语言时,人们忽略这些错误的来源并不罕见。

看看代码段中的第5行示例: ds.Tables( “dbo.AccountMaster”)。行(索引).Item( “账户号码”)。的ToString

这种情况并不罕见,但您在这里将四个引用链接在一起并假设它们都是有效的。查看发生错误的行,并检查语句中的每个组件的值。在上面的行中,您需要检查:   - ds   - ds.Tables(“dbo.AccountMaster”)   - ds.Tables(“dbo.AccountMaster”)。行(索引)   - 等等。

如果其中任何一个为null,则表示您尝试对其结果采取的后续操作,例如ToString将导致Null Reference异常。