[英]Recognizing sender button control in click event
我制作了一個自定義按鈕,其中包含一個名為Data
的字段。
我在運行時以編程方式將此按鈕添加到我的 winform 中,並且在添加時我還為它們定義了一個點擊事件。 好吧,其實我只有一種方法,我將新添加的按鈕訂閱到這個方法。
但是在點擊事件中我想訪問這個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!
}
更新:
對不起,我提到“沒有編譯”。 .Data
沒有出現在智能感知中……
您需要強制轉換為具有“數據”字段的自定義類的類型。
就像是:
YourCustomButton button = sender as YourCustomButton;
假設您的自定義按鈕類型是CustomButton
,您應該這樣做:
CustomButton_Click(object sender, EventArgs e){
CustomButton button = sender as CustomButton;
if (button != null){
// Use your button here
}
}
如果您不想設置變量,那么簡單的方法是:
((CustomButton)sender).Click
或者你想要什么。
我在 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.