xxldoener
xxldoener

Reputation: 43

Remove control created at runtime

I wrote some code to create an additional textbox during runtime. I'm using the metro framework, but this shouldn't matter for my question.

When you click a button, a textbox is being created by a private on_click event:

private void BtnAddButton_Click(object sender, EventArgs e)
{           
    MetroFramework.Controls.MetroTextBox Textbox2 = new MetroFramework.Controls.MetroTextBox
    {
        Location = new System.Drawing.Point(98, lblHandy.Location.Y - 30),
        Name = "Textbox2",
        Size = new System.Drawing.Size(75, 23),
        TabIndex = 1
    };
    this.Controls.Add(Textbox2);
}

What I want to do now is to use the click event of another button, to remove the Textbox again. What I am not sure about is, if I have to remove just the controll or also the object itself. Furthermore I can neither access the Textbox2 Control nor the object from another place.

private void BtnRemoveTextbox2_Click(object sender, EventArgs e)
{
    this.Controls.Remove(Textbox2);
}

This does not work, since the other form does not know about Textbox2. What would be the best way to achieve my goal? Do I have to make anything public and if so, how do I do that?

Upvotes: 1

Views: 198

Answers (3)

Koby Douek
Koby Douek

Reputation: 16693

Since the control was created in another form, the current form has no way of knowing it by its instance name.

To remove it, loop through all controls and look for its Name:

private void BtnRemoveTextbox2_Click(object sender, EventArgs e)
{
    foreach (Control ctrl in this.Controls) 
    {
        if (ctrl.Name == "Textbox2")
          this.Controls.Remove(ctrl);
    }
}

Upvotes: 1

Reza Aghaei
Reza Aghaei

Reputation: 125292

You need to find those controls using Controls.Find method and then remove and dispose them:

this.Controls.Find("Textbox2", false).Cast<Control>().ToList()
    .ForEach(c =>
    {
        this.Controls.Remove(c);
        c.Dispose();
    });

Upvotes: 1

Cooleshwar
Cooleshwar

Reputation: 417

You have to find it first before you choose to remove it.

private void BtnRemoveTextbox2_Click(object sender, EventArgs e)
{
    MetroFramework.Controls.MetroTextBox tbx = this.Controls.Find("Textbox2", true).FirstOrDefault() as MetroFramework.Controls.MetroTextBox;
    if (tbx != null)
    {
        this.Controls.Remove(tbx);
    }
}

Here, Textbox2 is the ID of your textbox. Please make sure you're setting the ID of your textbox control before adding it.

Upvotes: 1

Related Questions