How to sync multiple buttons to an event?

Asked

Viewed 105 times

2

Good evening, my teacher of programming language asked us to make a program, that when calling the event Form1_load generate 200 buttons, until then I did, but I wanted to implement a function that click on a button, regardless of which it changed color. But without having to add the 200 buttons in the code, follow the code:

public partial class Form1 : Form
{
    Button[] btn = new Button[200];
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        char letra = 'A';
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 20; j++)
            {
                btn[i] = new Button();
                btn[i].Name = letra.ToString() + j + 1;
                btn[i].Text = letra.ToString() + (j + 1);
                btn[i].BackColor = Color.Green;
                btn[i].Location = new Point(90 * (i + 1), 30 * (j + 1));
                Controls.Add(btn[i]);
            }
            letra++;
        }
    }
}

1 answer

2


Your code is correct, what is missing is to specify an event that at the time of the Click, can change component color, example:

private void Form1_Load(object sender, EventArgs e)
{
    char letra = 'A';
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 20; j++)
        {
            btn[i] = new Button();
            btn[i].Name = letra.ToString() + j + 1;
            btn[i].Text = letra.ToString() + (j + 1);
            btn[i].BackColor = Color.Green;
            btn[i].Location = new Point(90 * (i + 1), 30 * (j + 1));
            btn[i].Click += Button_Click;
            Controls.Add(btn[i]);
        }
        letra++;
    }
}

private void Button_Click(object sender, EventArgs e)
{
    ((Button)sender).BackColor = Color.Red;
}

that is, on the added line btn[i].Click += Button_Click; the event was created. At the same time object sender means that the moment you click on the button is passed to that variable the button that has now been clicked just give a cast and use BackColor and change the color, in this example changes to red.

  • 1

    Thanks bro, you helped a lot !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.