Click here to Skip to main content
15,887,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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");
        }


how to remove button2 after displaying "Hello World"?

What I have tried:

b.Dispose();


it does not display button at first.

Thank you!
Posted
Updated 25-Oct-17 1:23am
v2

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");
}
 
Share this answer
 
Comments
Member 13462842 25-Oct-17 3:05am    
why it works also without
1. b.Click-=Hello
2. buttons.Clear();
are they necessary?
OriginalGriff 25-Oct-17 4:03am    
Yes.
The first removes the event handler, so that the Garbage Collector can Dispose the control if it needs to. You don't strictly need this for small test apps, but it's a good idea to use good practices even for small projects - that way you don't forget and get caught with larger ones!
The second removes the buttons from the list, so that if you call the RemoveButtons method again you don't try to remove buttons you have already dealt with.
No need to search for the button since it's already known in its own click handler:
C#
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900