C#创建动态按钮和onClick动态EventHandlers

时间:2013-05-02 20:24:33

标签: c# winforms visual-studio-2010

我的程序动态创建按钮。

private void CreateButton(string buttonName)
{

   Color[] c = { Color.Red, Color.Teal, Color.Blue, Color.WhiteSmoke };

   transbutton = new Button();
   transbutton.BackColor = c[2];
   transbutton.Text = buttonName;
   transbutton.Name = buttonName + "Button";
   transbutton.Width = 150;
   transbutton.Height = 150;
   transbutton.Font = new Font("Segoe UI", 13);
   transbutton.ForeColor = Color.White;

   transbutton.Click += new EventHandler(transbutton_Click);
}

private void transbutton_Click(object sender, EventArgs e)
{

   tbList.Text = transbutton.Text;
}

enter image description here

我想要做的是当用户点击按钮时,它会将按钮的名称添加到多行TextBox中,如上图所示。我创建了一个EventHandler,但无法弄清楚如何使它与动态按钮一起使用。

2 个答案:

答案 0 :(得分:6)

您可以在此处单击作为sender参数单击的按钮。所以......

private void transbutton_Click(object sender, EventArgs e)
    {
       tbList.Text += "\r\n" + ((Button)sender).Text;
    }

答案 1 :(得分:0)

使用像这样的按钮数组。它将创建3个动态按钮bcoz h变量的值为3

public void button_Click(object sender, EventArgs e)
{
 if( sender == buttonArray[0] )
  {


  MessageBox.Show("hello");
   }

 }

private void button1_Click(object sender, EventArgs e)
{

    int h =3;


    Button[] buttonArray = new Button[8];

    for (int i = 0; i <= h-1; i++)
    {
       buttonArray[i] = new Button();
       buttonArray[i].Size = new Size(20, 43);
       buttonArray[i].Name= ""+i+"";
       buttonArray[i].Click += button_Click;//function
       buttonArray[i].Location = new Point(40, 20 + (i * 20));
        panel1.Controls.Add(buttonArray[i]);

    }
}