Oct 16, 2008

C# - Web Browser Control - Load String in Web Browser control (4th way).

Here is one more way to load string in Web Browser Control (C#). This is in case you are using the managed control.

        
// Fourth way to write html in WebBrowserControl with C#:
        wb.DocumentText = strHtml;

I can tell you (just guessing) that this will be the best one as it became available in the managed control (at least I didn't found it in the old COM versions). That is why I think it was reviewed and probably optimized.
>

C# - Web Browser Control - Load String in Web Browser control.

I was thinking about this long time ago. I recently found this post:

http://www.xtremevbtalk.com/showthread.php?t=167531

So how to load a string in WebBrowser Control with C#?

First - navigate to "about:blank" (as the web browser needs a document to operate on)
Then use WebBrowser.Document.Write(string text) to write the string you want to load in the WebBrowser control. Kind of tricky but ...

Another way is to write something like:

about:your html here

And the last one is to write the document on the hard disk with StreamWriter for example, and then to navigate to it.

Here is a code to show you all methods discussed:


        
WebBrowser wb = new WebBrowser();
        
// First way to
write html in WebBrowserControl with C#:
        string strHtml = "you html here";
        wb.Navigate(
"about:" + strHtml);

        
// Second way to write html in WebBrowserControl with C#:
        wb.Navigate("about:blank");
        wb.Document.Write(strHtml);

        
// Third way to write html in WebBrowserControl with C#:
        const string strAddress = "test.html";
        
using (StreamWriter sw = new StreamWriter(strAddress))


{
        sw.Write(strHtml);
        

}      wb.Navigate("file://" + Application.StartupPath + "\\" + strAddress);