Blank the WebBrowser control in C#

If a program displays a web page in a WebBrowser control and then that page become irrelevant to the program, you may want to blank the control. Doing that is as easy as making the control navigate to the special URL "about:blank." When you click this example's Blank button, the following code blanks the WebBrowser control.

// Blank the WebBrowser.
private void btnBlank_Click(object sender, EventArgs e)
{
    wbrCSharpHelper.Navigate("about:blank");
}

That's easy enough but there is a catch. The WebBrowser control takes some time to get ready to work and to load a web page. If you try to make it do something before it is ready, it sometimes fails. It seems to do okay with simple navigation, but actions such as trying to set the control's Document contents may cause trouble.

To avoid those kinds of errors, you should wait until the control's has finished loading whatever document it is loading before you do anything else. This probably isn't necessary in this example but the program does it for form's sake.

At design time, I disabled the Blank button. I also set the WebBrowser control's URL property to www.csharphelper.com/howto_index.html so it loads the C# Helper index page when it starts. When that page is finished loading, the control's DocumentCompleted event fires and the following event handler executes.

// Enable the Blank button.
private void wbrCSharpHelper_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    btnBlank.Enabled = true;
}

This code simply enables the Blank button so you can blank the control.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.