user1051434
user1051434

Reputation: 167

Dynamic button EventArgs Click

I have a method that creates a Button for each Item of my List. Something like that:

foreach (Product p in productsList)
{
    b = new Button();
    b.Name = p.Name;
    b.Tag = p.Name;
    b.Text = p.Name;
    b.Size = new Size(93, 23);
    b.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly;
    b.AutoSize = true;
    b.Click += new System.EventHandler(this.b_Click);

    this.ProdutosFlowPanel.Controls.Add(b);
}

Now, when the user cliks on one of those Buttons I want to display a different view. But the buttons have the same identifier so the view diaplayed was always for the laste button created. How can I solve my problem? Any ideas?

Thank you.

Best regards, Maria

Upvotes: 0

Views: 1317

Answers (2)

Zak
Zak

Reputation: 734

You can use the Buttons' Tag:

b.Tag = p;

And in your handler:

Product p = ((Product)((Button)sender).Tag);

And then do logic depending on the original product.

Edit: changed DataContext (WPF) to Tag (WinForms).

Upvotes: 2

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

try with this code

protected void Submit_Click(object sender, EventArgs e)
    {
        var flag = ((Button)sender).Text;
        if (flag == "case 1")
        {
           ....
        }

        else if (flag == "case 1")
        {
           ....
        }
        .....

Upvotes: 1

Related Questions