Search code examples
c#winformsnumericupdown

How to generate dynamic textboxes and label using numericUpDown1 in C# Winforms


I can dynamically create textboxes and labels using numericUpDown1, but i cannot decrement when the user wants to decrease the number of textboxes and labels to be used.

Here is my code :

TextBox textbox = new TextBox();
Point p = new Point(35, 40 * i);
textbox.Location = p;

textbox.Size = new System.Drawing.Size(219, 20);
textbox.Name = "txtbox_" + i;
textbox.Text = "txtbox_" + i;
gb_addPos.Controls.Add(textbox);


Label label = new Label();
Point q = new Point(5, 40 * i);
label.Location = q;

label.Size = new System.Drawing.Size(21, 15);
textbox.Name = "label_" + i;
label.Text = i + ".)";
gb_addPos.Controls.Add(label);
i++;

Size r = new Size(259, 50 * j);
gb_addPos.Size = r;
j++;

Thank you for giving time in helping a beginner like me.. Very much Appreciated...


Solution

  • I don't really like dynamically adding and removing only by the name of the control. What I like to do is manage the list of controls myself and call Add or Remove with the actual control:

    private readonly List<TextBox> _txts = new List<TextBox>();
    
    // Then you can add a textbox with:
    TextBox txt = // init a new textbox
    this._txts.Add(txt);
    this.Controls.Add(txt);
    
    // And remove with:
    this.Controls.Remove(this._txts[i]);
    this._txts.RemoveAt(i);
    

    The reason I like this approach specifically is because it doesn't force you to unbox Control into a TextBox if you want to treat it like what it really is. But the greater reason is that you actually manage the your array TextBoxs on your own. What if you had a TextBox that wasn't dynamically created? That would mess things up.

    // looping over textboxes:
    foreach (var txt in this._txts)
    {
        // txt is TextBox
        // With the normal approach you would have to write:
        // foreach (var txt in this.Controls.OfType<TextBox>())
    }