我正在尝试从我的2个动态按钮中确定单击事件处理程序。
如何在Form load
创建2个动态按钮private void Form1_Load(object sender, EventArgs e)
{
for (int q = 0; q < 2; q++)
{
Point newLoc = new Point(a, b);
for (int i = 0; i <= 3 - 1; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(95, 80);
buttonArray[i].Name = "btn" + q;
buttonArray[i].Text = "btn" + q;
buttonArray[i].Click += newButton;
buttonArray[i].Location = newLoc;
a = a + 10;
if (a > 300)
{
b = b + 100;
a = 1;
}
this.Controls.Add(buttonArray[i]);
}
}
}
我正试图打电话的事件
void newButton(object sender, EventArgs e)
{
if (sender == "btn1")
{
MessageBox.Show("btn1");
}
if (sender == "btn2")
{
MessageBox.Show("btn2");
}
}
如果我不添加IF语句,它可以调用事件处理程序。
答案 0 :(得分:2)
您需要将object sender
转换为Button
,然后针对Name
属性进行测试:
void newButton(object sender, EventArgs e)
{
Button btn = sender as Button;
// btn could be null if the event handler would be
// also triggered by other controls e.g. a label
if(btn != null)
{
if (btn.Name == "btn1")
{
MessageBox.Show("btn1");
}
if (btn.Name == "btn2")
{
MessageBox.Show("btn2");
}
}
}
在C#7.0中,您可以简化该调用:
void newButton(object sender, EventArgs e)
{
if(sender is Button btn)
{
if (btn.Name == "btn1")
{
MessageBox.Show("btn1");
}
if (btn.Name == "btn2")
{
MessageBox.Show("btn2");
}
}
}
答案 1 :(得分:0)
你有两个问题 一:
buttonArray[i].Name = "btn" + q;
buttonArray[i].Text = "btn" + q;
您应该为每个按钮创建并传递新值:
int temp = q;
buttonArray[i].Name = "btn" + temp;
buttonArray[i].Text = "btn" + temp;
二:
if (sender == "btn1")
{
MessageBox.Show("btn1");
}
您正在将Button
对象与string
进行比较。您要做的是首先检查您的sender
是Button
,然后检查Name
属性。
Button btn = sender as Button;
if(btn != null)
{
if (btn.Name == "btn1")
{
MessageBox.Show("btn1");
}
}