[c#] How to display the string html contents into webbrowser control?

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?

thanks in advance

This question is related to c# browser

The answer is


Simple solution, I've tested is

webBrowser1.Refresh();
var str = "<html><head></head><body>" + sender.ToString() + "</body></html>";
webBrowser1.DocumentText = str;

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.


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.


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...
        }
    }        

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

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.


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.


webBrowser.NavigateToString(yourString);


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>";