Reputation: 25
Im trying to create a chess strategy application in c#. I have placed the panels in the form designer where they have been named panel1, panel2, ect.... I am needing to know how I can assign the panels to a 2D Array like 'chessBoardPanels[0,0]' this would allow me to actually control the backgrounds of the panels with a command like:
chessBoardPanels[0,0].Background=Color.Black;
But it says I need a some sort of object reference.
Upvotes: 1
Views: 963
Reputation: 166476
I would rather go for something like this
int numBlocks = 8;
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
for (int iRow = 0; iRow < numBlocks; iRow++)
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(50, 50);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(50 * iRow, 50 * iColumn);
chessBoardPanels[iRow, iColumn] = p;
this.Controls.Add(p);
}
This would allow you to create the Panels on the fly, without having to create them in the designer.
You will however have to work on a formula to handle the spacing for you.
EDIT
I have also added an example of how to space/set the panel blocks.
Upvotes: 2
Reputation: 5126
I kept a bool in my loop for the creation of my board to determine whether to use black or white as the background color. Before setting each field you must initiate the array (usually a two-dimensional one):
this.Fields = new PieceButton[Board.Size, Board.Size];
board = new Board(this);
for (int i = 0; i < Board.Size; i++)
{
for (int j = 0; j < Board.Size; j++)
{
this.Fields[i, j] = new PieceButton(even ? white : black, i, j);
this.Fields[i, j].Size = fieldSize;
this.Fields[i, j].Location = new Point(
i * PieceSize + widthOffset,
(Board.Size - j - 1) * PieceSize + heightOffset);
Fields[i, j].MouseDown += this.Piece_MouseDown;
this.Controls.Add(Fields[i, j]);
even = !even;
}
even = !even;
}
Upvotes: 0
Reputation: 66388
The syntax for creating such 2D array would be:
Panel[,] chessBoardPanels = new Panel[8, 8];
chessBoardPanels[0, 0] = panel1;
chessBoardPanels[0, 1] = panel2;
chessBoardPanels[0, 2] = panel3;
//...
chessBoardPanels[0, 7] = panel8;
chessBoardPanels[1, 0] = panel9;
//...
Upvotes: 1