Alessio Raddi
Alessio Raddi

Reputation: 622

Remove Handler to Button

I'm trying to remove a handler (Click) from a button, I tried many ways but they didn't work.

I create two buttons like this:

private void CreateButtons()
{
    Button button1 = new Button()
    {
        Text = "Start"
    };
    Button button2 = new Button()
    {
        Text = "Stop"
    };
    this.Controls.Add(button1);
    button1.Click += Button1_Click;
    this.Controls.Add(button2);
    button2.Click += Button2_Click;
}

The first one just creates a MessageBox:

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

The second one should remove the handler:

private void Button2_Click(object sender, EventArgs e)
{
    button1.Click -= Button1_Click;
}

Unfortunately after clicking button2, button1 keeps generating a MessageBox. What am I doing wrong?

Upvotes: 0

Views: 109

Answers (1)

Sach
Sach

Reputation: 10393

It appears that your form has a different button you've created at an earlier time named button1.

Remove that, and make your button1 and button2 fields of the form.

public partial class Form1 : Form
{
    private Button button1;
    private Button button2;

    public Form1()
    {
        InitializeComponent();
    }

    private void CreateButtons()
    {
        button1 = new Button()
        {
            Font = new Font(Font.FontFamily, 10, FontStyle.Bold),
            BackColor = Color.Yellow,
            Width = 79,
            Height = 62,
            Location = new Point(141, 191),
            Text = "Start"
        };

        button2 = new Button()
        {
            Font = new Font(Font.FontFamily, 10, FontStyle.Bold),
            BackColor = Color.Yellow,
            Width = 79,
            Height = 62,
            Location = new Point(338, 191),
            Text = "Stop"
        };
        this.Controls.Add(button1);
        button1.Click += Button1_Click;
        this.Controls.Add(button2);
        button2.Click += Button2_Click;
    }

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

    private void Button2_Click(object sender, EventArgs e)
    {
        button1.Click -= Button1_Click;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CreateButtons();
    }
}

Upvotes: 2

Related Questions