【问题标题】:Webbrowser control throws NullReferenceException when navigatingWebbrowser 控件在导航时抛出 NullReferenceException
【发布时间】:2016-11-19 22:35:18
【问题描述】:

我正在尝试使用 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

当我把它放到测试中时,大部分时间都会在这部分代码中抛出异常'System.NullReferenceException':

If document IsNot Nothing And
        document.All("userName") IsNot Nothing And
        String.IsNullOrEmpty(
        document.All("userName").GetAttribute("value")) Then

有时它会起作用,但大多数情况下它根本不起作用。知道如何解决这个问题吗?我对 .Net 平台非常陌生,如果有任何拼写错误,我深表歉意。任何帮助表示赞赏。

【问题讨论】:

标签: vb.net webbrowser-control nullreferenceexception


【解决方案1】:

如果document 什么都不是,那么If 语句的其他子句将产生异常,因为您正在尝试访问属性而documentNothing。您需要像这样重写代码:

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

【讨论】:

  • 他真正的问题是And 运算符的使用。我认为除了提供没有解决他的实际问题的不同解决方案之外,这应该得到解决。也不需要所有嵌套的 if,因为他没有对它们做任何事情,它看起来很拥挤......
  • @Zaggler - 我不同意你不请自来的节制。我的回答解决了他的问题,并且旨在通过对原始代码进行最少的编辑来做到这一点,以便让 OP 看到问题。这不是最佳答案,因为我没有完全重写他的代码。因此,您的否决票是错误的,因为答案不是“没用”-只是没有您想要的那么有用。如果你实际运行他的代码,你会发现我的提议在他当前的应用程序范围内解决了他的问题。
  • 我没有说你的解决方案不起作用,它确实会。他真正的问题是他对三元运算符的使用......我会解释说,很明显他不知道......
  • 如果您接受该解决方案有效(但您的批评是,与AndAlso 相比,使用嵌套 IF 不是最佳选择)那么您的反对意见是没有根据的。但是,我接受您的建设性批评,即有一个更好的方式来做他想做的事。建议你需要花时间设身处地为能力不如自己的人着想。这对你来说比玩线程警察更有价值。提问者应该可以访问 IMO 的答案......
猜你喜欢
  • 2013-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2019-02-08
  • 2010-11-29
相关资源
最近更新 更多