1

Using VB.NET, trying to write a page title to a text file. I am stumped here:

Private Sub
    Dim pagetitle As String
    pagetitle = WebBrowser1.Document.Title
    My.Computer.FileSystem.WriteAllText("page title.txt", pagetitle, False)

But I get an error saying "Object reference not set to an instance of an object." Please help!

user2221877
  • 35
  • 1
  • 3
  • 6
  • Most likely WebBrowser1.Document = Nothing. – Hanlet Escaño Mar 29 '13 at 16:48
  • 1
    Put a debugging break on the first line of the code, and check to ensure that WebBrowser1.Document isn't null (Nothing in VB.NET), and if that's OK check to see if the Title is mull. All that error means is that you're trying to reference something that doesn't exist. If the document is there and there is no title, you'll get that error, for example. – David Mar 29 '13 at 16:48

2 Answers2

1

Most likely you are trying to access the Document property when it is still equal to Nothing. Move your code to the DocumentCompleted event of the WebBrowser control, as such:

Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        If WebBrowser1.Document IsNot Nothing Then
            Dim pagetitle As String
            pagetitle = WebBrowser1.Document.Title
            My.Computer.FileSystem.WriteAllText("page title.txt", pagetitle, False)
        End If
End Sub
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
0

My Guess is 'WebBrowser1.Documen't is null. I'm not sure what conditions have to exist to make the Document not null, but you should definitely check that first before trying to grab its title.

I stole this from:http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document.aspx

Private Sub webBrowser1_Navigating( _
    ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs) _
    Handles webBrowser1.Navigating

    Dim document As System.Windows.Forms.HtmlDocument = _
    webBrowser1.Document
    If document IsNot Nothing And _
        document.All("userName") IsNot Nothing And _
        String.IsNullOrEmpty( _
        document.All("userName").GetAttribute("value")) Then

        e.Cancel = True
        MsgBox("You must enter your name before you can navigate to " & _
            e.Url.ToString())
    End If 

End Sub
tobyb
  • 696
  • 9
  • 18