C#中如何处理多动态创建的按钮事件 [英] c# how to deal with events for multi dynamic created buttons

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

问题描述

我创建了一个WinForm的,我加入到它的动态按钮,我该怎么处理这事件。

I have created a WinForm and I added to it dynamic Buttons, how I can deal with it's events

public static void Notify()
{

    var line = 3;

    Form fm = new Form();
    fm.Text = "Hello!";
    fm.ShowInTaskbar = false;
    fm.ShowIcon = false;
    fm.MinimizeBox = false;
    fm.MaximizeBox = false;
    fm.FormBorderStyle = FormBorderStyle.FixedToolWindow;
    fm.TopMost = true;
    fm.ClientSize = new Size(150, 75 * line/2);
    Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
    int left = workingArea.Width - fm.Width-5;
    int top = workingArea.Height - fm.Height-4;
    fm.Location = new Point(left, top);
    fm.StartPosition = FormStartPosition.Manual;

    var buttomArray = new Button[line];

    for (int i = 0; i < line; i++)
    {
        buttomArray[i] = new Button();
        buttomArray[i].Text = "Button " + (i + 1);
        buttomArray[i].Location = new Point(10,30*(i+1) - 16);
        buttomArray[i].Size = new Size(130,25);
        fm.Controls.AddRange(new Control[] { buttomArray[i] });
    }

    fm.Show();
}

我希望能够做一些不同的事情,当我在不同的按钮点击(也许我可以用名作为标识?)

I want to be able to do some different things when I click on different Button (maybe I can use the "name" as an identifier?)

欢呼声

推荐答案

只要指定的点击处理程序:

for (int i = 0; i < 10; i++)
{
    var btn = new Button();
    btn.Text = "Button " + i;
    btn.Location = new Point(10, 30 * (i + 1) - 16);
    btn.Click += (sender, args) =>
    {
        // sender is the instance of the button that was clicked
        MessageBox.Show(((Button)sender).Text + " was clicked");
    };
    Controls.Add(btn);
}

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

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