在 C# winform 中删除运行时生成的控件

Remove runtime generated controls in C# winform

我有代码在用户右键单击面板时生成文本框。我需要一种方法来允许用户还 remove/delete 创建的文本框控件。这段代码是我在运行时创建文本框的方式:

private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            Point cp = panel1.PointToClient(Cursor.Position);
            i++;
            TextBox text = new TextBox();
            text = new TextBox();
            text.Name = "user_textbox" + i.ToString();
            text.Size = new System.Drawing.Size(panel1l.Width, 30);               
            text.Location = new Point(0, cp.Y);  // puts box at current mouse position  
            panel1.Controls.Add(text);
            text.Focus();
        }

我在另一个 post 中找到了删除控件的代码,但它无法满足我的需要。该代码在下面,但它旨在根据名称搜索和删除控件。我希望能够做的是右键单击已创建的文本框,然后选择删除它。任何帮助将不胜感激。

// this is code to remove controls using
// name of the control

foreach (Control ctrl in this.Controls) 
{
    if (ctrl.Name == "Textbox2")
      this.Controls.Remove(ctrl);
}

经过反复试验和大量阅读后,我发现菜单项不会从其当前容器中移除焦点。所以,我创建了一个菜单并添加了一个 "delete" 按钮。效果很好。

private void deleteCurrentScheduleToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (ActiveControl is TextBox)
        {
            this.panel1.Controls.Remove(ActiveControl);

        }
    }