software is fun software is fun - 3 months ago 5
C# Question

Get text of dynamically generated TextBox controls?

for(int i = 0; i < numberOfFields; i++)
{
TextBox generatedField = new TextBox();
generatedField.Text = "Please enter Field Report ID Here";
generatedField.Width = 176;
generatedField.Location = new Point(pointX, pointY);
panel1.Controls.Add(generatedField);
panel1.Show();
pointY += 25;
}


After generating the TextBoxes, how can I find out what was typed into them?

Answer

You need to set Name of your controls, then you can access them by name this way:

Create controls and assign Name:

for(int i = 0; i < numberOfFields; i++)
{
     TextBox generatedField = new TextBox();
     generatedField.Name = "someName_" + i.ToString();
     generatedField.Text = "Please enter Field Report ID Here";
     generatedField.Width = 176;
     generatedField.Location = new Point(pointX, pointY);
     panel1.Controls.Add(generatedField);
     panel1.Show();
     pointY += 25;
}

Find and Use controls:

var txt = (TextBox)panel1.Controls["someName_1"];
MessageBox.Show(txt.Text);

Some Notes:


Unique Names: Pay attention to generate unique names.

Null Checking: You may want add null checking after var txt = (TextBox)panel1.Controls["someName_1"];

Another Option: You can use this.Controls.Find
You can also use this code, that will return a TextBox with name of someName_1:

 var txt = this.Controls.Find("someName_1", true).Cast<TextBox>().FirstOrDefault();

Handling Events: You can add TextChanged event
Another thing you may find useful, is adding TextChanged event when creating controls:

generatedField.TextChanged += generatedField_TextChanged;

This way, you should have this method in form:

void generatedField_TextChanged(object sender, EventArgs e)
{
    var txt = (TextBox)sender;
    // do what you need with txt.Text and other properties
}