Paul Michaels
Paul Michaels

Reputation: 16705

WinForms inherited form not able to see parent's variables

I’m trying to use a variable in a parent form to store a variable. The code for the parent form is as follows:

public partial class Form1 : Form
{
    internal string testVar;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        testVar = "button1";
        MessageBox.Show("testVar = " + testVar);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form2 newfrm = new Form2();
        newfrm.Show();
    }
}

So, if the user presses button1, it sets the variable to “button1”. Pressing button2 launches a child form, defined as follows:

public partial class Form2 : Form1
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        MessageBox.Show(base.testVar);
    }
}

So, button3 shows the value of the internal variable within the parent form. However, it is blank (regardless of whether it is set or not). Why can’t the child form see the values in the parent?

Upvotes: 0

Views: 1316

Answers (3)

Vlad
Vlad

Reputation: 35594

Your code doesn't access the parent form! You are using base.testVar, which accesses the variable in the current object inherited from the base class, but not from the Form1 instance which created the Form2 instance!

Maybe you want something like the following:

public partial class Form1 : Form
{
    ...
    private void button2_Click(object sender, EventArgs e)
    {
        Form2 newfrm = new Form2();
        newfrm.ParentForm = this;
        newfrm.Show();
    }
}

public partial class Form2 : Form1
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        string v = (ParentForm != null) ? ParentForm.testVar : "<no parent set>";
        MessageBox.Show(v);
    }
    public Form1 ParentForm;
}

(Well, you'll need a better protection for your ParentForm.)

Upvotes: 1

Sasha Goldshtein
Sasha Goldshtein

Reputation: 3519

These are two separate instances. One is your main form, an instance of Form1, which has the testVar variable set to a value. The other is the secondary form, an instance of Form1 which derives from Form1 but its testVar variable is not set.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273804

Because the instances of Parent and Child form each have their own copies.

This should work (and explain it) :

private void button2_Click(object sender, EventArgs e)
 {
        Form2 newfrm = new Form2();
        newFrm.testVar = this.testVar;
        newfrm.Show();
}

Upvotes: 1

Related Questions