如何删除按钮运行时间?

时间:2012-04-21 19:17:34

标签: c# winforms button

我的C#winform项目有问题 在我的项目中,我有一个在运行时创建一个新按钮的函数。因为有时候我创建了太多按钮,我想编写一个删除我想在运行时删除的按钮的函数。 有人可能已经有了这个功能吗?

private void button2_Click(object sender, EventArgs e)
{
        Button myText = new Button();
        myText.Tag = counter;
        myText.Location = new Point(x2,y2);
        myText.Text = Convert.ToString(textBox3.Text);
        this.Controls.Add(myText);
}

这就是我在运行时创建按钮的方式。

3 个答案:

答案 0 :(得分:2)

你应该可以使用this.Controls.Remove(myText);

答案 1 :(得分:2)

为了删除您添加的最后一个按钮,您可以使用以下内容:

//a list where you save all the buttons created
List<Button> buttonsAdded = new List<Button>();

private void button2_Click(object sender, EventArgs e)
{
    Button myText = new Button();
    myText.Tag = counter;
    myText.Location = new Point(x2,y2);
    myText.Text = Convert.ToString(textBox3.Text);
    this.Controls.Add(myText);
    //add reference of the button to the list
    buttonsAdded.Insert(0, myText);

}

//atach this to a button removing the other buttons
private void removingButton_Click(object sender, EventArgs e)
{
    if (buttonsAdded.Count > 0)
    {
        Button buttonToRemove = buttonsAdded[0];
        buttonsAdded.Remove(buttonToRemove);
        this.Controls.Remove(buttonToRemove);
    }
}

这应该允许您删除任意数量的按钮,方法是删除从现有按钮添加的最后一个按钮。

<强>更新

如果您希望能够使用鼠标光标悬停按钮,然后使用删除键将其删除,则可以使用此解决方案:

  • KeyPreview设置为 true ,因此Form可以接收其控件中发生的关键事件
  • 添加buttonsAdded列表并修改button2_Click,如本回答中描述的第一个解决方案

  • KeyDown创建Form事件处理程序并添加以下代码:

    private void MySampleForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Delete)
        {
            //get control hovered with mouse
            Button buttonToRemove = (this.GetChildAtPoint(this.PointToClient(Cursor.Position)) as Button);
            //if it's a Button, remove it from the form
            if (buttonsAdded.Contains(buttonToRemove))
                {
                    buttonsAdded.Remove(buttonToRemove);
    
                    this.Controls.Remove(buttonToRemove);
                }
        }
    }
    

答案 2 :(得分:1)

public Button myText ; // keep public button to assign your new Button 

private void buttonAdd_Click(object sender, EventArgs e)
{
        myText = new Button();
        myText.Tag = counter;
        myText.Location = new Point(x2,y2);
        myText.Text = Convert.ToString(textBox3.Text);
        this.Controls.Add(myText);
}

private void buttonRemove_Click(object sender, EventArgs e)
{
      if(Button != null && this.Controls.Contains(myText))
      {
           this.Controls.Remove(myText);
           myText.Dispose();
      )
}

如果你想在删除键上删除,按下可以使用按键事件,如下所示

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
          if(Button != null && this.Controls.Contains(myText))
          {
               this.Controls.Remove(myText);
               myText.Dispose();
          )
    }
}