2012-07-08 53 views
2

我做了一個自定義按鈕,其中有一個名爲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! 
    } 

UPDATE:

我很抱歉,我認爲「不編譯」.Data不顯示在intelisense中......

+0

您不必檢查是否sender''是'Button' ,因爲'as'關鍵字確保你的變量是'null',如果它不能將你的變量轉換爲正確的類。 – Styxxy 2012-07-08 22:04:40

+4

這是無效的C#代碼,所以當然不起作用。通常,自定義按鈕控件應該重寫OnClick方法,以便它可以實現自己的自定義點擊事件行爲。 – 2012-07-08 22:07:39

+0

您是如何嘗試訪問「數據」字段的? – 2012-07-08 22:08:46

回答

5

您需要轉換爲具有數據字段的自定義類的類型。

喜歡的東西:

YourCustomButton button = sender as YourCustomButton; 
+3

aaaaaaah我好蠢! – 2012-07-08 22:05:47

+0

@ Sean87這個答案解決了無法訪問數據字段的問題,但更好的長期方法是遵循Hans的評論並重寫OnClick,或者可能引入自定義事件以使事物觸摸更安全 - 您目前依賴於佈線customhandler(這只是一個標準處理程序簽名)到右側按鈕。通過自定義事件,您可以確保接線是正確的。 – 2012-07-08 22:13:39

+1

+1更快:D – GETah 2012-07-08 22:14:51

3

假設您的自定義按鈕類型是CustomButton,你應該這樣做,而不是:

CustomButton_Click(object sender, EventArgs e){ 
    CustomButton button = sender as CustomButton; 
    if (button != null){ 
     // Use your button here 
    } 
}