简体   繁体   中英

button in c# not firing

I am writing a simple code it has 3 buttons 2 that will need to open up other forms and one to close the program. When i start the program the exit button will not work even though i have it coded the same as any other time i have wrote a program.

When i press any of the buttons nothing happens. Im not 100% sure how to use the buttons to open another form but i know the exit button should work as is.

Here is the 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 _3343_ParksJ_Lab02
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void workerButton_Click(object sender, EventArgs e)
        {
            WorkerForm workersForum = new WorkerForm();
        }

        private void suppervisorButton_Click(object sender, EventArgs e)
        {
            SupervisorForm workersForum = new SupervisorForm();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

You have to subscribe your buttons' click events to the event methods before they'll fire correctly.

You can check the Designer.cs file to see if this has already been done, though I'm guessing it hasn't. You'll be looking for something like this:

this.workerButton.Click += new System.EventHandler(this.workerButton_Click);

One way to do so is directly in the constructor:

public MainForm()
{
    InitializeComponent();

    workerButton.Click += workerButton_Click;
    suppervisorButton.Click += suppervisorButton_Click;
    exitButton.Click += exitButton_Click;
}

Normally, I'd do this through the designer. Select each Button in turn, then open the properties panel and double-click on the event you wish to subscribe to, which will create the corresponding event method in the code-behind for you.

在此处输入图片说明

Look at .Designer.cs file and make sure your button is adding the correct delegate method. In your case it should exitButton_Click.

Sometimes when you change names of a button VS designer does not make the name change correctly in the .Designer file. Very rare but it happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM