2017-02-09 26 views
0

当我尝试更改父窗体中的标签时,它给了我一个NullReferenceException。父母形式给予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(); 
    } 
+0

也许ParentForm为空? –

+0

你还没有告诉Form2它有一个父窗体。这样做:'Form2 f2 = new Form2(this);' – Equalsk

回答

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