Search code examples
c#winformstextboxcontrols

Delete/Remove the Dynamically created Textboxes in Windows Application


I have a Code Which will Create a Textbox During Runtime.

 public System.Windows.Forms.TextBox AddNewTextBox()
        {
            System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
            this.Controls.Add(txt);
            dynamicTextBoxes.Add($"tb{cLeft}", txt);
            txt.Top = cLeft * 25;
            txt.Left = 100;
            txt.Multiline = true;
            txt.Size = new System.Drawing.Size(100,100);
            txt.BringToFront();
            txt.BorderStyle = BorderStyle.None;


            txt.Text = "TextBox " + this.cLeft.ToString();
            cLeft = cLeft + 1;
            return txt;
        }

i also added the control into the dictionary

 private Dictionary<string, TextBox> dynamicTextBoxes = new Dictionary<string, TextBox>();

now i want to delete the textbox.

I am using this code to delete/remove the textbox.

dynamicTextBoxes[$"tb{cLeft - 1}"].Dispose();

But this line of code is removing only the last created textbox.

My question is how can i remove all or selected textboxes one by one on each button click.


Solution

  • Firstly you need to use Children instead of Controls and secondly you should add controls to some container like Grid,StackPanel ,...

    System.Windows.Controls.TextBox txt = new System.Windows.Controls.TextBox();
    yourGrid.Children.Add(txt);
    

    Please note that namespace should be System.Windows.Controls here.