我試圖用VB.Net中的Webbrowser組件構建我的第一個HTML UI。我發現在微軟網站上的這個代碼示例Web瀏覽器控件在導航時拋出NullReferenceException
https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document(v=vs.110).aspx:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
Handles Me.Load
WebBrowser1.DocumentText =
"<html><body>Please enter your name:<br/>" &
"<input type='text' name='userName'/><br/>" &
"<a href='http://www.microsoft.com'>continue</a>" &
"</body></html>"
End Sub
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
當我把它放在測試,大部分時間拋出異常「System.NullReferenceException」在這部分代碼:
If document IsNot Nothing And
document.All("userName") IsNot Nothing And
String.IsNullOrEmpty(
document.All("userName").GetAttribute("value")) Then
有時它有效,但大多數情況下根本不起作用。任何想法如何解決這個問題?我對.Net平臺很陌生,如果有任何拼寫錯誤,我很抱歉。任何幫助表示讚賞。
改變你'和''到... AndAlso'其短路... – Codexer
的【什麼是一個NullReferenceException,以及如何修復它可能的複製?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Codexer