Create click event for multiple C#buttons

Asked

Viewed 25 times

1

I make a class to generate buttons like this:

public Button GerarBotao(string Text, string Name)
{
    Button button = new Button();
    button.Text = Text;
    button.Name = Name;
    button.Dock = DockStyle.Top;
    button.Size = new System.Drawing.Size(100, 50);
    return button;
}

Now in a Form (Windowns Forms) I call the method to create buttons

for (int i = 1; i <= count; i++)
{                  
  string nomeBotão = "vaga" + i;
  string texto = "V-" + i + " LIVRE";
  p_botoes.Controls.Add(gerarBotoesVagas.GerarBotao(texto, nomeBotão));
}

The count is the number of buttons it will generate.

Now I’m stuck because I don’t know how to do to generate the click action of the generated buttons. In case the click would lead to another Form, only with the button information it would be the nomeBotao.

1 answer

1


A method needs to be created with the following signature:

private void Button_Click(object sender, EventArgs e)
{
    Button clicado = (Button)sender;
    MessageBox.Show(clicado.Text);
}

and at the time of creation of the buttons put this method in the Eventhandler Click:

public Button GerarBotao(string Text, string Name)
{
    Button button = new Button();
    button.Text = Text;
    button.Name = Name;
    button.Dock = DockStyle.Top;
    button.Size = new System.Drawing.Size(100, 50);
    button.Click += Button_Click; // adicionando o evento ...
    return button;
}

By clicking the event button Button_Click is triggered and appropriate conditions must be made for these buttons created at runtime.

Observing: in your code have variables with accentuation and this is not a good practice.

  • 1

    Thank you. It worked perfectly :)

Browser other questions tagged

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