Ayush
Ayush

Reputation: 42440

How can I ascertain which button called event handler?

I have a form with two buttons: btn_oldFile and btn_newFile. Both buttons, on click call the function btnOnClick:

btn_oldFile.Click += btnOnClick;
btn_newFile.Click += btnOnClick;

protected void OldFileBrowse_Click(object sender, EventArgs args)
        {
            //if btn_oldFile called
                // print to tbx_OldFile
            //else
                //print to tbx_NewFile
        }

For the most part, btnOnClick is to do the same thing no matter which button called itself, except for assigning a value to a variable. If btn_oldFile calls the method, I print some text to a textbox: tbx_OldFile, while if btn_newFile calls it, the text is printed to tbx_NewFile.

How can I ascertain which button was the one that called the method?

Upvotes: 2

Views: 584

Answers (2)

JaredPar
JaredPar

Reputation: 754545

As Fara pointed out when a click occurs, the Button causing the click will be the first parameter. However this solution requires a cast and can be foiled by a derived type calling the method and not passing a Button type in the sender slot.

A more typesafe approach to this is to use a lambda expression to pass the relevant button down in a type safe fashion.

btn_oldFile.Click += delegate { OldFileBrowse_Click(btn_oldFile); };
btn_newFile.Click += delegate { OldFileBrowse_Click(btn_newFile); };

protected void OldFileBrowse_Click(Button sender) {
  //if btn_oldFile called 
    // print to tbx_OldFile 
  //else 
    //print to tbx_NewFile 
}

Upvotes: 0

Alex McBride
Alex McBride

Reputation: 7011

The object that raised the event is passed to the event handler as the sender parameter, so you can cast that to the correct type to access it.

protected void OldFileBrowse_Click(object sender, EventArgs args)
{
    Button btn = (Button)sender;
}

Edit: You can then use a basic if statement to check which button it was.

if (btn == btn_oldFile) // etc..

Upvotes: 9

Related Questions