在按钮上显示二维值数组的最简单方法



我正在寻找在按钮上显示二维值数组的最佳化代码。我创建了这样的按钮网格:http://screenshot.sh/m2eZscO4i0fXq我实际上使用以下代码在此按钮上显示数组的值:

button1.Text = board.gameBoard[0, 0].getValue().ToString();
button2.Text = board.gameBoard[0, 1].getValue().ToString();
button3.Text = board.gameBoard[0, 2].getValue().ToString();
button4.Text = board.gameBoard[0, 3].getValue().ToString();
button5.Text = board.gameBoard[1, 0].getValue().ToString();
...
button15.Text = board.gameBoard[3, 2].getValue().ToString();
button16.Text = board.gameBoard[3, 3].getValue().ToString();

有没有更简单的方法可以做到这一点?它现在正在工作(http://screenshot.sh/mMDP9pvcC7WOk),但我认为这不是做这件事的最佳方式。有人可以告诉我如何做得更好吗?

您可以动态创建按钮,并在创建过程中将文本放入要Button.Text的内容。

它将是这样的:

// array of your buttons (it's not necessary)
var buttons = new Button[4,4];
void SomeMethod()
{
    for(var x = 0; x < 4; x++)
    {
    for(var y = 0; y < 4; y++)
        {
            var newButton = new Button();
            // put your text into the button
            newButton.Text = board.gameBoard[x, y].getValue().ToString();
            // set the coordinates for your button
            newButton.Location = new Point(someCoordinateX, someCoordinateY);
            // store just created button to the array
            buttons[x, y] = newButton;
            // add just created button to the form
            this.Controls.Add(newButton).
        }
    }
}

然后,在初始化步骤的某个地方使用此方法来创建和初始化按钮。如果您需要以某种方式修改按钮,最近可以使用 buttons 数组。

希望它会有所帮助。

最新更新