更新TableLayoutPanel中的PictureBox

时间:2013-11-26 19:13:09

标签: c# winforms tablelayoutpanel

我正在编写一个通过网络玩国际象棋的应用程序。但是我遇到了一个小问题。

TableLayoutPanels cells;
cells = GetBoard();
this.Controls.Add(cells);

 private TableLayoutPanel GetBoard()
    {
        TableLayoutPanel b = new TableLayoutPanel();
        b.ColumnCount = 8;
        b.RowCount = 8;
        for (int i = 0; i < b.ColumnCount; i++) { b.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, Cell.CellSize.Width)); }
        for (int i = 0; i < b.RowCount; i++) { b.RowStyles.Add(new RowStyle(SizeType.Absolute, Cell.CellSize.Height)); }
        for (int row = 0; row < b.RowCount; row++)
        {
            for (int col = 0; col < b.ColumnCount; col++)
            {
                Cell cell = new Cell(row, col);
                cell.Click += new EventHandler(this.cell_Click); //Added an event handler
                b.Controls.Add(cell, col, row);
            }
        }
        b.Padding = new Padding(0);
        b.Size = new System.Drawing.Size(b.ColumnCount * Cell.CellSize.Width, b.RowCount * Cell.CellSize.Height);

        return b; //Returns the whole table
    }

GetBoard初始化一个8×8的PictureBoxes板。我有一个鼠标事件处理程序,当用户单击其中两个时,切换PictureBox的图像。

private void cell_Click(object sender, EventArgs e)
{
   Cell currentClickedCell = (Cell) sender; 
   currentClickedCell.Image = prevClickedCell.Image; //Switch the two images
   prevClickedCell = null; //Set the previously clicked cell's image to blank
}

然后通过网络(通过使用switch语句强制转换为枚举)在网络上发送信息。

但是,一旦我收到服务器的响应(两个整数),我不知道如何更新信息。我会尽我所能说出这句话:“有没有办法让两个单元格的”对象发送者“”切换图像?

1 个答案:

答案 0 :(得分:0)

此代码将“交换”当前图像与最后一张图像:

private void cell_Click(object sender, EventArgs e) {
  Cell currentClickedCell = (Cell)sender;
  if (prevClickedCell != null) {
    Image img = currentClickedCell.Image;
    currentClickedCell.Image = prevClickedCell.Image;
    prevClickedCell.Image = img;
  }
  prevClickedCell = currentClickedCell;
}