父母表单给出NullReferenceException

时间:2017-02-09 17:21:57

标签: c#

当我尝试更改父表单中的标签时,它会给我一个NullReferenceException。

Form1

    public string LabelText
    {
        get
        {
            return label1.Text;
        }
        set
        {
            label1.Text = value;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog();
    }

窗体2

    private void button1_Click(object sender, EventArgs e)
    {
        ((Form1)ParentForm).LabelText = textBox1.Text;
        this.Close();
    }

1 个答案:

答案 0 :(得分:0)

您应该检查Owner表单而不是ParentForm。你打开第二张表格时应该通过所有人:

private void Form1_Load(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    f2.ShowDialog(this);
}

窗体2:

private void button1_Click(object sender, EventArgs e)
{
    ((Form1)Owner).LabelText = textBox1.Text;
    this.Close();
}

但这仍然不是在表单之间传递数据的最佳方式。在Form2表单上创建公共属性,并在关闭子表单后 Form1返回DialogResult时在OK 中阅读其值:

private void Form1_Load(object sender, EventArgs e)
{
    using(Form2 f2 = new Form2())
    {
        if (f2.ShowDialog() != DialogResult.OK)
           return;

        LabelText = f2.SomeValue;   
    }
}

Whats the difference between Parentform and Owner