I have a Windows Forms application containing around 15 different buttons which on-click should display either 1 or 0.
Now the problem:
Currently i’m repeating almost the exact same code for each and every button and that works fine, but what i would like to do is some method that knows which button i’m currently pressing and then i would like to send that buttons name as a parameter to the function which contains the code.
This is how i’m doing it now:
private: System::Void button1Click(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
//CODE HERE
}
private: System::Void button2Click(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
//SAME CODE HERE
}
And this goes on until button 15…
What i would like to do:
private: System::Void justClicked(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
//CODE HERE with justClicked as the buttons name.
}
The
senderparameter, though defined as an object, is the reference to the object that caused the event. All you have to do is castsenderto a Button, or Control, to get the name or whatever property you need.You also just need a single event handler. All your buttons’ Click events should be assigned to the same event handler function.