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!
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
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