2013-03-29 68 views
1

使用VB.NET,尝试将页面标题写入文本文件。我在这里难倒:VB.Net如何将对象引用设置为对象的实例?

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

,但我得到一个错误说“对象引用不设置到对象的实例。”请帮忙!

+0

最有可能WebBrowser1.Document =什么。 –

+1

在代码的第一行添加一个调试中断,并检查以确保WebBrowser1.Document不为空(VB.NET中为Nothing),如果没有问题,请检查标题是否精确。所有的错误意味着你试图引用一些不存在的东西。如果文档在那里,并且没有标题,则会出现该错误。 – David

回答

1

您很可能在尝试访问Document属性时仍然等于Nothing。移动你的代码到DocumentCompleted事件WebBrowser控制的,因为这样的:

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 
+0

这工作!谢谢! – user2221877

+0

不客气。如果这解决了您的问题,请标记为已回答。 –

0

我的猜测是“WebBrowser1.Documen't为空。我不确定必须存在什么条件才能使Document不为空,但在尝试获取标题之前,您一定要先检查一下。

我偷了这个来自: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 
相关问题