简体   繁体   English

VB.NET抛出“对象引用未设置为对象的实例”异常

[英]VB.NET throwing “Object reference not set to an instance of an object” Exception

Why do I get this Exception? 为什么我会得到这个例外?

Object reference not set to an instance of an object. 你调用的对象是空的。

With: 附:

wb.Document.GetElementById("formfieldv1").InnerText = "some value"

Where wb is the name of the WebBrowser control. 其中wbWebBrowser控件的名称。

Here is all the code: 这是所有代码:

Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
Dim strFrom As String = txtFrom.Text
Dim strTo As String = txtTo.Text
Dim strMsg As String = txtMsg.Text
wb.Document.GetElementById("formfieldv1").InnerText = strFrom ' strFrom fills fine
End Sub

Update 更新

As suggested in comments I modified code like this: 正如评论中所建议的,我修改了这样的代码:

  Dim doc = wb.Document

  If (doc Is Nothing) Then
     MsgBox("doc is nothing")
  End If


  Dim el = wb.Document.GetElementById("formfieldv1")

  If (el Is Nothing) Then
     MsgBox("el is nothing")
  Else
     el.InnerText = strFrom
  End If

With that I am getting el is nothing . 有了这个,我得到el is nothing How do I solve this now ? 我现在该怎么解决这个问题?


Alternatively if you guys can help me out with this that will solve my problem too: 或者,如果你们可以帮助我解决我的问题:

How to fill html form using web browser control 如何使用Web浏览器控件填充html表单

I think this is a great example of why it's good to break down operations into several lines, instead of trying to do many operations in one line, especially when null values can be returned. 我认为这是一个很好的例子,说明为什么将操作分解为多行,而不是尝试在一行中执行许多操作,尤其是在可以返回空值时。

If you take wb.Document.GetElementById("formfieldv1").InnerText = "some value" 如果你带wb.Document.GetElementById("formfieldv1").InnerText = "some value"

and break it down into 并把它分解成

var document = wb.Document;
var element = document.GetElementById("formfieldv1");
element.InnerText = "some value";

When the exception is thrown, it will be much more apparent what is failing. 抛出异常时,失败的情况会更加明显。 It is also easier to inspect the result of each operation when stepping through code. 单步执行代码时,检查每个操作的结果也更容易。 From a compilation standpoint, it will make no difference, it will ultimately be compiled down to the same IL. 从编译的角度来看,它没有任何区别,它最终会被编译成同一个IL。

I think there tends to be a natural desire to do as much as possible in a single line of code, but I think in many cases it hurts readability and debug-ability. 我认为在一行代码中尽可能多地做自然的愿望,但我认为在很多情况下它会损害可读性和调试能力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM