Erik S
Erik S

Reputation: 45

Pass name of button to click event

I am generating a number of buttons with similar or identical content and was hoping to use the names they are given to differentiate them. As the program is creating the buttons dynamically I can't create a separate event for them all and instead need to be able to grab the name to be able to know which button triggered the event.

Is there a way to pass through the name of a button to the click event it initiates? the sender object seems to contain the content but not the name.

It is for a event like this:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        //getname of button
        Canvas.Children.Remove(//name of button\\)
    }

Upvotes: 1

Views: 1891

Answers (3)

MethodMan
MethodMan

Reputation: 18843

Perhaps getting at the control's name will work for you

private void button1_Click(object sender, RoutedEventArgs e)
{
  Control control = (Control)sender;
  Canvas.Children.Remove(control.Name);
}

Upvotes: 0

Kal_Torak
Kal_Torak

Reputation: 2551

Far as I know, WPF does not even assign anything to the Name property automatically - that's just for developers to assign so we can reference the control.

However, you should be able to just pass in the sender to the remove method since it accepts a UIElement argument which Button is derived from.

Canvas.Children.Remove((Button)sender);

Upvotes: 6

Win
Win

Reputation: 62260

I'm not familiar with WPF. If this answer appears to be a junk, I'll delete it.

In ASP.Net, we can cast to a button to get the sender's information. Something like this -

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    button.Name
}

Upvotes: 5

Related Questions