Displaying custom HTML in WebBrowser control
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 property to true – some guys suggest it – has no effect also.
To get all assignments works after first one we need to navigate to some page. about:blank 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. C#
private void DisplayHtml(string html)
if (webBrowser1.Document != null)
webBrowser1.DocumentText = html;
Private Sub DisplayHtml(ByVal html As String)
If webBrowser1.Document IsNot Nothing Then
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 about:blank. We have to allow this navigation and disable all other navigation. Fortunately there is Navigating event of WebBrowser. In Navigating event we can do our filtering. C#
private void webBrowser1_Navigating(object sender,
if (e.Url.ToString() != "about:blank")
e.Cancel = true;
Private Sub webBrowser1_Navigating(ByVal sender As Object, _
ByVal e As WebBrowserNavigatingEventArgs)
If e.Url.ToString() <> "about:blank" Then
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!