Adding controls at Runtime

G

Guest

I've got a Windows form that has a TabControl. I add TabPages to this
TabControl at Runtime, along with two Textboxes and a button. The problem
I'm having is I can't figure out how to reference the Textboxes elsewhere
once they have been created. The TextBoxes are being named based on a
private global counter (i.e. TextBox tb = new TextBox(); tb.Name = "tb" +
(counter++).ToString();) They are being created in a private method called
"AddTab". Anybody have any idea's?
 
M

Morten Wennevik

Hi slylos,

You can either add the TextBoxes to a list of your own or use the TabPage.Controls property to look for a Control with the right name.
 
G

Guest

That's what I can't figure out - how to create this "List". Also, using
TabPage.Controls property means I have to know the index of the textbox I'm
working with. Is there no way to keep track of these names, then use them at
runtime? i.e.

private void addcontrol()
{
Textbox t = new Textbox();
t.Name = "myBox";
tabPage1.Controls.Add(t);
}

private void SomeOtherMethod()
{
myBox.Text = "Hey!!";
}

That's what I'm hoping for. If not, some way to achieve that . . .
 
M

Morten Wennevik

Just create a TextBox[], or ArrayList, and put all your TabPage TextBoxes in it. Of course, you will need to know the proper index, or loop through this list or the TabPage.Controls collection and search for a specific name.

foreach(Control c in tabPage1.Controls)
{
if(c.Name == "myBox")
c.Text = "Hello World";
}

or using an ArrayList add your TextBoxes to this list.

foreach(TextBox tb in myArrayList)
{
if(tb.Name == "myBox")
tb.Text = "Hello World";
}

That's what I can't figure out - how to create this "List". Also, using
TabPage.Controls property means I have to know the index of the textbox I'm
working with. Is there no way to keep track of these names, then use them at
runtime? i.e.

private void addcontrol()
{
Textbox t = new Textbox();
t.Name = "myBox";
tabPage1.Controls.Add(t);
}

private void SomeOtherMethod()
{
myBox.Text = "Hey!!";
}

That's what I'm hoping for. If not, some way to achieve that . . .
 
G

Guest

That seems like a good solution, I will try that and post back on here.
Thanks for your help Morten!!

Morten Wennevik said:
Just create a TextBox[], or ArrayList, and put all your TabPage TextBoxes in it. Of course, you will need to know the proper index, or loop through this list or the TabPage.Controls collection and search for a specific name.

foreach(Control c in tabPage1.Controls)
{
if(c.Name == "myBox")
c.Text = "Hello World";
}

or using an ArrayList add your TextBoxes to this list.

foreach(TextBox tb in myArrayList)
{
if(tb.Name == "myBox")
tb.Text = "Hello World";
}
 

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