C#创建动态按钮和onClick动态EventHandlers [英] C# Create Dynamic Buttons and onClick Dynamic EventHandlers

查看:197
本文介绍了C#创建动态按钮和onClick动态EventHandlers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序动态创建按钮。

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

我要做的是,当用户单击按钮时,它会添加名称按钮进入多行文本框,如上图所示。我创建了一个EventHandler,但无法弄清楚如何使其与动态按钮一起使用。

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.

推荐答案

您对按钮有引用在该处单击 sender 作为参数。所以...

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

这篇关于C#创建动态按钮和onClick动态EventHandlers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆