2015-07-02 36 views
1

我在類中使用Button。當按下按鈕時,它應該用按鈕的相應文本調用例程。如何將發件人轉換爲String_Entry?另外,關於面向對象/類編程,我是一個新手,所以我們歡迎評論。訪問Button父項

public class String_Entry 
{ 
    public TextBox textbox; 
    public Button send; 
    // other stuff 

    public String_Entry() 
    { 
     textbox = new TextBox(); 
     send = new Button(); 
     send.Click += new System.EventHandler(this.bSend_Click); 
     // put in GUI, set parameters and other stuff 
    } 

    // other stuff 

    private void bSend_Click(object sender, EventArgs e) 
    { 
     // Trying to get the corresponding String_Entry from the Button click event 
     Button cntrl = (Button)sender; 
     String_Entry entry = (String_Entry)(cntrl.Parent); 

     parse.ProcessHexLine(entry); 
    } 
} 
+0

爲什麼不通過'this'? – germi

+0

查看https://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396父屬性。你沒有正確使用它。同時檢查標籤屬性。 –

回答

3

您使用文本框和事件處理程序封裝按鈕的解決方案是健全的。它只是錯在事件處理程序:

private void bSend_Click(object sender, EventArgs e) 
{ 
    Button cntrl = (Button)sender; 
    String_Entry entry = (String_Entry)(cntrl.Parent); 

    parse.ProcessHexLine(entry); 
} 

首先,有沒有一點做什麼用sender,因爲它會是一樣的場send。接下來cntrl.Parent將爲您提供對包含按鈕的表單或其他容器對象的引用,而不是String_Entry的此實例。要訪問它,請使用this。因此,您可以將事件處理程序更改爲:

private void bSend_Click(object sender, EventArgs e) 
{ 
    parse.ProcessHexLine(this); 
}