views:

59

answers:

1

I was wondering how could I select objects which were created during programs runtime. Each object has its unique name. How could I select that object by its name?

Example names:

"mapPart_0_0"
"mapPart_0_1"
"mapPart_0_2"
etc.

It's a windows form project. In c#.

Creation of those objects:

    private void addBoxes()
    {
        for (int a = 0; a < 25; a++)
        {
            for (int b = 0; b < 10; b++)
            {
                MyCustomPictureBox box = new MyCustomPictureBox();
                box.Location = new Point(b * 23 + 5, a * 23 + 5);
                box.Image = new System.Drawing.Bitmap("tiles/0.png");
                box.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                box.Size = new Size(24, 24);
                box.Name = "mapPart_" + a + "_" + b;
                box.Click += new EventHandler(boxClickAdd);
                box.oFile = "0";
                panel1.Controls.Add(box);
            }
        }
    }
+5  A: 

I would suggest to simply put the objects in a System.Collections.Generic.Dictionary<string, your object type> list. It provides the exact functionality you are seeking if I understand the question correctly.

Regards, Mathias

rotti2
I agree with Mathias. Simply add the objects, as you create them dynamically, to a Dictionary.You can use Reflection, but that may incur an unacceptable runtime penalty (and Reflection in C# can be verbose).
Joubert Nel