WebBrowser control created at runtime??

NJDubois

Well-known member
Joined
May 15, 2008
Messages
84
Programming Experience
Beginner
I can create and place WebBrowser controls at run time no problem.

But why can't I figure out how to get one of any number of created WebBrowser controls to navigate to a website?

I have a FORM a BUTTON and TWO TEXTBOX controls at design time. I run the program and it creates a random number of WEBBROWSER controls named WebBrowser1 to WebBrowser whatever.

textbox1.text = a number, 1 - max number of created webbrowsers, determined in whatever way it is. A user changes it, a random generated number, it doesn't matter.

textbox2.text = "www.google.com"

if textbox1.text = 4 when the button is clicked,
WebBrowser4.Navigate(textbox2.text)

but what if textbox1.text could equal 35, or 1, or whatever. HOW DO I REFERENCE IT'S ASSOCIATED WEBBROWSER CONTROL?!?!?

I've spent a few hours researching this and I find page after page on creating controls, but I can't change the data of a control determined at run time, and I can't find how to anywhere.

Please help!

Much thanks for even reading this!
Nick
 
But why can't I figure out how to get one of any number of created WebBrowser controls to navigate to a website?
I can't answer that one. ;)

The principle is very simple. No matter what, in order to get a WebBrowser object, or any object for that matter, to do something you must have a variable that refers to it. It doesn't matter whether you create your WebBrowser at design time or in code, you must have a variable that refers to that WebBrowser control in order to get or set a property or call a method of that object.

When you add the WebBrowser in the designer the IDE will create a member variable for you, so you will usually use that. If you add the WebBrowser in code then you will have to declare a member variable yourself and assign the WebBrowser object to it, e.g.
VB.NET:
Private myWebBrowser As WebBrowser
VB.NET:
Me.myWebBrowser = New WebBrowser
If you're going to be creating multiple WebBrowsers then a single WebBrowser variable won't be sufficient. Most likely you'd use a List(Of WebBrowser) so you can add new objects whenever you like, e.g.
VB.NET:
Private myWebBrowsers As New List(Of WebBrowser)
VB.NET:
Me.myWebBrowsers.Add(New WebBrowser)
You can then refer to each individual WebBrowser object in the List by index.
 
Set a Name for the control and you can get a reference later by using the string indexer of the Controls collection you added the control to.
VB.NET:
Dim c As Control = Me.Controls("web23")
Other arrangments could be better, like keeping your own collection/dictionary as mentioned. Also sometimes you could store info various places for easy access, for example using the Tag property of a TabPage, if it was not easier to just get the first (and only) index of the tabs Controls collection. How to arrange things depends on the situation, to get a better answer you have to explain that.
 
Back
Top