如何将预先存在的面板分配给面板[0,0]等数组?

时间:2013-09-11 12:51:11

标签: c# controls

我试图在c#中创建一个国际象棋战略应用程序。我已将面板放在表单设计器中,它们被命名为panel1,panel2,ect ....我需要知道如何将面板分配给2D数组,如'chessBoardPanels [0,0]'这将允许我用以下命令实际控制面板的背景:

chessBoardPanels[0,0].Background=Color.Black;

但它说我需要某种对象引用。

3 个答案:

答案 0 :(得分:2)

我宁愿选择这样的东西

        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);
            }

这样您就可以动态创建面板,而无需在设计器中创建它们。

但是,您必须处理公式以处理间距。

修改

我还添加了一个如何空间/设置面板块的示例。

答案 1 :(得分:1)

创建此类2D数组的语法如下:

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;
//...

答案 2 :(得分:0)

我在我的循环中保留了一个bool,用于创建我的板以确定是使用黑色还是白色作为背景颜色。在设置每个字段之前,您必须启动数组(通常是二维数组):

        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;
        }