对象引用未设置为对象的实例 - vb.net

时间:2012-11-18 04:38:45

标签: html vb.net webbrowser-control

我试图获取元素子元素的InnerHtml。这就是我所拥有的:

If doc.GetElementById("ctl00_cphBanner_MenuRedesign_BannerAlertsAndOptionsLoginView_BannerAlertsAndOptions_Authenticated_FriendsBubble") IsNot Nothing Then
                    Dim el As HtmlElement = doc.GetElementById("ctl00_cphBanner_MenuRedesign_BannerAlertsAndOptionsLoginView_BannerAlertsAndOptions_Authenticated_FriendsBubble")
                    inboxTxt.Text = el.Children(1).Children(0).InnerHtml.ToString
                End If

这是我收到的错误:

"Object reference not set to an instance of an object."

我该如何解决这个问题?

编辑:当我删除"尝试"函数,错误显示在这里:

If doc.GetElementById("ctl00_cphBanner_MenuRedesign_BannerAlertsAndOptionsLoginView_BannerAlertsAndOptions_Authenticated_FriendsBubble") IsNot Nothing Then

2 个答案:

答案 0 :(得分:1)

您假设您的doc对象具有值。在检查子元素之前,请尝试检查它是否也没有。

If Not IsNothing(doc) Then
    If Not IsNothing(doc.GetElementById("ctl00_cphBanner_MenuRedesign_BannerAlertsAndOptionsLoginView_BannerAlertsAndOptions_Authenticated_FriendsBubble")) Then
        Dim el As HtmlElement = doc.GetElementById("ctl00_cphBanner_MenuRedesign_BannerAlertsAndOptionsLoginView_BannerAlertsAndOptions_Authenticated_FriendsBubble")
        inboxTxt.Text = el.Children(1).Children(0).InnerHtml.ToString
    End If
End If

更新的代码。这可以,但不会返回您的HtmlElement

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        wb.Navigate("http://www.roblox.com/user.aspx?id=3659905")
    End Sub

    Private Sub Form1_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
        Dim doc As HtmlDocument = wb.Document
        If Not IsNothing(doc) Then
            Dim el As HtmlElement = doc.GetElementById("ctl00_cphBanner_MenuRedesign_BannerAlertsAndOptionsLoginView_BannerAlertsAndOptions_Authenticated_FriendsBubble")
            If el IsNot Nothing Then
                inboxTxt.Text = el.Children(1).Children(0).InnerHtml.ToString
            Else
                inboxTxt.Text = "No Data"
            End If
        End If
    End Sub
End Class

答案 1 :(得分:0)

最有可能的是,至少有一个表达式el.Children(1)el.Children(1).Children(0)el.Children(1).Children(0).InnerHtml导致null / Nothing。按顺序检查每一个,以确保您确实有一个值。