It turns out that I am starting to program in C#, well, my problem is that I have a Button array and when I initialize the buttons I add a method to them in the Click event, I would like to know if parameters can be passed to the event method.
I have the initialization of my matrix like this:
for(int x = 0; x < celdas.GetLength(0); x++)
{
for (int i = 0; i < celdas.GetLength(1); i++)
{
celdas[x, i] = new Celda();
celdas[x, i].SetBounds(i * anchoCelda, x * altoCelda, anchoCelda, altoCelda);
celdas[x, i].UseVisualStyleBackColor = true;
celdas[x, i].Click += evento;
this.panelMatriz.Controls.Add(celdas[x, i]);
}
}
in the 'Event' method I want to use the row and column of the button. but I see a way to send them to the method.
public void evento(object sender, EventArgs e)
{
Celda celda = ((Celda)sender);
MessageBox.Show(celda.Destapada+"");
}
an example, that when pressing the button that shows me the row and the column where it is located.
In principle, arguments cannot be added to the handler of an event
Click
, basically because you are not the one raising the event, so in no case could you send any argument to it. If it was a custom event, there would be no problem.That said, there is actually a way, but I'll show you later after looking at other possibilities.
One method used in the past was to use the property
Tag
that all controls have. This property accepts anyobject
,so it can be used to store information on the button itself (I'm going to use your example of passing the button's row and column):This way, in your event handler you could just get the data from the
Tag
:Another possibility is that the button name contained the data you want to pass. For example,
celdas[x, i].Name= string.Format("Boton{0}{1}",x,i);
Now we go to a way to actually be able to pass arguments to the event in a very comfortable way:
This way your arguments are added to the event, you just have to modify the handler like this: