1

For a School assignment we are making a Chess game in C#, in which we have to learn to work in a Object-Oriented way. The board is made out of a 2D picturebox array in a nested for loop

//Create the Board Pattern out of PictureBoxes
        #region Checkerboard

        PictureBox[,] Vak = new PictureBox[8, 8];

        for (int i = 0; i < 8; i++)
        {
            for (int x = 0; x < 8; x++)
            {

                Vak[i, x] = new PictureBox();
                Vak[i, x].Name = String.Format("{0},{1}", i, x);
                Vak[i, x].Width = 50;
                Vak[i, x].Height = 50;
                Vak[i, x].Location = new Point(xpos, ypos);
                Vak[i, x].SizeMode = PictureBoxSizeMode.Zoom;
                Vak[i, x].Click += Chess_Click;
                if ((i + x) % 2 == 0)
                {
                    Vak[i, x].BackColor = ColorTranslator.FromHtml("#e5e5e5");  //white ColorTranslator.FromHtml("#e5e5e5");
                }
                else
                {
                    Vak[i, x].BackColor = ColorTranslator.FromHtml("#545454"); //black ColorTranslator.FromHtml("#545454");

                }
                xpos += 50;
                this.Controls.Add(Vak[i, x]);
            }
            xpos = 50;
            ypos += 50;
            this.Controls.Add(border);
        }
        #endregion

On other posts i have found that i can Refer to a class (via the picturebox) using the .Tag property like so:

Vak[i,x].Tag = new Tower();

However, i cannot figure out a way to call properties from the Tower class from withing the tag

Say the Tower class has a property "name", how would i go about calling that

string objectname = Vak[i,x].Tag.(name?)

Sorry If this is a stupid question, but i am very new to programming. Thanks!

3
  • 1
    If you know the type of the object that you're storing in the Tag property, you'll need to cast it explicitly to that type to access its properties. Something like ((Tower)(Vak[i, x])).Name.
    – dotNET
    Mar 8, 2016 at 13:48
  • 3
    I would recommend not to use the Tag property, but instead create your own struct with a picturebox and a chesspiece member.
    – wimh
    Mar 8, 2016 at 13:50
  • @Wimmel And how exactly would i go about doing that?
    – Daanv z
    Mar 8, 2016 at 13:57

1 Answer 1

6

You have to cast it, since Tag is an Object type:

Tower tower = Vak[i,x].Tag as Tower;

if(tower!=null)
{
   //do stuff
}

However, i would avoid storing data structures in Tag properties like this.

1
  • 1
    And what if it is not a Tower?
    – wimh
    Mar 8, 2016 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.