Dynamically adding controls to a Windows Form in .NET
I just wrote some code to dynamically add some textboxes to a Windows Form in .NET. I thought I would share it here and see if anyone has any suggestions, since this is my first attempt at dynamically adding elements to a Windows Form in .NET.
Basically within the form's class, I create an ArrayList, as a private variable in the form's class. On the Load event of the form, I instantiate the ArrayList and then add TextBox objects to the ArrayList. Remember that you need to actually add the control to the form by using this.Controls.Add(). On an event, such as a button click, you can get the values of the text boxes as shown in the button click event below. If you have any suggestions, please put them in as feedback.
//Start Code
private ArrayList arylTxtGEItems;
//VS.NET stuff omitted for brevity.
private void frmEncounterDynamic_Load(object sender, System.EventArgs e)
{
int i = 0;
this.arylTxtGEItems = new ArrayList();
for(i = 0; i< 3; i++)
{
this.arylTxtGEItems.Add( new System.Windows.Forms.TextBox() );
((System.Windows.Forms.TextBox)this.arylTxtGEItems[i]).Location = new System.Drawing.Point(40, 36 + i * 20);
((System.Windows.Forms.TextBox)this.arylTxtGEItems[i]).Name = "txtGE" + i.ToString();
((System.Windows.Forms.TextBox)this.arylTxtGEItems[i]).Size = new System.Drawing.Size(184,20);
((System.Windows.Forms.TextBox)this.arylTxtGEItems[i]).TabIndex = i + 2;
((System.Windows.Forms.TextBox)this.arylTxtGEItems[i]).Text = String.Empty;
this.Controls.Add( ((System.Windows.Forms.TextBox)this.arylTxtGEItems[i]) );
}
}
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show( ((System.Windows.Forms.TextBox)this.arylTxtGEItems[1]).Text );
}
//End Code
Wally