I have a C# win app program. I save the text with html format in my database but I want to show it in a webbrowser to my user.How to display the string html contents into webbrowser control?
-
3possible duplicate of [c# webcontrol - how to load a html on the fly?](http://stackoverflow.com/questions/4467219/c-sharp-webcontrol-how-to-load-a-html-on-the-fly) – Malachi Feb 04 '15 at 18:23
-
2This question doesn't seem to have any tags to indicate *which* windows platform you're building this app for. -- For those of us that end up here via google search and want to know how to do this in a Windows 10 (or UWP) app, the browser control (called a `WebView`) has a method called `NavigateToString` where you just pass the HTML in. – BrainSlugs83 Dec 14 '16 at 22:55
-
1It's the WebBrowser control, not the WebView - so this is for Windows Forms. – eltiare Aug 04 '18 at 15:59
10 Answers
Try this:
webBrowser1.DocumentText =
"<html><body>Please enter your name:<br/>" +
"<input type='text' name='userName'/><br/>" +
"<a href='http://www.microsoft.com'>continue</a>" +
"</body></html>";

- 4,529
- 1
- 22
- 20
-
8This worked for me only the first call. Even an additional webbrowser1.Refresh() did not help for second call. Finally, this helped me: http://weblogs.asp.net/gunnarpeipman/archive/2009/08/15/displaying-custom-html-in-webbrowser-control.aspx – Thomas Weller Oct 11 '13 at 05:24
As commented by Thomas W. - I almost missed this comment but I had the same issues so it's worth rewriting as an answer I think.
The main issue being that after the first assignment of webBrowser1.DocumentText
to some html, subsequent assignments had no effect.
The solution as linked by Thomas can be found in detail at http://weblogs.asp.net/gunnarpeipman/archive/2009/08/15/displaying-custom-html-in-webbrowser-control.aspx however I will summarize below in case this page becomes unavailable in the future.
In short, due to the way the webBrowser control works, you must navigate to a new page each time you wish to change the content. Therefore the author proposes a method to update the control as:
private void DisplayHtml(string html)
{
webBrowser1.Navigate("about:blank");
if (webBrowser1.Document != null)
{
webBrowser1.Document.Write(string.Empty);
}
webBrowser1.DocumentText = html;
}
I have however found that in my current application I get a CastException from the line if(webBrowser1.Document != null)
. I'm not sure why this is, but I've found that if I wrap the whole if
block in a try catch the desired effect still works. See:
private void DisplayHtml(string html)
{
webBrowser1.Navigate("about:blank");
try
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.Write(string.Empty);
}
}
catch (CastException e)
{ } // do nothing with this
webBrowser1.DocumentText = html;
}
So every time the function to DisplayHtml
is executed I receive a CastException
from the if
statement, so the contents of the if statement are never reached. However if I comment out the if
statement so as not to receive the CastException
, then the browser control doesn't get updated. I suspect there is another side effect of the code behind the Document property which causes this effect despite the fact that it also throws an exception.
Anyway I hope this helps people.
-
1You've forgotten to include this line => `You should set AllowNavigation property to true before you deal with contents shown to users. ` – Ghasem Sep 11 '19 at 05:14
-
1Funny. 9 years afer my comment, I find this answer, because I couldn't recall how it was done properly. Thanks. Perhaps you can include the comment of @AlexJolig, because that was exactly the issue this time. Disabling the navigation can then be done by cancelling the OnNavigation. – Thomas Weller Feb 23 '23 at 09:55
Instead of navigating to blank, you can do
webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();
No need to wait for events or anything else. You can check the MSDN for OpenNew, while I have tested the initial DocumentText assignment in one of my projects and it works.
-
1As hacky as it looks, this is the only method that seems to work consistently. – Christian Mar 13 '15 at 01:39
For some reason the code supplied by m3z (with the DisplayHtml(string)
method) is not working in my case (except first time). I'm always displaying html from string. Here is my version after the battle with the WebBrowser control:
webBrowser1.Navigate("about:blank");
while (webBrowser1.Document == null || webBrowser1.Document.Body == null)
Application.DoEvents();
webBrowser1.Document.OpenNew(true).Write(html);
Working every time for me. I hope it helps someone.
-
Interesting. I wonder why my solution worked for me and not you. I can't say I've tried your solution either but it seems to be a similar concept. – m3z Apr 04 '14 at 08:57
-
I don't know, but I suspect it's the DoEvents() method. I think when you Navigate to "about:blank", it's taking some time (maybe in another thread) and your next "if" statement didn't work on my PC because 1. it has no thread synchronization with the effects of Navigate(), and 2. my processor has different speed/load than yours and I wasn't so lucky with the "if" processing as you. Not to mention that DoEvents() can do something on the same thread. Of course it's only a speculation. Also you don't have an OpenNew call. One thing I know for sure is that I ALWAYS have problems with WebBrowser.. – P.W. Apr 05 '14 at 23:41
-
1Yea I can remember not liking the WebBrowser control all that much. I subsequently found and bookmarked a webkit based replacement control which I intend to use in future projects. – m3z May 04 '14 at 05:32
-
I marked this as "answered" for me because the `Application.DoEvents`(); solved my issue. I am using `webBrowser1.DocumentText = myHtml; while (webBrowser1.DocumentText != myHtml) { Application.DoEvents(); }` – gridtrak Jul 11 '16 at 16:58
Simple solution, I've tested is
webBrowser1.Refresh();
var str = "<html><head></head><body>" + sender.ToString() + "</body></html>";
webBrowser1.DocumentText = str;

- 132,869
- 46
- 340
- 423

- 97
- 1
- 6
webBrowser.NavigateToString(yourString);

- 79
- 1
-
2Does the "NavigateToString" method exist on your webBrowser control? Because it doesn't on mine. – MondayPaper Jul 17 '13 at 15:37
-
1
-
-
NavigateToString only exists in the WPF version of the WebBrowser control – Machman Apr 26 '16 at 11:33
Here is a little code. It works (for me) at any subsequent html code change of the WebBrowser control. You may adapt it to your specific needs.
static public void SetWebBrowserHtml(WebBrowser Browser, string HtmlText)
{
if (Browser != null)
{
if (string.IsNullOrWhiteSpace(HtmlText))
{
// Putting a div inside body forces control to use div instead of P (paragraph)
// when the user presses the enter button
HtmlText =
@"<html>
<head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" />
</head>
<div></div>
<body>
</body>
</html>";
}
if (Browser.Document == null)
{
Browser.Navigate("about:blank");
//Wait for document to finish loading
while (Browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
System.Threading.Thread.Sleep(5);
}
}
// Write html code
dynamic Doc = Browser.Document.DomDocument;
Doc.open();
Doc.write(HtmlText);
Doc.close();
// Add scripts here
/*
dynamic Doc = Document.DomDocument;
dynamic Script = Doc.getElementById("MyScriptFunctions");
if (Script == null)
{
Script = Doc.createElement("script");
Script.id = "MyScriptFunctions";
Script.text = JavascriptFunctionsSourcecode;
Doc.appendChild(Script);
}
*/
// Enable contentEditable
/*
if (Browser.Document.Body != null)
{
if (Browser.Version.Major >= 9)
Browser.Document.Body.SetAttribute("contentEditable", "true");
}
*/
// Attach event handlers
// Browser.Document.AttachEventHandler("onkeyup", BrowserKeyUp);
// Browser.Document.AttachEventHandler("onkeypress", BrowserKeyPress);
// etc...
}
}

- 625
- 8
- 9
-
1does not work for me dynamic Doc = Browser.Document.DomDocument; // so far so good Doc.open(); // starts to fall apart, due lack of reference for using dynamic Doc.write(HtmlText); Doc.close(); – gg89 Sep 19 '15 at 10:47
Old question, but here's my go-to for this operation.
If browser.Document IsNot Nothing Then
browser.Document.OpenNew(True)
browser.Document.Write(My.Resources.htmlTemplate)
Else
browser.DocumentText = My.Resources.htmlTemplate
End If
And be sure that any browser.Navigating
event DOES NOT cancel "about:blank" URLs. Example event below for full control of WebBrowser
navigating.
Private Sub browser_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles browser.Navigating
Try
Me.Cursor = Cursors.WaitCursor
Select Case e.Url.Scheme
Case Constants.App_Url_Scheme
Dim query As Specialized.NameValueCollection = System.Web.HttpUtility.ParseQueryString(e.Url.Query)
Select Case e.Url.Host
Case Constants.Navigation.URLs.ToggleExpander.Host
Dim nodeID As String = query.Item(Constants.Navigation.URLs.ToggleExpander.Parameters.NodeID)
:
:
<other operations here>
:
:
End Select
Case Else
e.Cancel = (e.Url.ToString() <> "about:blank")
End Select
Catch ex As Exception
ExceptionBox.Show(ex, "Operation failed.")
Finally
Me.Cursor = Cursors.Default
End Try
End Sub

- 377
- 1
- 2
- 11
The DisplayHtml(string html) recommended by m3z worked for me.
In case it helps somebody, I would also like to mention that initially there were some spaces in my HTML that invalidated the HTML and so the text appeared as a string. The spaces were introduced (around the angular brackets) when I pasted the HTML into Visual Studio. So if your text is still appearing as text after you try the solutions mentioned in this post, then it may be worth checking that the HTML syntax is correct.

- 1
Even simpler is:
var html = "<html><body><h3>Hello</h3></body></html>";
BrowserCtrl.NavigateToString(html);

- 21
- 1