简体   繁体   English

在点击事件中识别发件人按钮控件

[英]Recognizing sender button control in click event

I made a custom button that has a field named Data .我制作了一个自定义按钮,其中包含一个名为Data的字段。

I add this button programatically during runtime to my winform and on adding I also define a click event for them.我在运行时以编程方式将此按钮添加到我的 winform 中,并且在添加时我还为它们定义了一个点击事件。 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:但是在点击事件中我想访问这个Data字段并将其显示为消息框,但似乎我的转换不正确:

    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...对不起,我提到“没有编译”。 .Data没有出现在智能感知中……

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 ,您应该这样做:

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:我在 Github 上的 win forms 项目中发现了一个有趣的检查作业:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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