How to add parameters to the EventHandler method that is added to the Click event in C #?

2

It turns out that I'm starting to program in C #, well, my problem is that I have a Button matrix and when I initialize the buttons I add a method in the Click event, I would like to know if parameters can be passed to the method of the event.

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 the 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 by pressing the button that shows me the row and the column where it is.

    
asked by Alexis Rodriguez 15.09.2017 в 23:03
source

1 answer

3

In principle, you can not add arguments to the handler of a Click event, basically because you are not the one that raises the event, so in no case could you send it any argument. If it were a personalized event, there would be no problem.

That said, actually there is a way, but I'll show you later after analyzing other possibilities.

A method that was used in the past was to use the Tag property that all the controls have. This property supports any object , which can be used to store information on the button itself (I will use your example of passing the row and column of the button):

celdas[x, i] = new Celda();
celdas[x, i].Tag=string.Format("{0},{1}",x,i);
...

In this way, in your event handler you could simply get the data of Tag :

Celda celda = ((Celda)sender);
string[] datos=celda.Tag.ToString().Split(',');
int fila=int.Parse(datos[0]);
int columna=int.Parse(datos[1]);

Another possibility is that the name of the button contains the data you want to pass. For example, celdas[x, i].Name= string.Format("Boton{0}{1}",x,i);

Now we are going to a way to really be able to pass arguments to the event in a very comfortable way:

celdas[x, i].Click += (sendr, EventArgs) => { evento(sendr, EventArgs, x,i); };

In this way your arguments are added to the event, you just have to modify the manager like this:

public void evento(object sender, EventArgs e,int fila, int columna)
{
    Celda celda = ((Celda)sender);
    MessageBox.Show(celda.Destapada+"");
}
    
answered by 16.09.2017 / 02:15
source