views:

2337

answers:

2

My WinForms application has a tab with a System.Windows.Forms.WebBrowser control. There are several controls that set the WebBrowser's .Url property, and when the form repaints it calls the WebBrowser's .Refresh(WebBrowserRefreshOption.Completely) method.

Occasionally, however, the form gets repainted and the WebBrowser content doesn't change. I break on the .Refresh( ), and the .Url is the previous Url. What's going on?

According to MSDN:

If you set the value of this property and then immediately retrieve it again, the value retrieved may be different than the value set if the WebBrowser control has not had time to load the new document.

Well isn't that special? Why doesn't .Refresh( ) wait until the control has "had time to load the new document" before it redraws? Is there any way to force this to happen?

+1  A: 

Try adding an event handler to your code that runs when the "DocumentCompleted" event fires. Then add your refresh code in there. There are some examples of code here in MSDN. If you do it this way you won't lose any time guessing if the page has loaded, and can continue processing as soon as it is ready.

http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documentcompleted.aspx

Joe Basirico
+4  A: 

Unless you're doing something very special, it doesn't make sense to force the WB to repaint itself. Since it is its own control and has its own Handle, it is quite capable of repainting itself whenever it deems necessary. Since you are forcing it to repaint at a moment that's completely out of sync with its ReadyState, getting an "old" url is to be expected.

Hans Passant
You're absolutely right; leaving it alone allowed the WB to refresh when the new page loaded, completely independently of my form redraw. I wish I could give you more than a +1.
Dour High Arch