Recognizing sender button control in click event
Solution 1
You need to cast to the type of your custom class that has the Data field.
Something like:
YourCustomButton button = sender as YourCustomButton;
Solution 2
Assuming your custom button type is CustomButton
, you should do this instead:
CustomButton_Click(object sender, EventArgs e){
CustomButton button = sender as CustomButton;
if (button != null){
// Use your button here
}
}
Solution 3
If you dont want to set a variable the simple way to do is:
((CustomButton)sender).Click
or whatever you want.
EMBEDONIX
Protecting yourself against thrown exceptions, considered as a defensive programming practice.
Updated on April 27, 2020Comments
-
EMBEDONIX about 4 years
I made a custom button that has a field named
Data
.I add this button programatically during runtime to my winform and on adding I also define a click event for them. Well, Actually I only have one method and I subscribe the newly added buttons to this method.
But in the click event I want to access this
Data
field and show it as a message box, but it seems that my casting is not right:CustomButton_Click(object sender, EventArgs e) { Button button; if (sender is Button) { button = sender as Button; } //How to access "Data" field in the sender button? //button.Data is not compiling! }
UPDATE:
I am sorry, I ment with "is not compiling" that
.Data
does not show up in intelisense...