使用WebBrowser加载页面之后,试图访问其Document,以及其中的HtmlElement, HtmlElements等对象,总是出现异常: HtmlElement nullreferenceexception was unhandled 。
终于在MSDN上找到如下原因:
When using the DOM through the WebBrowser control, you should always wait until the DocumentCompleted event occurs before attempting to access the Document property of the WebBrowser control. The DocumentCompleted event is raised after the entire document has loaded; if you use the DOM before then, you risk causing a run-time exception in your application.
原来我在Form1_Load函数中,也就是在页面刚加载时就试图去访问这些页面元素,而这时,这些页面还没加载完成,所以得到的总是空。把代码换到DocumentCompleted事件中去,就搞定了。
这篇文章的地址是:http://msdn.microsoft.com/en-us/library/ms171712.aspx