mihai11 mihai11 - 1 year ago 185
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);

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);

For removing I am trying this :

private void onClickRemove(object sender, EventArgs e)
foreach(TextBox text1 in inputTextBoxes)


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

Answer Source

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)

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.


@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>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download