unknown
unknown

Reputation: 25

How to generate multiple controls with code

So I'm trying to create the same control (in this case a panel) over and over via my code. I can do this by using this piece of code

    int i;
    int PNL_1_Loc = -70;

    private void CreateControls()
    {
        Panel PNL_1 = new Panel();

        i = i + 1;

        PNL_1_Loc= PNL_1_Loc+ 70;
        PNL_1.Location = new Point(0, PNL_1_Loc);
        PNL_1.Name = "PNL_1_" + i.ToString();

        PNL_1.Width = 1052;
        PNL_1.Height = 60;
        PNL_1.BackColor = Color.FromArgb(222, 222, 222);
   }

Every time I call this function it creates a panel with the name: PNL_1_(panel number). The problem is that I want to acces the PNL_1 variable outside of the function it is created in.

I tried to fix this by placing the PNL_1 variable outside of the function. This doesn't work at all. It can create a panel, but when I press the button for the second time it removes the first panel and creates the second panel. This is a problem because I want to keep the first panel. How do I do this?

Upvotes: 0

Views: 68

Answers (1)

Cataklysim
Cataklysim

Reputation: 677

Simply create a public List outside your Method and add the Panel at the end of it into that list. You will always be able to access all Panel you created.

public List<Panel> ExistingSelfMadePanel { get; set;}

private void CreateControls()
{
    //your code
    this.ExistingSelfMadePanel.Add(PNL_1);
}

Edit: I don't know how far you are into properties like this, but don't forget to initialize the List!

this.ExistinSelfMadePanel = new List<Panel>();

Otherwise you get a null reference exception. Just came into my mind. :)

Edit II:

Here is a "small" Documentation from MSDN about the Generic List. There will be shown how to store and access the items you stored in it. Read it carefully and you will be able to access the panels you want. Also, I think you are getting us wrong. To manipulate a existing Panel, load the wanted panel with the help of your List. Something like this:

foreach (Panel tmpPanel in Form1.ActiveForm.Controls)
{
  if(tmpPanel.Name == this.ExistingSelfMadePanel.FirstOrDefault(p => p.Name == "PNL_1").Name)
  {
     tmpPanel.ForeColor = Color.Aquamarine;
     break;
  }
}

Upvotes: 1

Related Questions