c# - 如何删除按钮运行时间?

标签 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);
}

这就是我在运行时制作按钮的方式。

最佳答案

为了删除你添加的最后一个按钮,你可以使用这样的东西:

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

这应该允许您通过始终从现有按钮中删除最后添加的按钮来删除任意数量的按钮。

更新

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

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

  • 为您的 Form 创建 KeyDown 事件处理程序并在其中添加以下代码:

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

关于c# - 如何删除按钮运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10262178/

相关文章:

c# - 字符 + 字符 = 整数?为什么?

c# - MVC 显示目录列表未加载应用程序

c# - JsonPatchDocument 到复杂的 Entity Framework 跟踪对象

c# - 如何从使用存储过程的数据表填充 ListView

javascript - 每次单击按钮时使表单中的数字上升

c# - DataReader (DbCommand) 如何处理 DB 通信?

c# - 刷新一个控件

c# - 更改 DocumentCompleted 中 Web 浏览器控件的大小

Android:创建异形按钮

HTML:什么 css 属性使按钮 "center"中的内容?