获取Button父级的访问权限

时间:2015-07-02 10:31:05

标签: c#

我正在课堂上使用Button。按下按钮时,应该使用按钮的相应文本调用例程。如何将发件人转换为String_Entry?此外,我是面向对象/类编程的新手,所以欢迎提出意见。

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

1 个答案:

答案 0 :(得分: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将为您提供对包含按钮的Form或其他容器对象的引用,而不是String_Entry的此实例。要访问它,请使用this。因此,您可以将事件处理程序更改为:

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