0

In constructor:

webBrowser2.Navigate("http://www.tapuz.co.il/forums/forumpage/393");

Then in DocumentCompleted:

void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlElementCollection items = this.webBrowser1.Document.GetElementsByTagName("span");
            foreach (HtmlElement item in items)
            {
                if (item.GetAttribute("className") == "addMessage")
                {
                   item.InvokeMember("click");
                   break;
                }
            }
        }

I'm getting on

HtmlElementCollection items = this.webBrowser1.Document.GetElementsByTagName("span");

Null exception.

I tried to add before this line a loop:

while (webBrowser2.ReadyState != WebBrowserReadyState.Complete)
            {
                return;
            }

But then it didn't do anything when the page loaded. It's never got to to the next lines. I just saw the page loading in the webBrowser.

Daniel Hamutel
  • 595
  • 1
  • 11
  • 25
  • 4
    You are getting null reference exception because `this.webBrowser1.Document` is null. Because you navigated in `webBrowser2`. Also when using `DocumentCompleted` event you don't need such `while` loop. – Reza Aghaei Dec 24 '15 at 13:48
  • 3
    A NRE is something that every developer hits at some point. The best thing you can do to arm yourself against it is learn how to debug - [this question](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) goes over it in a more general sense. – James Thorpe Dec 24 '15 at 13:54
  • 1
    [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Reza Aghaei Dec 24 '15 at 13:55

1 Answers1

1

You are getting null reference exception because this.webBrowser1.Document is null.

Document property of WebBrowser is null before navigation.

You navigated in webBrowser2 and your webBrowser1.Document is still null.

Reza Aghaei
  • 103,774
  • 12
  • 145
  • 300