如何动态删除表单中的按钮 [英] How to dynamically remove a button in a form

查看:242
本文介绍了如何动态删除表单中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Button b = new Button();
            b.Text = "button2";
            
            Controls.Add(b);
            b.Click += Hello;
            
        }

      

        private void Hello(object sender, EventArgs e)
        {
            MessageBox.Show("hello World");
        }





如何在显示Hello World后删除button2?



我尝试过:





how to remove button2 after displaying "Hello World"?

What I have tried:

b.Dispose();





它最初不显示按钮。



谢谢!



it does not display button at first.

Thank you!

推荐答案

要删除它,必须先从Controls集合中删除它!

使用现有代码很困难,因为除非它是表单上的唯一按钮(并且不是),否则您将难以确定要删除的按钮!



试试这个:

To remove it, you must first remove it from the Controls collection!
That's difficult with your existing code, because unless it's the only button on your form (and it isn't), you will have difficulty identifying which button to remove!

Try this:
public Form1()
{
    InitializeComponent();
}
private List<Button> buttons = new List<Button>();
private void button1_Click(object sender, EventArgs e)
{
    Button b = new Button();
    b.Text = "button2";
    
    Controls.Add(b);
    buttons.Add(b);
    b.Click += Hello;
    
}

private void RemoveButtons()
{
    foreach (Button b in buttons)
    {
        Controls.Remove(b);
        b.Click -= Hello;
    }
    buttons.Clear();
}

private void Hello(object sender, EventArgs e)
{
    MessageBox.Show("hello World");
}


无需搜索按钮,因为它已经在自己的点击处理程序中已知:

No need to search for the button since it's already known in its own click handler:
private void Hello(object sender, EventArgs e)
{
    MessageBox.Show("hello World");
    
    Button thisButton = sender as Button;
    if(thisButton != null)
    {
        thisButton.Click -= Hello;
        Controls.Remove(thisButton);
    }
}

免责声明:代码没有经过任何特定目的的测试,没有特别的目的,你知道这一切。

Disclaimer: Code not tested in any way, no particular purpose, you know all that.


这篇关于如何动态删除表单中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆