0

My intention is to create buttons at runtime and have a click event handler subscribed to them. Once the dynamically created button is clicked, the click eventhandler is unsubscribed, such that the click event only fires once.

At runtime the desired behaviour only works if I create one button and click it immediately . If I create more than one button, than only the last created button unsubscribes from the click event. Did I miss something?

public partial class Form1 : Form
{
    Button b;
    int counter;

    public Form1()
    {
        InitializeComponent();
    }

    // create more buttons
    private void button1_Click(object sender, EventArgs e)
    {
        b = new Button();
        b.Size = new Size(50, 50);
        b.Click += b_Click; // dynamic button click event
        this.Controls["flowLayoutPanel"].Controls.Add(b);

    }

    // dynamic button click eventhandler
    void b_Click(object sender, EventArgs e)
    {
        b.Text = counter.ToString();
        b.Click -= b_Click;
        counter++;
    }
}
0

1 Answer 1

2

Because b member will reference last created dynamic button, so clicking any buttons will remove click event handler of currently referenced button in b variable, which would be last created.

Use sender to access instance of "current" button and remove click event handler only from "current" button.

void b_Click(object sender, EventArgs e)
{
    var button = sender As Button;
    button.Text = counter.ToString();
    button.Click -= b_Click;
    counter++;
}

Don't use private member for dynamic button, but local variable

private void button1_Click(object sender, EventArgs e)
{
    var button = new Button();
    button.Size = new Size(50, 50);
    button.Click += b_Click;
    this.Controls["flowLayoutPanel"].Controls.Add(button);
}

If you need to reference collection of created button somewhere, you can access them from the controls of flow panel where buttons were added

var dynamicButtons = . 
    this.Controls["flowLayoutPanel"].Controls.OfType<Button>().ToList();

Or save them to the dedicated collection (in case flow panel has other buttons)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.