C# Can Not Access public member of Form from Parent Class

906 views Asked by At

I am trying to add an event handler in a Class that refers to an event of a Form Control which is instantiated within that Class. All classes exist within the same namespace.

The program is based on an ApplicationContext forms application. Within static void Main() in Program.cs

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

Within the 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 within the public partial class AppForm in AppForm.Designer.cs which is generated by the designer, where I have made the control modifier public and I have made the class public

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 on earth am I doing wrong? When I type appForm., someToolStripMenuItem doesn't even appear in the code completion box, as if it were inaccessible in the context - however appForm is accessible, and someToolStripMenuItem is public.

2

There are 2 answers

2
Juan On BEST ANSWER

The compiler thinks appForm is a Form and not an AppForm because of the way you're declaring it:

Form appForm;

Either try changing the declaration to AppForm appForm; or cast it like:

((AppForm)appForm).someToolStripMenuItem.Click += form_Click;
0
jmcilhinney On

The issue is that your appForm field is declared as type Form. The Form class has no member named someToolStripMenuItem. You need to declare your field as type AppForm in order to access members of that type.