c# - 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?
解决方案
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;
}
推荐阅读
- python-3.x - 使用 boto3 创建到 mysql 的胶水连接
- uproot - JaggedArray 可以计算最内层并返回另一个 JaggeredArray 吗?
- javascript - 使用 url 下载 s3 存储桶对象
- php - Laravel 6 - SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;
- xml - 在定义的字符串之后查找特定字符串
- python - 如何堆叠for循环的每次迭代的输出?
- windows - 在不重新启动 Windows 的情况下更新 KMDF 驱动程序
- php - 在 php 中收到 FormData 时导致错误
- raspberry-pi - 如何在树莓派上卸载motioneye?
- firebase - Crashlytics - Firebase 日志中的 Stacktrace 不可读