c# how to deal with events for multi dynamic created buttons

好久不见. 提交于 2019-12-12 05:38:15

问题


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?)

cheers


回答1:


Simply assign the Click handler:

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



回答2:


Subscribe to the Button.Click event. Attach the data you want to use in the click-handler to the Tag-property while your are in the creation loop.

for (int i = 0; i < line; i++) 
    { 
        buttomArray[i] = new Button(); 
        buttomArray[i].Tag=i;
    .....

In the click handler, the sender will be the Button (you can cast to it) and the tag will contain your value.

Button btn=(Button)sender;
int value=(int)btn.Tag;

The Tag-property accepts any type. Therefore you can attach any value to it.



来源:https://stackoverflow.com/questions/3645643/c-sharp-how-to-deal-with-events-for-multi-dynamic-created-buttons

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