Dynamically Remove Textbox in a button using loop

Winston Winston 21 Reputation points
2022-03-16T02:37:45.32+00:00

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
        {

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


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

            }

        }





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


        }
C#
C#
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,648 questions
{count} votes

Accepted answer
  1. Sreeju Nair 12,176 Reputation points
    2022-03-16T06:52:57.067+00:00

    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

    this.Controls.Add(textadd1);  
    

    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.

    this.Controls.RemoveAt(index)  
    

    Hope this helps


0 additional answers

Sort by: Most helpful