我有一组动态添加的按钮。当用户不断点击按钮时,新的按钮被添加到窗口中。我正在使用winforms。我将所有这些按钮的onclick事件绑定到同一个函数。我使用以下代码。
System.EventHandler myEventHandle= new System.EventHandler(this.Button_Clicked);
创建新的动态按钮后,我使用以下代码添加事件处理程序:
b1.Click += myEventHandle;
现在在函数Button_Clicked()中我想获取调用此事件的Button。我想要禁用此按钮,以便它不能再次单击,我想要点击按钮的名称,因为我想根据按钮名称执行各种操作。我是C#的新手。
这是我到目前为止所尝试过的,但似乎不起作用:
Button b = sender as System.Windows.Forms.Button;
b.Font = new Font(b.Font, FontStyle.Bold);
Console.WriteLine(""+b.Name);
b.Enabled = false;
答案 0 :(得分:3)
使用活动的发件人
if(sender is Button)
{
Button b = sender as Button;
b.Enabled = false;
///something = b.Name;
}
答案 1 :(得分:2)
嗯,您的Button_Clicked
方法必须看起来像
void Button_Clicked(object sender, EventArgs e) {
Button clickedButton = (Button)sender;//if sender is always a Button
clickedButton.Enabled = false;
}