0

When I try to change the label in the parent form it gives me a 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();
    }

Form2

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

1 Answers1

0

You should check Owner form instead of ParentForm. And you should pass owner when opening second form:

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

Form2:

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

But that's still not the best way to pass data between forms. Create public properties on Form2 form and read their values in Form1 if DialogResult returned OK after closing child form:

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

Community
  • 1
  • 1
Sergey Berezovskiy
  • 215,927
  • 33
  • 392
  • 421