Maciej
Maciej

Reputation: 10805

WebBrowser created dynamically doesn't work

I'd like to create WebBrowser control programically in my code and then read page content.
I think I'm doing the same thing as designer does but control dynamically created doesn't work (DocumentText return empty string)

What I'm doing wrong?

Edit 2: Code change after @Axarydax suggestion (working)

Main block code:

WebBrowser browser = new WebBrowser { Name = "myBrowser"};
browser.DocumentCompleted += browser_DocumentCompleted;
browser.Navigate("www.google.com");
while (pageLoaded == false)
{
  Thread.Sleep(500);       // pageLoaded is local field
  Application.DoEvents();  // didn't wotk without this...
}
Console.WriteLine(browser.DocumentText);

Event Handler code:

void browser_DocumentCompleted (object sender, WebBrowserDocumentCompletedEventArgs e )
{ 
    pageLoaded = true; 
}

Upvotes: 1

Views: 3065

Answers (3)

Sheng Jiang 蒋晟
Sheng Jiang 蒋晟

Reputation: 15261

You need to pump messages for the events to fire. Blocking the message pump with a while loop lacking message dispatching (e.g. Application.DoEvents) won't work.

Upvotes: 1

Tim Robinson
Tim Robinson

Reputation: 54734

The Navigate method works asynchronously, so the page loads in the background and there's no text when you access the DocumentText property.

Try adding a handler to the DocumentCompleted event and moving your Console.WriteLine(browser.DocumentText) call there.

Upvotes: 1

Axarydax
Axarydax

Reputation: 16603

Navigate method is asynchronous, so you should wait for NavigationComplete event to be fired. Though, if you want HTML of the page, use System.Net.WebClient.

Upvotes: 2

Related Questions