我试图在VB.Net中使用Webbrowser组件构建我的第一个HTML UI。我在Microsoft网站上找到了这个代码示例
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
当我把它放到测试中时,大部分时间抛出异常&#39; System.NullReferenceException&#39;在这部分代码中:
If document IsNot Nothing And
document.All("userName") IsNot Nothing And
String.IsNullOrEmpty(
document.All("userName").GetAttribute("value")) Then
有时它有效,但大多数情况下根本不起作用。知道如何解决这个问题吗?我对.Net平台很新,如果有拼写错误,请对不起。任何帮助表示赞赏。
答案 0 :(得分:-1)
如果document
为空,那么If
语句的其他子句将生成例外,因为您在document
为Nothing
时尝试访问属性。你需要像这样重写代码:
Dim document As System.Windows.Forms.HtmlDocument = WebBrowser1.Document
If document IsNot Nothing Then
If document.All("userName") IsNot Nothing Then
If 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 If
End If