1

I have a ToolStripMenuItem that I want to declare and instantiate with a String, a null value for an image, and an Event Handler for its Click event. This is the format Intellisense is expecting:

ToolStripMenuItem(string text, System.Drawing.Image image, EventHandler onClick).

But I am unable to assign the Event Handler and I do not know the proper syntax to do so. As a workaround, I assign the .Click event in the constructor like so...

class Timer
{
    //The other WinForms objects and my methods are omitted.
    private ToolStripMenuItem StartButton = new ToolStripMenuItem("Start Timer");

    public Timer()
    {
        //I want the assignment of StartButton_Click in my declaration and initialization of StartButton, not here.
        StartButton.Click += new EventHandler(StartButton_Click);
    }

    public void StartButton_Click(object sender, EventArgs e)
    {
        //The logic here is not relevant.
    }
}

I tried the syntax below but I keep getting the error: "CS0236 A field initializer cannot reference the non-static field, method, or property 'Timer.StartButton_Click(object, EventArgs)'"

new ToolStripMenuItem("Start Timer", null, new EventHandler(StartButton_Click));

Intelliense suggests I use the format

EventHandler(void(object,EventArgs)target)

but I do not know how to fill out the expected syntax property. How do I write the declaration of StartButton so that the method StartButton_Click is called after a Click event?

Bill
  • 47
  • 1
  • 8
  • Now that I know the answer, it does not matter. I'm self teaching and do not always know what the best practices are. When Intellisense suggested that method signature (String, Image, EventHandler) I just assumed you could do that outside of the constructor. – Bill Nov 25 '15 at 04:31

2 Answers2

2

The correct place to instantiate it is in the constructor. Do it all at once, like this:

private ToolStripMenuItem StartButton;

public Timer()
{
    StartButton = new ToolStripMenuItem("Start Timer", null, StartButton_Click);
}

As for that compiler error, you can read more about it here, although it's sparse on the details.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
0

From Stack Overflow: You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before StartButton_Click, so the above line might throw a NullReferenceException.

Make the method static and you should be good to go.

Community
  • 1
  • 1
T.J. Moats
  • 533
  • 1
  • 5
  • 8
  • Your solution will work perfectly as long as the method does not contain non-static variables. – Bill Nov 25 '15 at 04:26