删除动态生成的选择按钮

时间:2016-02-17 12:05:58

标签: c# .net winforms dynamic-controls

我在C#中开发了一个winform应用程序。我想在按钮点击时动态生成按钮,让它命名为"添加"。在随机单击任何按钮,然后单击删除按钮时,应删除所选按钮。现在我该怎么做?

这是我的动态按钮生成代码

public void AddNewButton()
{
    System.Windows.Forms.Button();
    Btn = new Button();
    this.Controls.Add(Btn);
    Btn.Name = textBox_code.Text + count;
    Btn.Location = new Point(50, 50);
    Btn.Text = textBox_code.Text;
    Btn.BackColor = Color.Red;
    Btn.ForeColor = Color.Blue;
    Btn.Click += new EventHandler(this.button_Click);
    count = count + 1;
    label1.Text = count.ToString();
    Btn.MouseDown += new MouseEventHandler(textbox_MouseDown);
    Btn.MouseMove += new MouseEventHandler(textbox_MouseMove);
    Btn.MouseUp += new MouseEventHandler(textbox_MouseUp);
}

并删除按钮

private void button_delete_Click(object sender, EventArgs e)
{
    this.Controls.Remove(Btn);
    count = count - 1;
    label1.Text = count.ToString();
}

以上代码仅删除最后添加的按钮而不删除任何随机选择的按钮

2 个答案:

答案 0 :(得分:2)

添加变量以保存最后点击的按钮(在班级别)

Button lastClicked = null;
private void button_Click(object sender, EventArgs args) 
{
    ...
}

button_Click添加此内容,

private void button_Click(object sender, EventArgs args) 
{
    // whatever you already have...

    lastClicked = (Button)sender;
}

然后在你的删除按钮处理程序中

private void button_delete_Click(object sender, EventArgs e)
{
    // delete the last clicked button
    this.Controls.Remove(lastClicked);
    count = count - 1;
    label1.Text = count.ToString();
}

答案 1 :(得分:0)

您无法解释如何选择要删除的按钮,但作为使用按钮名称的一般答案,而不是

fgScrollView.contentInset = UIEdgeInsets(top: CGRectGetHeight((self.navigationController?.navigationBar.frame)!) + CGRectGetHeight(UIApplication.sharedApplication().statusBarFrame), left: 0,
bottom: CGRectGetHeight((self.navigationController?.toolbar.frame)!), right: 0)

怎么样?
this.Controls.Remove(Btn);

修改

好的,你确实解释了这个过程。然后一种方法是使用一个变量来存储最后点击的按钮:

foreach (Control c in this.Controls)
{
     if (c.Name == "Name of button to delete")
     {
           this.Controls.Remove(c);
           break;
     }
}

然后在button_Click事件处理程序中,执行以下操作:

Button btnLastClicked;

最后,

btnLastClicked=sender as Button;