I am using WebBrowser control to show preview of automatically generated HTML. Users can select options and preview pane reflects those changes automatically. WebBrowser control has some problems that have been here for years already. Here is my example about how to show custom HTML in WebBrowser control.
When we look at methods and properties of WebBrowser control our common sense tells us that something like this should work (VB.NET users: delete “;” after this line):
webBrowser1.DocumentText = "some text here";
And it works – only once. All subsequent assignments change nothing. When we try to refresh WebBrowser control we get only white are. Setting AllowNavigation propertyto true – some guys suggest it – has no effect also.
To get all assignments works after first one we need to navigate to some page. # is good candidate because it “exists” also in local machine for sure. And that’s not enough – we need to write something to document. After that we can show our custom HTML.
private void DisplayHtml(string html)
if (webBrowser1.Document != null)
webBrowser1.DocumentText = html;
NB! You should set AllowNavigation property to true before you deal with contents shown to users.
Keeping users on generated page
Now we can show HTML correctly and everything seems to be okay. But are we finished? Answer is yes if we want users to be able to follow the links we show to them and no if we want to keep users on generated page.
Currently we allowed navigation because otherwise we cannot move to #. We have to allow this navigation and disable all other navigation. Fortunately there isNavigating event of WebBrowser. In Navigating event we can do our filtering.
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
if (e.Url.ToString() != "#")
e.Cancel = true;
So, that’s it. We can now display our custom HTML in WebBrowser control as many times as we want. If you have some better trick then please let me know!
View Comments (8)
hmm .. what would happen if you enable navigation, navigate to blank, and then disable navigation again?
Well, it was one of the first thing I tried. But it doesn't work.
ThankYOU, that realy solved all my problems!
Making a litle twitter c# app so custom html is needed, Thanks!
Thank YOU, that realy solved all my problems !
What if the design mode was enabled for the browser control? If you have design mode enabled the allowNavigate should be false for the design mode to work. I am building a web site builder which is based on browser control (in design mode) and mshtml.dll.
Any tips would be highly appreciated. Thanks
Thanks, this solved the problem that using only DocumentText property inside a Vb application it works only the first time.
How can i make this work for vba? I"m using this in ms access. This below works but when i move to another record, it does not update the activex webbrowser. It goes blank.
Great article! I am trying to run mozilla in my webbrowser control, having some issues...