2

I am trying to write a C# program that plays checkers. So far I've completed all the "Shallow" things such as generating the board and all the labels etc.

My problem is that all the controls are dynamically added. So I can't just "double click" them and define what to do at Button_Click event.

This is my code for generating the form

    public partial class formGameBoard : Form
    {
        private readonly int m_BoardSize;
        private readonly string m_Player1Name;
        private readonly string m_Player2Name;
        private GameTile m_BlueTile;
        private bool m_IsThereBlue;

        public formGameBoard(int i_BoardSize, string i_Player1Name, string i_Player2Name)
        {
            m_BoardSize = i_BoardSize;
            m_Player1Name = i_Player1Name;
            m_Player2Name = i_Player2Name;
            if (m_Player2Name == "(Computer)")
            {
                m_Player2Name = "Computer";
            }
            m_IsThereBlue = false;
            InitializeComponent();

        }

        private void formGameBoard_Load(object sender, EventArgs e)
        {
            int SizeOfButton = 60;
            int ButtonRowindex = 0;
            int ButtonColindex = 0;
            this.Size = new System.Drawing.Size(30 + m_BoardSize * SizeOfButton, 100 + m_BoardSize * SizeOfButton);
            Button[,] PlayButtonArray = new Button[m_BoardSize, m_BoardSize];
            for (ButtonRowindex = 0; ButtonRowindex < m_BoardSize; ButtonRowindex++)
            {
                for (ButtonColindex = 0; ButtonColindex < m_BoardSize; ButtonColindex++)
                {
                    PlayButtonArray[ButtonRowindex, ButtonColindex] = new Button();
                    PlayButtonArray[ButtonRowindex, ButtonColindex].Size = new Size(SizeOfButton, SizeOfButton);
                    PlayButtonArray[ButtonRowindex, ButtonColindex].Left = 10 + ButtonRowindex * SizeOfButton;
                    PlayButtonArray[ButtonRowindex, ButtonColindex].Top = 50 + ButtonColindex * SizeOfButton;
                    if ((ButtonRowindex + ButtonColindex) % 2 == 0)
                    {
                        PlayButtonArray[ButtonRowindex, ButtonColindex].Enabled = false;
                        PlayButtonArray[ButtonRowindex, ButtonColindex].BackColor = Color.Gray;
                    }

                    this.Controls.Add(PlayButtonArray[ButtonRowindex, ButtonColindex]);
                }
            }

            FillButtons(PlayButtonArray);
        }

        public void FillButtons(Button[,] ButtonMatrix)
        {
            int i, j;
            for (i = 0; i < m_BoardSize; i++)
            {
                for (j = 0; j < m_BoardSize; j++)
                {
                    if ((i + j) % 2 == 1)
                    {
                        if (j <= (m_BoardSize / 2) - 2)
                        {
                            ButtonMatrix[i, j].Text = "O";
                        }

                        if (j > (m_BoardSize / 2))
                        {
                            ButtonMatrix[i, j].Text = "X";
                        }
                    }
                }
            }
        }

        struct GameTile
        {
            int RowIndex;
            int ColumnIndex;
        }
    }
}

I have no issues with it, it looks very nice in my opinion enter image description here

My problem is that all those buttons are dynamically added. I didnt drag and drop them. I created them at form load. Now I want something to happen when I click a button. For example, I want the button I clicked to change its color to blue.

How can I do that?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Oria Gruber
  • 1,513
  • 2
  • 22
  • 44

2 Answers2

4

Adding the click event for a button is very simple, like this:

buttonName.Click += (sender, e) => { buttonName.Foreground = Colors.Blue; };

Or if you want to make it a method that will handle many button clicks, you could do this:

buttonName.Click += YourButtonHandler;

private void YourButtonHandler(object sender, EventArgs e)
{
    // do something, for example:
    Button b = sender as Button;
    b.Foreground = Colors.Blue;
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
2

You can add a handler to Click event of your buttons and use sender parameter.

Also probably the index of button in the array is important for you, so you can store array index of the button in Tag property and use it later.

In the for loop:

var button = PlayButtonArray[ButtonRowindex, ButtonColindex];
button.Tag= new Point(ButtonRowindex, ButtonColindex);
button.Click += Button_Click;

Code for Button_Click:

private void Button_Click(object sender, EventArgs e)
{
    var button = sender as Button;
    //You can manipulate button here

    //Also to extract the button index in array:
    var indexes = (Point)button.Tag;

    MessageBox.Show(string.Format("This is the button at {0}, {1}", indexes.X, indexes.Y));
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • It's working! Thank you! – Oria Gruber Jan 08 '16 at 17:30
  • In the for loop, where you are creating buttons. after `PlayButtonArray[ButtonRowindex, ButtonColindex]` or use `PlayButtonArray[ButtonRowindex, ButtonColindex]` instead of var button. – Reza Aghaei Jan 08 '16 at 17:31
  • The button.Tag as Point doesnt seem to be working though. point is non nullable value type and as must be used with reference type or nullable value type. – Oria Gruber Jan 08 '16 at 17:33
  • It is just a data structure to store (x,y). You will not use it as location. – Reza Aghaei Jan 08 '16 at 17:34
  • 1
    @OriaGruber Sure it's working. Reza is a WinForms guru, you can learn a lot from him. As per your last comment, use `var indexes = (Point)button.Tag;` – Ivan Stoev Jan 08 '16 at 17:34
  • Thank you both so very much. Always happy to learn from the more experienced. – Oria Gruber Jan 08 '16 at 17:35
  • @OriaGruber Also you can use `TableLayoutPanel` to layout controls more simple. You may find this Q/A helpful: [Dynamic button creation & placing them in a predefined order using c#](http://stackoverflow.com/questions/34426888/dynamic-button-creation-placing-them-in-a-predefined-order-using-c-sharp/34426939#34426939) this way working with layout is more flexible and more easy. – Reza Aghaei Jan 08 '16 at 17:40
  • @IvanStoev Thank you for pointing `(Point)button.Tag;`, and thank you for your kindness, seeing you around is really blessing :) – Reza Aghaei Jan 08 '16 at 17:47
  • @RezaAghaei The pleasure was all mine :) Happy New Year! – Ivan Stoev Jan 08 '16 at 17:50
  • @IvanStoev Happy new year to you too :) – Reza Aghaei Jan 08 '16 at 18:18
  • @OriaGruber It may be useful if you take a look at linked question and read the answer, even if you don't want to change your code now. Hope you find it helpful too :) – Reza Aghaei Jan 08 '16 at 18:31