【问题标题】:Easiest way to display 2dimensional array of values on buttons在按钮上显示二维值数组的最简单方法
【发布时间】:2016-05-22 02:58:11
【问题描述】:

我正在寻找在按钮上显示二维值数组的优化代码。 我创建了这样的按钮网格: 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),但我认为这不是做这件事的最佳方式。有人可以告诉我如何做得更好吗?

【问题讨论】:

标签: c# windows winforms


【解决方案1】:

您可以动态创建按钮,并在创建过程中将您想要的文本放入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 数组。

希望它会有所帮助。

【讨论】:

  • 嗯.. 它应该可以工作,谢谢。每次按键后按钮的值和一些属性都会改变,所以我会为此创建一个类。
  • 在这种情况下,您可以使用创建的按钮数组来处理按钮更改
  • TableLayoutPanel 我猜会是更好的选择,因为我也可以轻松更改整个面板属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
  • 2010-10-27
  • 2011-06-14
  • 2011-04-28
  • 1970-01-01
相关资源
最近更新 更多