MondQ
MondQ

Reputation: 142

Iterate through, and change all form objects

I created a Windows forms application with 6 'Cards'. 'Card' is a class I derived from System.Windows.Forms.PictureBox. I added a member called 'id'.

Is there a way to iterate though all objects of the type 'Card' and change the value of 'id'?

Screenshot

The class definition is below.

    public class Card : System.Windows.Forms.PictureBox
    {
        System.Drawing.Bitmap Back = MemoryGame.Properties.Resources.MG_back;

        byte id = 0;

        public Card()
        {

            this.Image = Back;

            this.SizeMode = PictureBoxSizeMode.Zoom;

         }

        public void Flip(System.Drawing.Bitmap bitmap)
        {

            if (this.Image == Back)
            {
                this.Image = bitmap;
            }
            else
            {
                this.Image = Back;
            }
        }

        public int GetId()
        {
            return this.id;
        }

    }

Upvotes: 0

Views: 128

Answers (2)

Erik T.
Erik T.

Reputation: 370

Loop over the parentcontrols "Controls" property. Then you can check, whether the current control is of your type Card.

foreach(var control in parentControl.Controls)
{
    if(control is Card c)
    {
        c.Id = 0 /*Some new value*/
    }
}

EDIT: Type pattern used in this example is available starting with C# 7.0

Upvotes: 1

mm8
mm8

Reputation: 169200

You could iterate through the Controls collection, e.g.:

int counter = 0;
foreach(var card in this.Controls.OfType<Card>())
{
    card.Id = ++counter;
}

Upvotes: 1

Related Questions