2个动态按钮,1个事件处理程序。如何确定谁点击了这个活动?

时间:2017-06-27 09:19:24

标签: c# winforms button dynamic

我正在尝试从我的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语句,它可以调用事件处理程序。

2 个答案:

答案 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;

More details

二:

if (sender == "btn1")
{
    MessageBox.Show("btn1");          
}

您正在将Button对象与string进行比较。您要做的是首先检查您的senderButton,然后检查Name属性。

Button btn = sender as Button;
if(btn != null)
{
    if (btn.Name == "btn1")
    {
        MessageBox.Show("btn1");
    }
}