How to create events in a for replay structure?

My doubt is as follows, I'm developing a program (I'm a beginner) in C#. The part I wanted to improve, is this: I'm wanting to create different events in a for structure. For example:

public frmSelecaoDeCartas()
{
    InitializeComponent();

    // Declara arrays contendo os Botões
    Button[] btn = { button2, button3, button4 };

    // Inicia uma estrutura de repetição para gerar os eventos
    for (int i = 0; i < btn.Length; i++)
    {
        // Cria o evento do Button de índice I com o nome de btnNum (Num = 0 a 4)
        btn[i].Click += btnNum_Click;

        // Evento com o código (Problema nessa parte, quero trocar a palavra Num por
        // números de acordo com a mudança da índice i (i++)
        void btnNum_Click(object sender, EventArgs e)
        {
            MessageBox.Show(CartasInformacao[i], "Informações",
                             MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

Would look like this:

btn[i].Click += btnNum_Click;

void btn1_Click(object sender, EventArgs e) { }
void btn2_Click(object sender, EventArgs e) { }
// E assim vai... 

Is this possible? If so, help me? Grateful!

Author: novic, 2017-10-05

2 answers

The problem is that when creating a delegate the captured variable i is the control variable of the for, which will be incremented with each iteration. However, the same i will be referenced by all events... that is, with each increment of for all references will see i incrementing.

If you make a copy of the variable, for another variable, before creating the delegate, it will be created with a reference to the copied variable. The variable declaration must be inside the for as in the example below:

// Inicia uma estrutura de repetição para gerar os eventos
for (int i = 0; i < btn.Length; i++)
{
    var copia_de_i = i;

    // Cria o evento do Button de índice I com o nome de btnNum (Num = 0 a 4)
    btn[i].Click += btnNum_Click;

    // Evento com o código (Problema nessa parte, quero trocar a palavra Num por
    // números de acordo com a mudança da índice i (i++)
    void btnNum_Click(object sender, EventArgs e)
    {
        MessageBox.Show(CartasInformacao[copia_de_i], "Informações", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
 6
Author: Miguel Angelo, 2017-10-05 23:10:22

It is possible yes! Considering the code that has already ready I would change only one thing: I would add new before associating the event.

btn[i].Click += new btnNum_Click;
 0
Author: Caiuby Freitas, 2017-10-05 23:03:46