HaMeD
HaMeD

Reputation: 359

Access controls that were created at run time

In my form i have a "plus-button", when the user click on it a new TextBox is added to the form:

private void btnPlus_Click(object sender, EventArgs e)
{
    TextBox tb = new TextBox();
    tb.Name = "textBox" + countTb.ToString();
    this.Controls.Add(tb);
    countTb++;
}

My problem is: I don't know how to access these TextBoxes. I have a save-button, when user clicks it i have to save all TextBox.Text into database, but I don't know how to find them.

Upvotes: 1

Views: 369

Answers (5)

Grant Winney
Grant Winney

Reputation: 66439

If you want to save all TextBox.Text values on the form in one comma-delimited string:

var allText = string.Join(",", Controls.OfType<TextBox>().Select(x => x.Text));

You'll need to clarify your question more, if this won't work.

  • This will grab the value of every TextBox on the form, so if you don't want to save the values from some, you'll need to filter them out first.

  • If you want a list, so you can save one record per TextBox, then remove string.Join.

Upvotes: 0

Jet
Jet

Reputation: 43

One of the best ways to access the text box after you have created it would be to insert it into an array or list, this way you would be able to iterate through that list/array to access any number of text boxes and save the data inside to a database.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460038

You could use Controls.OfType if the TextBoxes are on top of the form:

var allTextBoxes = this.Controls.OfType<TextBox>();
foreach(TextBox txt in allTextBoxes)
{
    // ...
}

Another approach is to use ControlCollection.Find to find controls with a given name:

for(int i = 1; i <= countTb; i++)
{
    Control[] txtArray = this.Controls.Find("textBox" + i, true); // recursive search
    if (txtArray.Length > 0)
    {
        TextBox txt = (TextBox)txtArray[0];
    }
}

Upvotes: 1

Joe Brunscheon
Joe Brunscheon

Reputation: 1989

To get all of the TextBoxes on the form, you can do the following:

var textBoxes = this.Controls.OfType<TextBox>();

Then you can iterate over them all to get their text values:

foreach(var textBox in textBoxes)
{
    var text = textBox.Text;
    //do something to save the values.
}

Upvotes: 0

Mostafa Soghandi
Mostafa Soghandi

Reputation: 1584

you can easily save button names on array or you can access to form text boxes from --> this.controls

Upvotes: 0

Related Questions