C# 创建动态按钮和 onClick 动态事件处理程序

标签 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

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

最佳答案

作为 sender 参数,您有一个对被点击按钮的引用。所以……

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

关于C# 创建动态按钮和 onClick 动态事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16347072/

相关文章:

c# - 代码未运行,因为另一个线程正在访问它

vb.net - 什么都没有和 system.DBNull 的区别

visual-studio-2010 - VS 2010,编码的 UI 测试 : Re-run failed test cases

c# - XML、LINQ 和 XDocument.Save 问题

c# - 你如何编辑一个用户,谁的电子邮件用户名包含一个连字符?

c# - XNA 绘制并创建对象数组

.net - XWindows终端仿真作为.NET Winform组件

c# - 为什么在路径中找不到异常 SignTool.exe?

visual-studio-2010 - 从 VS2010 安装程序安装快捷方式

c - 为链表节点中的字符串动态分配内存