How to retrieve the click on an array of buttons

Asked

Viewed 287 times

1

I’m making a minefield, so I have to add an array of buttons to a panel (to be the houses). I created the button array and added each[x][y] button in a panel. But I don’t know how to retrieve the click on a certain [x][y] button inside my matrix. I know only generate the event for a button, I do not know how I can "generalize" to others, for example, when the button[2][3], inside my matrix is clickado I receive a "button[2][3] was clickado" or "the clickadas positions were x = 2, y =3". I know it sounds like an obvious question, but it’s just that I started today in C#. Thank you.

  • There’s more than one way to solve this problem. I think it’s easier to answer your question if you give an example of the code you tried to use (try to do something simplified that only prints a message on the screen)

1 answer

1


You can use a single event generated for all buttons and within that event you check who fired it, something like this:

private void botoes_Click(object sender, EventArgs e)
{
    Console.WriteLine(((Button)sender).Name); // imprime no Console o nome do botão clicado
}

In that case the sender will reference the component that held the event Click, if you need any specific information, you can place it on the property Tag of each button and then access it like this ((Button)sender).Tag

Browser other questions tagged

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