1

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.

Carl Dun
  • 225
  • 4
  • 13
  • Use a ListView and a custom template instead, that way you don't have to programmatically create and add new controls (they'll get created for you when you add a new item to the ListView). – slugster Jan 26 '16 at 11:39
  • See this example: http://stackoverflow.com/questions/6187944/how-can-i-create-dynamic-button-click-event-on-dynamic-button – sr28 Jan 26 '16 at 11:45

2 Answers2

2

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.

mike
  • 455
  • 2
  • 6
2

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.

Haukinger
  • 10,420
  • 2
  • 15
  • 28