C# Create Dynamic Buttons and onClick Dynamic EventHandlers

后端 未结 2 2065
不知归路
不知归路 2020-12-04 01:14

My program creates buttons dynamically.

private void CreateButton(string buttonName)
{

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


        
相关标签:
2条回答
  • 2020-12-04 01:27

    use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 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]);
    
        }
    }
    
    0 讨论(0)
  • 2020-12-04 01:34

    You have a reference to the button that was clicked right there as the sender argument. So...

    private void transbutton_Click(object sender, EventArgs e)
        {
           tbList.Text += "\r\n" + ((Button)sender).Text;
        }
    
    0 讨论(0)
提交回复
热议问题