0

In my form1 I have a variable

public string parent;

and in my form2 I have the code to set that variable's value

 Form1 bfm = new Form1();

 bfm.ShowDialog(this);
 bfm.parent = "EditItem";

but when I used the variable parent it gives me a null reference exception

What could be the problem here? Can anyone help me? Thank you in advance. I am just a beginner.

yigyung
  • 19
  • 1
  • 5

2 Answers2

0

ShowDialog is modal. The assignment of parent doesn't occur until the the dialog is closed. You need to do the assignment before calling ShowDialog.

var bfm = new Form1() { parent = "EditItem" };
bfm.ShowDialog(this);
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
0

This may help you...

Just create a Parent on the Form1 class and set it before you show Form1.

public class Form1
{
  ...
 public string Parent{ get; set; }

 private void Form1_Load(object sender, EventArgs e)
 {
   MessageBox.Show(this.Parent);
 }
}

From Form2:

public void button1_Click(object sender, EventArgs e)
{
string dName = "EditItem";
Form1 bfm= new Form1();
bfm.Parent= dName;
bfm.Show();
this.Hide();
}
Anoop B.K
  • 1,484
  • 2
  • 17
  • 31