简体   繁体   中英

How to access a non-static property from another class

I have a non-static property inside a non-static MainForm class:

public string SelectedProfile
{
    get { return (string)cbxProfiles.SelectedItem; }
    set { cbxProfiles.SelectedItem = value; }
}

I would like to get the value of this property, from another non-static class. Using MainForm.SelectedProfile gives an error saying "An object reference is required for the non-static field, method or property".

Usually I would solve this problem by making SelectedProfile static, but I can't, since cbxProfiles (a ComboBox control) can't be made static.

So how do I access the property's value without making it static?

You access non-static members the same way you always do: by using a reference to an instance of the object.

So whatever code you want to be able to use that property, you need to pass it a reference to a MainForm object.

As said in the compilation error, you need to have a reference of the existing MainForm instance to act on it.

// You surely do this somewhere in your code
MainForm mainForm = new MainForm();
// ...
// Use the reference to your mainForm to access its public properties
String selectedProfile = mainForm.SelectedProfile;

I might be late to the party but my solution might help someone someday down the road. You can directly access an open form's controls (even private ones) using Application.OpenForms[n] ...

For example, let's assume you have created a MainForm and then created a comboBox such that it is inside MainForm => Tab (named tabControl) => TabPage (named tabPageMain) => Panel (named pnlMain) => ComboBox (named cmbSeconds). Then you can access this last control as follows:

ComboBox combo = Application.OpenForms[0].Controls["tabControl"].Controls["tabPageMain"].Controls["pnlMain"].Controls["cmbSeconds"] as ComboBox;
string SelectedProfile = (string)combo.SelectedItem;

// OR

bool isMaximized = Application.OpenForms[0].WindowState == FormWindowState.Maximized;

ie you've got to traverse the path from the top-level form down to that particular control. Document Outline view of Visual Studio ( View menu => Other Windows => Document Outline ) might help you in this bcoz you might be overlooking some transparent containers in between.

Use it cautiously. For example, if the handles of any of the referenced controls are not yet created, you might see runtime exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM