C # cannot access public member of form from parent class

I am trying to add an event handler to a class that references the event of a form control that is generated in this class. All classes exist within the same namespace.

The program is based on the application of forms ApplicationContext

. Within static void Main()

inProgram.cs

CustomApplicationContext applicationContext = new CustomApplicationContext();
Application.Run(applicationContext);

      

Inside public class CustomApplicationContext

public class CustomApplicationContext : ApplicationContext
{
    //create the application form
    Form appForm;

    public CustomApplicationContext() 
    {
        InitializeContext();

        //create instance of appForm
        appForm = new AppForm();

        //subscribe event handler to form closing event
        appForm.FormClosing += form_FormClosing; //this works fine

        //subscribe event handler to form control click event
        appForm.someToolStripMenuItem.Click += form_Click; //doesn't compile

        //can't even find appForm.someToolStripmenuItem in code completion!
    }

    void form_FormClosing(object sender, FormClosingEventArgs e)
    {
        ...
    }

    void form_Click(object sender, EventArgs e)
    {
        ...
    }

    ...
}

      

And from the inside public partial class AppForm

in AppForm.Designer.cs

, which is generated by the constructor, where I made the control modifier public

and I made the classpublic

public partial class AppForm  //note that I made this public
{
    ...

    this.someToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

    ...

    // 
    // someToolStripMenuItem
    // 
    this.someToolStripMenuItem.Name = "someToolStripMenuItem";
    this.someToolStripMenuItem.Size = new System.Drawing.Size(178, 22);
    this.someToolStripMenuItem.Text = "Some Item";

    ...

    public System.Windows.Forms.ToolStripMenuItem someToolStripMenuItem;
}

      

What am I doing wrong? When I type appForm.

, someToolStripMenuItem

doesn't even appear in the code completion window, as if it was not available in the context, however appForm

available, but someToolStripMenuItem

- public

.

+3


source to share


2 answers


The compiler thinks that appForm

- it is Form

, not appForm

because of how you declare it:

Form appForm;

      



Try changing your declaration to, AppForm appForm;

or execute it like:

((AppForm)appForm).someToolStripMenuItem.Click += form_Click;

      

+2


source


The problem is that the field is appForm

declared as type Form

. The class Form

does not have a named member someToolStripMenuItem

. You need to declare your field as a type appForm

in order to access the members of that type.



+1


source







All Articles