Mr.AwfulAtProgramming Mr.AwfulAtProgramming - 2 months ago 24
C# Question

How to create click event handler for a dynamic 2D array of buttons in C#

I'm currently making a bingo game for my C# class and cant figure out how to dynamically generate a click event handler for my card. Here is the code that creates the buttons. Any help would be greatly appreciated.

public void generateButtonsCard(Panel cardPanel)
{
for (int y = 0; y <= 4; y++)
{
for (int x = 0; x <= 4; x++)
{
cardButtons[x, y] = new Button();
cardButtons[x, y].Size = new Size(80, 80);
cardButtons[x, y].Name = "btn" + x + "" + y;
cardButtons[x, y].Location = new Point(80 * x, 80 * y);
cardPanel.Controls.Add(cardButtons[x, y]);

}

}

RNGCard();
cardButtons[2, 2].Text = "Free Space";

}

Answer

So you can create a single button click event handler, and inside that handler you can switch your logic based on which button was clicked. Here is an example of how to do it:

public class XYButton : Button
{
    private int xPos;
    private int yPos;

    public XYButton(int x, int y)
    {
        xPos = x;
        yPos = y;
    }

    public int GetX()
    {
        return xPos;
    }

    public int GetY()
    {
        return yPos;
    }
}

Then using this new extension of button...

public void generateButtonsCard(Panel cardPanel)
{
    for (int y = 0; y <= 4; y++)
    {
        for (int x = 0; x <= 4; x++)
        {
            cardButtons[x, y] = new XYButton(x,y);
            cardButtons[x, y].Size = new Size(80, 80);
            cardButtons[x, y].Name = "btn" + x + "" + y;
            cardButtons[x, y].Location = new Point(80 * x, 80 * y);
            cardButtons[x, y].Click += btn_Click;
            cardPanel.Controls.Add(cardButtons[x, y]);

        }

    }

    RNGCard();
    cardButtons[2, 2].Text = "Free Space";

}

private void btn_Click(object sender, EventArgs e){
   var xyButton = sender as XYButton;
   // now you can get the x and y position from xyButton.
}
Comments