How to create events in a for repeat structure?

Asked

Viewed 178 times

2

My question is the following, I am developing a program (I am beginner) in C#. The part I wanted to improve on is the following: 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 that possible? If yes, help me? Thank you!

  • Instead of posting a print of your code, post the code in full, so it looks better to analyze it.

  • But that’s the code, the rest is just logic and code of the program itself... Nothing to do with the code I printed, and what I printed shows all my doubts. But here’s a bigger print: http://prntscr.com/gtt3as

  • @Lucasnaja but putting the code snippet here makes it easier for us to help you, even easier to copy and paste to text

  • When you add to one button it works?

  • Yeah, thanks for the tip. The code goes: https://pastebin.com/v382kTPF Currently there are 3 buttons, when I run the code, the three are with the same code, because they are in the same event (btn_Click) For example, I click the button 2 and the same message appears by clicking the button 3 I wanted to create an event for each button using the for, not the same event for each button

2 answers

6


The problem is that when creating a delegate the captured variable i is the control variable of for, that will be incremented at each iteration. However, the same i will be referenced by all events... ie at each increment of the 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 variable declaration has to be within 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);
    }
}
  • Thank you very much! Problem solved, I am very grateful for the quick and efficient answers! Everyone helped a lot :) Caraca, look at the gods mano! Thanks again, you’re fucked! <3

  • @Lucasnaja: if you think it’s right, accept this answer. This has 2 objectives, reward me, and also mark the question as being answered. Not at all, friend!!! And thanks for the words. = D

  • Damn snapshots of context...

0

It is possible yes! 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;
  • Hello, this example seems to me to be correct! But when I do this, the following appears: http://prntscr.com/gtt8i0 Then I modify it to this: http://prntscr.com/gtt8mr But then when you click on the buttons, the 3 still have the same code.. I’m making the btn[i] code wrong. Click += new btnNum_Click;? Something is missing?

  • That’s right. When you associate the same event to the buttons, clicking it will trigger the same event. What you can do is create different streams within the event as the button that was clicked: switch ((Sender as Button).Name) { case "button1": //actions break; case "button2": //actions break; default: break; }

Browser other questions tagged

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