1

I am looking for optymalize code with displaying 2dimensional array of values on buttons. I have created grid of buttons like that: http://screenshot.sh/m2eZscO4i0fXq and I am actually displaying values of array on this buttons using this code:

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

Is there easier way to do that? It's working now (http://screenshot.sh/mMDP9pvcC7WOk), but it isn't the best way to do this thing I think. Can somebody show me how do that better?

Beast
  • 25
  • 1
  • 1
  • 11
  • You may find this post useful: [How to create a magic square using Windows Forms?](http://stackoverflow.com/questions/33968993/how-to-create-a-magic-square-using-windows-forms) – Reza Aghaei May 21 '16 at 19:05
  • Yeah, this is great. I wasn't looking long enough :D This is better solution than below I think. Am I right? – Beast May 21 '16 at 19:14

1 Answers1

0

You can create your buttons dynamically and during creating put the text what you want to Button.Text.

It will be something like:

// 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).
        }
    }
}

then, use this method somewhere on initialization step to create and initialize your buttons. The buttons array could be used lately if you will need to modify your buttons somehow.

Hope it will help.

MaKCbIMKo
  • 2,800
  • 1
  • 19
  • 27
  • Hmm.. It should work, thanks. Values and some properties of buttons will be changed each time after pressing key, so I will create a class for that. – Beast May 21 '16 at 19:07
  • In that case you can use created button array to handle button changes – MaKCbIMKo May 21 '16 at 19:09
  • TableLayoutPanel will be the better choice I guess because I can easy change whole Panel properties too. – Beast May 21 '16 at 19:16