Clearing a WebBrowser control

D

David Veeneman

In .NET 2.0, how do I clear the contents of a web browser control?

I'm using a WebBrowser control in a Windows Form app to display strings
genrated by my application and formatted as HTML--I'm not using it to do any
actual web browsing.

I use 'webBrowser1.DocumentText = myText' to load an HTML string into the
control. But I can't clear that text when I want to load a new string into
the control.

I've tried 'webBrowser1.Navigate("about:blank")', and that doesn't seem to
work. I've looked for articles about using the WebBrowser control as an HTML
renderer, but I've had no luck.

Any articles out there? Any suggestions on how to clear the control? Thanks
in advance.

David Veeneman
Foresight Systems
 
D

David Veeneman

I found my answer. Don't use the DocumentText property to write text to a
WebBrowser control. Instead, use the Document object.

1) Initialize the document object by navigating it to "about:blank". This is
required, as otherwise the Document property will be null.

2) Use the Document.Write() method to write text to the WebBrowser control.

3) Use the Document.OpenNew() method to clear the control, after which more
text can be written.

Here's a siimple demo. Create a Windows Forms app and put a WebBrowser
control and a Button on Form 1. Create event handlers for the Form1_Load and
button1_Click events. Then add the following code to the event handlers:

private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("about:blank");
webBrowser1.Document.Write("Hello World!");
}

private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("Goodbye World!");
}

The demo will open with "Hello World!" showing in the WebBrowser control.
When you click the button, the text will be replaced by "Goodbye World!"

David Veeneman
Foresight Systems
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top