How to create events in a for loop structure?

2

My question is the following, 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);
        }
    }
}

It 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, will you help me? Thanks!

    
asked by anonymous 06.10.2017 / 00:38

2 answers

5

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

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 declaration of the variable must be within 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);
    }
}
    
06.10.2017 / 01:05
0

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

btn[i].Click += new btnNum_Click;
    
06.10.2017 / 00:54