1

I have a C# WPF application with a web browser control (System.Windows.Controls.WebBrowser) called wB. It is supposed to display a local html file, and some information parsed from it.

I get the a NullReferenceException as it says body is null in the last line (IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection) with the following code:

wB.Navigate(new Uri(file, UriKind.Absolute));                
HTMLDocument hDoc = (HTMLDocumentClass)wB.Document;
IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection;

If I do

wB.Navigate(new Uri(file, UriKind.Absolute));                
HTMLDocument hDoc = (HTMLDocumentClass)wB.Document;
System.Windows.MessageBox.Show("Loc:" + hDoc.url);
IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection;

Everything works fine. Why is body showing up null in the 1st example, but fine for the second?

Edit1 The method is marked as [STAThread]...so I thought concurrency wouldn't be an issue...

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Eugene
  • 10,957
  • 20
  • 69
  • 97

2 Answers2

4

That's because the Navigate() method is asynchronous - in the second example you confirming the MessageBox is just enough time for it having completed, so it works - not reliably though.

Instead you should subscribe to the DocumentCompleted event and do your data collection in the callback.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
3

You should use

wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);

So you can be sure the document loaded already:

private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
  WebBrowser wb = sender as WebBrowser;
  HTMLDocument hDoc = (HTMLDocumentClass)wB.Document;
  IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection;
}
dasheddot
  • 2,936
  • 4
  • 26
  • 33