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
.
The compiler thinks
appForm
is aForm
and not anAppForm
because of the way you're declaring it:Either try changing the declaration to
AppForm appForm;
or cast it like: