2017-02-09 87 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