Free C# Tutorials

home
Stay at Home and Learn

Adding a WebBrowser to a Windows Form in C# .NET

 
Computer Tutorials List

 

 

 

 

Web Browsers are quite easy to add. Locate the WebBrowser control in the Toolbox, under Common Controls:

The WebBrowser control in C# .NET

Draw out a web browser in the second panel of your SplitContainer. It will fill Panel2 by default. But if it doesn't, locate the Dock property and set it to Fill.

Most of what you need to do with a WebBrowser control is through its Methods, rather than its properties. So there's not much else to do on this control!

Time to do some coding, then.

 

Code for the TreeView Control

What we want the WebBrowser to do is navigate to the web page clicked on in the TreeView. To do that, you can use the NodeMouseClick event.

So, in Design View, click on your TreeView control to select it. Click the lightning bolt to see the events:

The NodeMouseClick Event

Now double click NodeMouseClick to bring up its code stub (we've used word wrap because the line is too big for this book. Yours will all be on one line):

C# code stub for the NodeMouseClick

Add the following between the curly brackets:

C# Code to navigate to a web page

The code sets up a new TreeNode and accesses the Tag property. This is where we placed our web address. The WebBrowser has a Navigate method that is used to navigate to web sites. We just pass it the web site that was in the Tag property.

But this code gets called every time a Node is clicked in the tree, thus firing the NodeMouseClick event. Run your programme and try it out. You should find that you have a rudimentary browser.


Exercise
Add a Textbox and a button to your form. Write code so that, when the button is clicked, the browser goes to the webpage typed in your textbox.


We'll leave events now, and move to another topic. There's an awful lot more to them, and you can even create your own events. But that's enough for a beginners book. Explore some of the events available to controls, though - you could find an easy way to add code!

<-- TreeView Nodes | Classes and Objects in C# -->

<--Back to the C# .NET Contents Page

View all our Home Study Computer Courses