首页 > 解决方案 > C# won't allow me to add event handler to a button into a form class

问题描述

This is a C# web form project I am starting with after a long time away from IDE coding...

I am trying to make a simple custom dialog box class. This is my code.

public static class Dialogo
{
        public static int show ()
        {
            Form dialogo = new Form();

            dialogo.Width = 300;
            dialogo.Height = 300;

            Button btnSim = new Button() { Text = "Sim", Left = 30, Width = 100 };
            Button btnNao = new Button() { Text = "Não", Left = 150, Width = 100 };

            dialogo.Controls.Add(btnSim);
            dialogo.Controls.Add(btnNao);
            dialogo.ShowDialog();

            // the following two lines are the problematic ones
            btnSim += new EventHandler(btnSim_Click);
            btnNao += new EventHandler(btnNao_Click);

            return -1;
        }
}

It's underlining the text within parenthesis and the message says:

The name btnSim_Click' does not exist in the current context

The problem is that I tried to add the following in my code but it doesn't let me put it anywhere (it always says that is something wrong):

private int btnNao_Click (object sender, EventArgs e)
{
    return 0;
}

private int btnSim_Click (object sender, EventArgs e)
{
    return 1;
}

My objective is that each of the both buttons btnSim and btnNao return a different value (say 1 and 0).

What am I doing wrong?

标签: c#event-handling

解决方案


EventHandler is a delegate for a method that returns void. Your methods return int.

Try something like this:

 public static int show()
    {
        int returnValue = -1;

        using (Form dialogo = new Form())
        {
            dialogo.Width = 300;
            dialogo.Height = 300;

            Button btnSim = new Button() { Text = "Sim", Left = 30, Width = 100 };
            Button btnNao = new Button() { Text = "Não", Left = 150, Width = 100 };

            dialogo.Controls.Add(btnSim);
            dialogo.Controls.Add(btnNao);

            btnSim.Click += (s, e) => { returnValue = 0; dialogo.DialogResult = DialogResult.OK; };
            btnNao.Click += (s, e) => { returnValue = 1; dialogo.DialogResult = DialogResult.OK; };
            dialogo.Disposed += (s, e) =>
            {
                btnSim?.Dispose();
                btnSim = null;

                btnNao?.Dispose();
                btnNao = null;
            };

            dialogo.ShowDialog();
        }

        return returnValue;
    }

推荐阅读