Abdur Rahim
Abdur Rahim

Reputation: 4021

Access elements in a list

I have generated 8*16 ovalshape's in a form. The code is:

for (int i = 0; i < 16; i++)
{
    for (int j = 0; j < 8; j++)
    {
        OvalShape ovl = new OvalShape();
        ovl.Width = 20;
        ovl.Height = 20;
        ovl.FillStyle = FillStyle.Solid;
        ovl.FillColor = Color.Transparent;
        ovl.Name = "oval" + j + "" + i;

        ovl.Location = new Point((ovl.Width * i) * 2, (ovl.Height * j) * 2);

        ovalShape.Add(ovl);
    }
}

foreach (OvalShape os in ovalShape)
{
    Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer = 
                           new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
    os.Parent = shapeContainer;
    this.Controls.Add(shapeContainer);
}

Now I want access to each ovalshape differently. How could I do this?

Upvotes: 0

Views: 1629

Answers (3)

shenhengbin
shenhengbin

Reputation: 4294

You have already named your controle like ovl.Name = "oval" + j + "" + i;

So , I think you can create dictrionary like Dictionary<string , OvalShape> dic

Then you can set it like

//...
ovl.Name = "oval" + j + "" + i;
dic.add(ovl.Name , ovl);
//...

Then , you can access this dictionary in other methods , and access it by its name.

Upvotes: 0

ABH
ABH

Reputation: 3439

You are already accessing each ovalshape in ovalShape differently in your foreach loop

foreach (OvalShape os in ovalShape)
{
  //...
}

Otherwise you can also access each ovalshape by it's index, as

var newOvalShape = ovalShape[0];

Upvotes: 0

Oded
Oded

Reputation: 499002

Since ovalShape is a List<OvalShape>, you can use the indexer to access any one item:

var anOval = ovalShape[0];

Upvotes: 1

Related Questions