In this blog you will find it very easy to create an array of TextBox using C#, just extract the file (txtBoxArray.zip) then read the code. When you run the program (TextBoxArray.exe) you can see six Text boxes, use the buttons to see how to hide, show, clear and remove any TextBox. If you edit any of the TextBox, then you can see its index and also see which one you have edited.
About the Code // Declaring array of TextBox
private System.Windows.Forms.TextBox[] txtArray;
private void AddControls(int cNumber)
{
// assign number of controls
txtArray = new System.Windows.Forms.TextBox[cNumber + 1];
for (int i = 0; i < cNumber + 1; i++)
{
// Initialize one variable
txtArray[i] = new System.Windows.Forms.TextBox();
}
}
// Result of the event Click TextBox
public void EnterTextBox(Object sender, System.EventArgs e)
{
// number of the TextBox
txtIndex = (int)((System.Windows.Forms.TextBox) sender).Tag;
label2.Text = txtIndex.ToString();
label3.Text = "";
label3.Text = txtArray[txtIndex].Text;
}
// Result of the event TextChange of TextBox
public void TextChange(Object sender, System.EventArgs e)
{
label3.Text = txtArray[txtIndex].Text;
}
private void ShowTextBox()
{
int xPos = 8;
int yPos = 32;
txtNum = 6; // number of TextBox required
AddControls(txtNum); // Create six TextBoxs
int n = 1;
while(n < txtNum + 1)
{
txtArray[n].Tag = n;
txtArray[n].Width = 120;
txtArray[n].Height = 24;
txtArray[n].BackColor = System.Drawing.SystemColors.Info;
txtArray[n].Text = "TextBox" + txtArray[n].Tag.ToString();
if(yPos > 96) // Three TextBoxs in one column
{
yPos = 32;
xPos = xPos + txtArray[n].Width + 16;
}
txtArray[n].Left = xPos;
txtArray[n].Top = yPos;
yPos = yPos + txtArray[n].Height + 12;
this.Controls.Add(txtArray[n]);
// the Event of Enter (TextBox)
txtArray[n].Enter += new System.EventHandler(EnterTextBox);
// the Event of TextChanged (TextBox)
txtArray[n].TextChanged += new System.EventHandler(TextChange);
n++;
}
btnAddText.Enabled = false; // not need to this button now
btnRemoveText.Enabled = true; // we need to remove any
btnHide.Enabled = true;
btnShow.Enabled = true;
btnClear.Enabled = true;
label5.Visible = true;
}
private void RemoveTextBox()
{
int n = txtNum;
if(n > 0)
{
this.Controls.Remove(txtArray[n]);
txtNum--;
}
if(n == 1)
{
btnAddText.Enabled = true; // we need to add again
// not need because all had removed
btnRemoveText.Enabled = false;
btnHide.Enabled = false;
btnShow.Enabled = false;
btnClear.Enabled = false;
}
}