C# 识别点击事件中的发件人按钮控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11387070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:41:32  来源:igfitidea点击:

Recognizing sender button control in click event

c#winformscustom-controls

提问by Saeid Yazdani

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. Well, Actually I only have one method and I subscribe the newly added buttons to this method.

我在运行时以编程方式将此按钮添加到我的 winform 中,并在添加时为它们定义了一个单击事件。好吧,实际上我只有一种方法,并且我将新添加的按钮订阅到此方法。

But in the click event I want to access this Datafield 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 .Datadoes not show up in intelisense...

对不起,我提到了“未编译”,.Data它没有出现在智能感知中......

采纳答案by David Hall

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

您需要转换为具有 Data 字段的自定义类的类型。

Something like:

就像是:

YourCustomButton button = sender as YourCustomButton;

回答by GETah

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

回答by Elvis Silva Noleto

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

如果您不想设置变量,简单的方法是:

((CustomButton)sender).Click

or whatever you want.

或任何你想要的。