简体   繁体   English

删除在运行时创建的控件

[英]Remove control created at runtime

I wrote some code to create an additional textbox during runtime. 我写了一些代码来在运行时创建一个额外的textbox I'm using the metro framework, but this shouldn't matter for my question. 我正在使用metro框架,但这对我的问题无关紧要。

When you click a button, a textbox is being created by a private on_click event: 单击按钮时, private on_click事件正在创建textbox

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. 我现在要做的是使用另一个按钮的click事件,再次删除文本框。 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. 此外,我既不能访问Textbox2 Control,也不能访问其他地方的对象。

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 . 这不起作用,因为另一种形式不知道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? 我是否必须公开任何内容,如果是这样,我该怎么做?

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. 在这里, Textbox2是文本框的ID。 Please make sure you're setting the ID of your textbox control before adding it. 在添加之前,请确保您正在设置文本框控件的ID。

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 : 要删除它,请遍历所有控件并查找Name

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

You need to find those controls using Controls.Find method and then remove and dispose them: 您需要使用Controls.Find方法找到这些控件,然后删除并处置它们:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM