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

时间:2019-03-28 23:40:25

标签: c# controls runtime

我有一些代码,当用户在面板上单击鼠标右键时会生成文本框。我需要一种允许用户删除/删除已创建的文本框控件的方法。这段代码是我在运行时创建文本框的方式:

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

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

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

1 个答案:

答案 0 :(得分:0)

经过反复试验和大量阅读后,我发现菜单项并未将Focus从其当前容器中删除。因此,我创建了一个菜单并添加了“删除”按钮。效果很好。

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

        }
    }