简体   繁体   中英

An object reference is required for the non-static field, method or property error

I am developing a C# windows form application and on the main form I have a TabControl. It is declared in the Form1.Designer.cs file as follows:

public System.Windows.Forms.TabControl logFileCollectorTabControl;

In another class file in my project I want to use this TabControl as follows:

 logFileCollectorForm.logFileCollectorTabControl.TabPages.Add(newTabPage);

But I get the error 'An object reference is required for the non-static field, method or property error'. So my question is, there must be an object of the Form class declared somewhere because the form launches when I launch the application, so how do I find out what that is, or how can I solve this issue, any help is greatly appreciated!

This is usually overcome by passing in an instance of Form1 to the constructor of the calling class, then keeping it in a field until needed.

//somewhere in Form1
OtherClass other = new OtherClass (this);

// OtherClass.cs
class OtherClass {
    Form1 _opener;

    public OtherClass(Form1 opener) {
        _opener = opener;
    }
}

Is your other class aware of logFileCollectorForm?

If you do not pass a reference to the form to the other class, then the other class does not know what Is logFileCollectorForm is referencing.

//example of another class
class AnotherClass
{
    Form1 logFileCollectorForm;

    public AnotherClass(Form1 logFileCollectorForm)
    {
        this.logFileCollectorForm = logFileCollectorForm;
    }


    public DoSomething(String newTabPage)
    {
        logFileCollectorForm.logFileCollectorTabControl.TabPages.Add(newTabPage);
    }
}

There is probably no need to pass an instance of an entire form, you could pass a reference to your TabControl only. But it's still bad design in my opinion. Your logic should be separated from UI. If your class performs some computations, database operations or what not, it shouldn't really have to "know" about your window at all, because this is inflexible. Implement an event instead.

Another option is to keep a static reference to the main form in the Program class.

static class Program
{
    internal static Form1 MainForm { get; set; } 

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MainForm = new Form1();
        Application.Run(MainForm);
    }
}

class OtherClass
{
    public void AddNewTab(TabPage newTabPage)
    {
        Program.MainForm.logFileCollectorTabControl.TabPages.Add(newTabPage);
    }
}

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