Dynamically Remove Textbox in a button using loop

Winston Winston 21 Reputation points

In my codes the problem i encounter it wont delete textboxes dynamically.

int count = 0;

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

private void addbox_Click(object sender, EventArgs e) // button to create dynamic textbox

            for (int i = 0; i < count; i++)
                TextBox textadd = new TextBox();
                textadd.Location = new System.Drawing.Point(Left, Top);
                textadd.Name = "btnUserInput";
                textadd.Size = new Size(376, 50);

                TextBox textadd1 = new TextBox();
                textadd1.Location = new System.Drawing.Point(619, Top);
                textadd1.Name = "btnUserInput";
                textadd1.Size = new System.Drawing.Size(228, 38);



private void textdelete_Click(object sender, EventArgs e) // button to delete textboxes
            int count = this.panel1.Controls.Count;           
            if (count > 0)
                this.panel1.Controls[count - 1].Dispose();

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,350 questions
{count} votes

Accepted answer
  1. Sreeju Nair 11,621 Reputation points

    Based on your query, I believe, you need support on how to remove a control that you already added to the page. As per your code you are adding the controls using the method


    To remove the controls you have three methods, Remove, RemoveAt and RemoveByKey. see the corresponding documenation links below.

    Remove - https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.controlcollection.remove?view=windowsdesktop-6.0
    RemoveAt - https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.controlcollection.removeat?view=windowsdesktop-6.0
    RemoveByKey - https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.controlcollection.removebykey?view=windowsdesktop-6.0

    basically, you may use below. Make sure the variable index contains the index of the control to be deleted.


    Hope this helps

0 additional answers

Sort by: Most helpful