如何为flowlayoutpanel中动态创建的按钮生成点击事件? [英] How to generate click events for buttons created dynamically in a flowlayoutpanel?

查看:401
本文介绍了如何为flowlayoutpanel中动态创建的按钮生成点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FlowLayoutPanel fp = new FlowLayoutPanel();
           fp.Size = new Size(180, 150);
           fp.Location = new Point(100, 140);
           fp.BackColor = Color.Aqua;

           this.Controls.Add(fp);
           for (int i = 0; i < 9; i++)
           {
               Button b1 = new Button();
               b1.Text = i.ToString();
               b1.Size = new Size(50, 40);
               fp.Controls.Add(b1);





我的尝试:



b1.Click + = new EventHandler(b1_click);



What I have tried:

b1.Click+=new EventHandler(b1_click);

推荐答案

您显示的代码将用于添加事件处理程序 - 尽管可能您可以使用更简单的语法:

The code you show will work to add the event handler - though it may be that you can use the simpler syntax:
    Button b1 = new Button();
    b1.Text = i.ToString();
    b1.Size = new Size(50, 40);
    b1.Click += numberButton_Click;
    fp.Controls.Add(b1);
...
void numberButton_Click(object sender, EventArgs e)
    {
    ...
    }

取决于您使用的C#版本。

这将导致所有按钮共享一个事件处理程序,因此可能值得将Tag属性设置为 i ,而不是依赖Text属性以便稍后识别它们。 (这样你以后可以使用漂亮的图像让你的计算器看起来更好而你的代码不需要改变)。

然后在你的处理程序方法中直接使用Tag:

Depending on the version of C# you are using.
That will cause all the buttons to share an event handler, so it's probably worth setting the Tag property to i rather than relying on the Text property to identify them later. (That way you could use pretty images later to make your calculator look better and your code doesn't need to change).
Then in your handler method use the Tag directly:

void numberButton_Click(object sender, EventArgs e)
    {
    Button b = sender as Button;
    if (b != null)
        {
        int key = (int)b.Tag;
        // ...
        }
    }



但是,我建议您更改循环终止条件:除非您的用户对'9'有所帮助! :笑:

这可能会更好:


However, I would suggest that you change the loop termination condition: unless your users have something against '9's! :laugh:
This would probably be better:

for (int i = 0; i <= 9; i++)



如果您想强制点击按钮,就好像用户按下了它(我不认为你这样做)然后使用Button.PerformClick方法。


If you want to force a click on the button as if the user had pressed it (and I don't think you do) then use the Button.PerformClick method.


这篇关于如何为flowlayoutpanel中动态创建的按钮生成点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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