ParentForm and a null reference
-
I'm trying to load some data from a parent form, actually the main Form, of my app into a dialog box using the following: Config config; config = ((Form1)this.ParentForm).config; the ParentForm though is always 'undefined' and a NullReferenceException occurs with the followiing information: 'Object reference not set to an instance of an object' I'm confused, as I followed the code example in the C# help "Retrieving Information from the Parent Form of a Dialog Box". What am I doing wrong, how do I manage this?
-
I'm trying to load some data from a parent form, actually the main Form, of my app into a dialog box using the following: Config config; config = ((Form1)this.ParentForm).config; the ParentForm though is always 'undefined' and a NullReferenceException occurs with the followiing information: 'Object reference not set to an instance of an object' I'm confused, as I followed the code example in the C# help "Retrieving Information from the Parent Form of a Dialog Box". What am I doing wrong, how do I manage this?
When are you trying to do this? In the constructor? ParentForm has the default value (null) when in the constructor (just like any other variable).
-
When are you trying to do this? In the constructor? ParentForm has the default value (null) when in the constructor (just like any other variable).
I'm not doing any of this in the constructor. A simple case is: I have 2 forms Form1 has a public string, myString, initialised with "ABCDEF". It also has a button that when clicked loads Form2:
private void button1_Click(object sender, System.EventArgs e) { Form2 frm = new Form2(); frm.Show(); }
Form2 has a label on it, in the label's 'Click' event I try to set it's Text with the following:void label1_Click(object sender, System.EventArgs e) { label1.Text = ((Form1)this.ParentForm).myString; }
This causes the NullReferenceException and when I highlight 'this.ParentForm', it shows as Why? -
I'm not doing any of this in the constructor. A simple case is: I have 2 forms Form1 has a public string, myString, initialised with "ABCDEF". It also has a button that when clicked loads Form2:
private void button1_Click(object sender, System.EventArgs e) { Form2 frm = new Form2(); frm.Show(); }
Form2 has a label on it, in the label's 'Click' event I try to set it's Text with the following:void label1_Click(object sender, System.EventArgs e) { label1.Text = ((Form1)this.ParentForm).myString; }
This causes the NullReferenceException and when I highlight 'this.ParentForm', it shows as Why?Ah, I see. The problem is that when you use Form.Show(), it creates a global form, not a child form. You either need to set the Parent property manually (which will also put the second form "into" the first form visually) or create a modal form using Form.ShowDialog().