Carl Dun
Carl Dun

Reputation: 235

How do I access a dynamic button's event handler? Visual Studio 2015 WPF

I'm trying to learn C# again and I was wondering what is the approach to achieve the result I needed, this is my code, it creates the label and button when I click a button.

    private void button_Copy_Click(object sender, RoutedEventArgs e)
    {
        counter++;

        Label lbl = new Label();
        lbl.Content = counter.ToString();
        lbl.HorizontalAlignment = HorizontalAlignment.Center;
        lbl.VerticalAlignment = VerticalAlignment.Center;
        lbl.FontSize = 50;

        Button bt = new Button();
        bt.Content = "X";
        bt.HorizontalAlignment = HorizontalAlignment.Right;
        bt.VerticalAlignment = VerticalAlignment.Top;

        grid.Children.Add(lbl);
        grid.Children.Add(bt);
    }

However I'm having a problem determining where to put the click event since it was created dynamically. What I wanted to happen was when I click the X button, it will remove the specific label and x button I clicked. So if I clicked the main button twice, it would show a 1 with an x on the top left and a 2 with an x on the top left and when I click the 2's x, it will remove both the label with 2 and the x button for 2.

Upvotes: 1

Views: 551

Answers (2)

Haukinger
Haukinger

Reputation: 10863

You can add a handler to your button's Clicklike this

bt.Click += (a,b) => grid.Children.Remove( a );

but you really should do it with a ListView and templates, as slugster suggested.

Upvotes: 2

mike
mike

Reputation: 475

Just add an event handler to the button:

private void button_Copy_Click(object sender, RoutedEventArgs e)
{
    counter++;

    Label lbl = new Label();
    lbl.Content = counter.ToString();
    lbl.HorizontalAlignment = HorizontalAlignment.Center;
    lbl.VerticalAlignment = VerticalAlignment.Center;
    lbl.FontSize = 50;

    Button bt = new Button();
    bt.Content = "X";
    bt.HorizontalAlignment = HorizontalAlignment.Right;
    bt.VerticalAlignment = VerticalAlignment.Top;

    // add subscriber
    bt.Click += Button_Click;

    grid.Children.Add(lbl);
    grid.Children.Add(bt);
}

// On click event for button
private void Button_Click(object sender, EventArgs e) 
{
    // do whatever when button is clicked

    // this is a reference to the button that was clicked,
    // you can delete it here or do whatever with it
    Button buttonClicked = (Button)sender;
}

Now, when the button is clicked, "Button_Click" will be fired off.

Upvotes: 2

Related Questions