views:

136

answers:

3

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; 
}
+2  A: 

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.

Axarydax
I've changed code according your suggestion - still doesnt work - any idea how to fix it?
Maciej
@Axarydax:heartly thanx, for this post, it helped me a lot !!
FosterZ
+1  A: 

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.

Tim Robinson
I need to 'wait' in my main program thread to process read content. I've add Edit#1 to my example trying archive that. Any idea how to manage that?
Maciej
If all you need is the HTML source for the page, follow Axarydax's suggestion.
Tim Robinson
+1  A: 

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.

Sheng Jiang 蒋晟