celliott1997
celliott1997

Reputation: 1145

Object reference not set to an instance of an object - vb.net

I'm trying to get the InnerHtml of a child of a child of an element. Here is what I have:

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

And this is the error I'm receiving:

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

How do I fix this?

Edit: When I removed the "Try" function, the error was shown here:

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

Upvotes: 2

Views: 1790

Answers (2)

Mark Hall
Mark Hall

Reputation: 54532

You are making the assumption that your doc object has a value. Try checking if it is nothing also, before you check for child elements.

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

Updated Code. This Works but does not return your 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

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 415911

Most likely, at least one of the expressions el.Children(1), el.Children(1).Children(0), or el.Children(1).Children(0).InnerHtml results in null/Nothing. Check each of those, in order, to make sure you actually have a value.

Upvotes: 0

Related Questions