mihai11 mihai11 - 1 month ago 17
C# Question

Removing textbox/label on button click C#

I am trying to remove textboxes and labels one by one by pressing a button.
I have a list of textboxes called inputTextBoxes.

Here is the code for adding :

private void onClickAdd(object sender, EventArgs e)
{
inputTextBoxes = new List<TextBox>();
Label label1 = new Label();
label1.Name = "label1";
label1.Text = "w" + i;
label1.Location = new System.Drawing.Point(5, 10 + (20 * i));
label1.Size = new System.Drawing.Size(30, 20);
this.Controls.Add(label1);

TextBox text1 = new TextBox();
text1.Name = "text1";
text1.Location = new System.Drawing.Point(35, 10 + (20 * i));
text1.Size = new System.Drawing.Size(25, 20);
inputTextBoxes.Add(text1);
this.Controls.Add(text1);
i++;
}


For removing I am trying this :

private void onClickRemove(object sender, EventArgs e)
{
foreach(TextBox text1 in inputTextBoxes)
{
this.Controls.Remove(text1);
}

}


But it removes only the last textbox added,clicking againg on the button doesn't do anything.

Answer

You want to remove only one TextBox at a time, why do you need a foreach loop? just grab the last or first TextBox and if it is not null remove it from the Controls:

 private void onClickRemove(object sender, EventArgs e)
 {
     var textBoxToRemove = inputTextBoxes.LastOrDefault();
     // or
     // var textBoxToRemove = inputTextBoxes.FirstOrDefault();
     if (textBoxToRemove != null)
     {
         this.Controls.Remove(textBoxToRemove);
         inputTextBoxes.Remove(textBoxToRemove);
     }
 }

Make sure you remove it from inputTextBoxes also so the next time you will ask to remove a TextBox it will not try to remove it again and go on to the next one.

Edit

@Piotr Nowak has pointed one more problem you have, you allocate a new list for inputTextBox every time you add a new TextBox, you should allocate the list only once when you create your class.

Remove this from onClickAdd method:

inputTextBoxes = new List<TextBox>();

And use this when you declare the list as a field it your class:

private readonly inputTextBoxes = new List<TextBox>();