C# Create Dynamic Buttons and onClick Dynamic EventHandlers

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

My program creates buttons dynamically.

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; }

What I am trying to do is when the user clicks on the button(s) it adds the name of the button into the multiline TextBox such as in the picture above. I created an EventHandler but cant figure it out how to make it work with dynamic buttons.

回答1:

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;     }


回答2:

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]);      } }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!