0
votes

I'm a real beginner on c# and everything. But I was trying to make my first program when I got this problem. I've done the "private void closeButton_Click(object sender, EventArgs e)" Wich says when click the custom close button it will show a confirm message.

But I want that one of the items on the menu strip named 'Exit', do the same thing as on that "private void closeButton_Click".

It's a short code, I could write a new message box and everything but it's got to be a way to simply repeat a code.

Here is the code

private void closeButton_Click(object sender, EventArgs e)
        {
            DialogResult dialog = MessageBox.Show("Do you really want to exit?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialog == DialogResult.Yes)
            {
                Application.Exit();
            }
            else if (dialog == DialogResult.No)
            {
                //Close 'dialog'
            }
        }


private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            closeButton_Click = true;
        }
2
What's wrong with closeButton_Click(null, null); in the exitToolStripMenuItem_Click event?Siyavash Hamdi

2 Answers

2
votes

You're using closeButton_Click as a boolean variable (setting it to true), but it is a method.

You can just call the method.

private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
    closeButton_Click(sender, e);
}
2
votes

The way this is done it .NET is through event handler delegates. In the case of different buttons, it's probably on their "Click" event. The setup looks like this:

protected void CloseHandler(object sender, EventArgs e){ /*code goes here*/ }

//two buttons, referencing the same handler.
firstButton.Click += CloseHandler;
secondButton.Click += CloseHandler;