Question

I have a form (Windows Forms) with dynamically created textboxes:

                    TextBox[] tbxCantServ = new TextBox[1];
                    int i;
                    for (i = 0; i < tbxCantServ.Length; i++)
                    {
                        tbxCantServ[i] = new TextBox();
                    }

                    foreach (TextBox tbxActualCant in tbxCantServ)
                    {
                        tbxActualCant.Location = new Point(iHorizontal, iVertical);
                        tbxActualCant.Name = "tbx" + counter++;
                        tbxActualCant.Visible = true;
                        tbxActualCant.Width = 44;
                        tbxActualCant.MaxLength = 4;
                        this.Controls.Add(tbxActualCant);
                    }

Now I want to fill them with data, how could I do that?

If I created some textboxes dynamically with the names:

"tbxActualServ.Name = "txt" + counter;"

How can I write in them? How can I access to them?

For example, if I have created tbx1, tbx2 and tbx3, I would have a "for" that fills tbx1.Text with "1", tbx2.Text with "2", and tbx3.Text with "3".

something like

"for from i=0 to counter {
tbx[i] = i
}"

of like:

this.Controls.OfType<TextBox>().Where(r => r.Name == "tbx" + counter).¿¿Write??(r => r.Text = i).ToString();

Thanks!

Was it helpful?

Solution

You could do something like this:

this.Controls.OfType<TextBox>().ToList<TextBox>().ForEach(tb => tb.Text = "bla bla");

OTHER TIPS

Evening,

Guessing from your tags that this is a web forms project.. Im going to have to make some other assumptions.

I am guessing that you are creating your text boxes in code, something like

TextBox tb1 = new TextBox();
form1.Controls.Add(tb1);

TextBox tb2 = new TextBox();
form1.Controls.Add(tb2);

If this is the case then I believe that you could do something like this:

for (int i = 0; i < 2; i++)
{
    TextBox tb1 = page.findControl("tb" + i.ToString());
    tb1.Text = "This is number " + i.ToString();
}

There is another alternative, you could keep a collection of the controls as you create them, you could then iterate over the collection.

To be honest, without more details about your code it will be difficult to give a full answer, I think that this answers what you are looking for, if not update your question with more details and more of the code (the code where you are dynamically creating the controls would be useful)

While it's possible to access controls by their names (the way you do it depends on the technology - are you using WinForms, WPF, Web Forms, ...?), using an array of controls is a much better solution. Here's some pseudo-C#:

MyControl[] controls = new MyControl[length];
for(int n = 0; n < controls.Length; n++)
{
    controls[n] = new MyControl(...);
}

// ...

for(int n = 0; n < controls.Length; n++)
{
    DoSomethingWith( controls[n] );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top