我使用的是以下代码:
foreach (Control c in this.Controls)
{
Button btn = c as Button;
{
if (c == null)
continue;
c.Click += handle_click;
}
void handle_click(object sender, EventArgs e)
{
Form1 ss = new Form1();
ss.label1.Text = (sender as Button).Text;
ss.ShowDialog();
}
但是代码影响了我所有的Form元素。举例说明我所有的按钮。如何为一个按钮创建异常?我通过创建一个面板并将按钮放在里面来管理它,但当我点击面板时,我会收到以下错误消息:
"NullReferenceExeption未处理"对象引用未设置为对象的实例"
为什么会发生这种情况?
这里有一个问题:
Button btn = c as Button;
{
if (c == null) <-- should be if(btn == null)
continue;
因此,您将事件处理程序分配给每个控件,而不仅仅是按钮。然后,当您尝试在事件处理程序中将发送方强制转换为Button
时,您会得到一个null值。
您还可以在事件处理程序中支持您的事件处理:
void handle_click(object sender, EventArgs e)
{
var button = (sender as Button);
if(button == null)
{
//throw an exception? Show an error message? Ignore silently?
}
Form1 ss = new Form1();
ss.label1.Text = button.Text;
ss.ShowDialog();
}