Home>

Nice to meet you. I am learning C# from today.
I've heard about the Close method.

If i write this.Close();in button1, the form will close properly,
Even if you write this.Close();of button2, the form does not close.
I'd like the form to close on button2, but I'm having trouble understanding why it doesn't.
We apologize for such questions, but we would appreciate your answer.
Applicable source code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void label1_Click(object sender, EventArgs e)
        {
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
What I tried

I looked up the Close method on the net to find out what was wrong, but I'm not sure.

Supplementary information (FW/tool ​​version, etc.)

I am using Visual Studio 2015.

c#
  • Answer # 1

    When espering, button2_Click just copy and copy button1_Click and rewrite 1 into 2, and button 2 (name is automatically created) is added regardless of that, so no event handler is registered.

    In that case, after adding button 2, the event handler is automatically generated by the same procedure as button 1, and then the processing inside (this.Close();) Let's copy and paste

    What if we made button2_Click first? In that case, let's examine the procedure for adding an existing method to the event handler of the button.

  • Answer # 2

    Let's set a breakpoint at this.Close();(click the line there to mark it) and see if execution stops there.
    If you don't go there when you click the button, it won't close.