简体   繁体   中英

Recognizing sender button control in click event

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...

You need to cast to the type of your custom class that has the Data field.

Something like:

YourCustomButton button = sender as YourCustomButton;

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
  } 
}

If you dont want to set a variable the simple way to do is:

((CustomButton)sender).Click

or whatever you want.

I found a funny check assignment in a win forms project on Github:

private void btn_Click(object sender, EventArgs e){

 // here it checks if sender is button and make the assignment, all in one shot.
 // Bad readability, thus not recommended
 if (!(sender is Button senderButton)) 
                return;

var _text = senderButton.Text;
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM