Nick
Nick

Reputation: 1268

Accessing child form property in C# window's forms

So I am trying to access a public member variable of my child form from its parent form. The form has a public get property from which I am trying to access the variable. Here is how the variable is defined in my child form:

    public partial class frmNewProduct : Form
{
    public Inventory _inventory { get; private set; }

Now let's switch pace and go to the parent form. The instance of the child form is created below, and you can also see me trying to access _iventory's get property from that instance, but I receive compiler errors every time.

        private void btnAdd_Click(object sender, EventArgs e)
    {
        Form newProduct = new frmNewProduct(_inventory, Mode.add);
        newProduct.Show();
        Inventory variable = newProduct._inventory;
    }

The compiler error reads the following:

Error 1 'System.Windows.Forms.Form' does not contain a definition for '_inventory' and no extension method '_inventory' accepting a first argument of type 'System.Windows.Forms.Form' could be found (are you missing a using directive or an assembly reference?)

Does anyone know what is wrong here? Thank you.

Upvotes: 0

Views: 1931

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65097

You're creating a type of the parent type Form. You need to declare it as the derived type, frmNewProduct. E.g:

frmNewProduct newProduct = new frmNewProduct(_inventory, Mode.add);
newProduct.Show();
Inventory variable = newProduct._inventory;

To clarify: You're adding a property to the type frmNewForm which inherits from Form. Form doesn't have the property, so you can't access it when declaring your variable as type Form.

Another example:

class BaseClass {
}

class DerivedClass : BaseClass {
    public int MyProperty { get; set; }
}

Using the above code, you can't do this:

BaseClass base = new DerivedClass();
base.MyProperty = 12; // ERROR

..however, you can do this:

DerivedClass derived = new DerivedClass();
derived.MyProperty = 12; // Works

Upvotes: 4

Related Questions