Avatar
Simplicity, Productivity and Organization Enthusiast.

.NET WebBrowser Control: When DocumentCompleted means not completed.


Earlier this month I was working on a piece of code where I had to use the .NET System.Windows.Forms.WebBrowser control. I needed to set a value on a particular element once the document was downloaded.

I was trying to get an instance of an HtmlElement using Document.GetElementById(someId) upon the DocumentCompleted event and I was not able to retrieve the element in question. The element in question was present in the DOM.

I dumped the document content to disk to realize that the document content was incomplete. What was misleading for me is that the document displayed properly in the browser control.

I googled a bit to find a solution here (via Anthony Stevens). To make a story short, the event is being fired multiple times, thus you have to check the ready state of the web browser using something like:

public void WebBrowserDocumentCompletedEventHandler(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
if (WebBrowserReadyState.Complete == webBrowser.ReadyState)
{

// Do stuff with the “really” completed document here…

}
}


Is it a bug? Well, the control really does not behave as documented on MSDN