Referencing dynamic controls

W

Will

Hi all.
I'm learning VB.Net and am developing a WinForms app.
I'm trying to make an app that I will use to scan in one or more than
on image. I want to use a tabbed interface to hold each image. Here's
the code I'm using for testing purposes. I've got the code in the
form's load event, but I think I'd have the same problems no matter
where the code existed. Right now, the form has an empty tab control,
everthing else is dynamic.

<code>
//Create a new tab
TabPage tabPage1 = new TabPage();
//Create a new panel
Panel panel1 = new Panel();
//add the panel to the form;
this.Controls.Add(panel1);
//create a new Picturebox;
PictureBox pictureBox1 = new PictureBox();
tabPage1.Text = "Page1";
//add the tab to the tab control;
this.tabImageHolder.Controls.Add(tabPage1);
//add the panel to the tab
tabPage1.Controls.Add(panel1);
//add the picturebox
panel1.Controls.Add(pictureBox1);
panel1.AutoScroll = true;
panel1.Dock = System.Windows.Forms.DockStyle.Fill;
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox1.Image = new Bitmap(@"C:\ImageStreamer1.gif");
</code>

My problem, besides ignorance, is that I now can't reference any of
the controls I've created anywhere else in the form. I think I
understand why, because the controls have been created on the fly and
are scoped to the Load event, right? If so, is there anyway I can make
these dynamic controls be "global" to the rest of the methods in the
form's class? Thanks.
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hi Will,

It's actually simple. Declare private variables in your Form-inherited class
for each dynamic control you want to reference (or even an array or a
hashtable if you expect a large number of controls). Then, in the Load event
handler, instantiate the corresponding controls and store references to them
to these class-scope variables. With this approach, you will be able to
access any of the dynamic controls throughout the class.

P.S. There is a dedicated microsoft.public.dotnet.languages.vb newsgroup for
VB.NET - related discussions.
 

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