2

I am passing an object: System.Windows.Forms.HtmlElement to a method when navigating WebBrowser object to a URL in C#, but if I navigate the WebBrowser object to another page, the HtmlElement object becomes null. The pseudo-code is:

//Code to navigate to a page
WebBrowser.Navigate("http://www.google.com");

//pass one of the page's element as parameter in a method
Method(HtmlElement WebBrowser.Document.Body.GetElementsByTagName("input")["search"]);

Method(HtmlElement Element)
{
  //Works fine till now
  MessageBox.Show(Element.InnerText);

  //Code to navigate to another page
  WebBrowser.Navigate("http://www.different_page.com");

  //Here the Element object throws exception because it becomes null after another navigation to another website.
  MessageBox.Show(Element.InnerText); 
}
2
  • 1
    I'm guessing HtmlElement is losing reference because WebBrowser.Document changes once .Navigate gets called. Try storing Element.InnerText in a string variable just before the .Navigate Nov 17, 2014 at 5:18
  • yes, this could be the possible reason for it... Nov 17, 2014 at 5:25

2 Answers 2

4

Element is holding a reference, therefore it loses its state on the second navigation. Try storing value types (such as .InnerText) before executing the second navigation.

1
  • Yes, but I wanted other properties also, like GetAttribute. I have posted answer to my problem. Nov 18, 2014 at 13:06
1

I found a work around to the problem. The solution is to create a temporary WebBrowser object and pass the Element in it as OuterHtml directly into the body, and then navigate to that DOM text as if it was a response HTML of a page:

Method(HtmlElement Element)
{
  MessageBox.Show(Element.InnerText);

  WebBrowser WebBrowser = new WebBrowser();

  WebBrowser.DocumentText = "<html><head></head><body>" + Element.OuterHtml + "</body></html>";

  while (WebBrowserReadyState.Complete != WebBrowser.ReadyState)
            Application.DoEvents();

  MessageBox.Show(WebBrowser.Document.Body.InnerText);
}

Now I am able to access the Element as: WebBrowser.Document.BodyAnd it persists even if I navigate the original WebBrowser object to another page.

1
  • +1 because it does the job without too much of a coding effort. Nov 18, 2014 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.