I've written a Minesweeper program, but my code for generating the buttons is taking much longer than I'd like. Here is the GUI code:
this.boardPanel.Controls.Clear();
this.boardValues = new int[mode.size.Width, mode.size.Height];
this.boardFound = new bool[mode.size.Width, mode.size.Height];
this.boardButtons = new Button[mode.size.Width, mode.size.Height];
EventHandler click = new EventHandler(btn_Click);
for (int x = 0; x < boardButtons.GetLength(0); x++)
{
for (int y = 0; y < boardButtons.GetLength(1); y++)
{
boardButtons[x, y] = new Button();
boardButtons[x, y].Size = new Size(Minesweeper.BUTTON_LENGTH, Minesweeper.BUTTON_LENGTH);
boardButtons[x, y].Location = new Point(x * Minesweeper.BUTTON_LENGTH, y * Minesweeper.BUTTON_LENGTH);
boardButtons[x, y].Tag = new Point(x, y);
boardButtons[x, y].Click += click;
this.boardPanel.Controls.Add(boardButtons[x, y]);
}
}
this.boardPanel.Size = new Size(mode.size.Width * Minesweeper.BUTTON_LENGTH, mode.size.Height * Minesweeper.BUTTON_LENGTH);
this.Size = new Size(5 + this.boardPanel.Width + 5 + 8, this.tstMain.Height + 5 + this.boardPanel.Height + 5 + this.stsStatus.Height + 30);
As you can see I am creating an EventHandler for a method called btn_Click
, outside of the loop, and assigning it to each button. This method reads the Tag
field of the clicked button to determine which button as pressed.
In an Intermediate game with a board size of 16x16, generating the buttons takes approximately 2-3 seconds. I know WinForm controls aren't known for the best performance, but is there a way I can generate a number of buttons, assign Event handlers and add them to a panel more efficiently?