0

In my program i'm currently working on programmatically adding a variety of form objects in C#. For example i'm trying to create a certain group of panels, which contain the data I wish to show. When loading the form I have a file which contains all of the data I wish to load in, the loading itself works fine but when loading I need to create a variety of form labels, panels and images to display all of the necessary data and as such I need to make these panels and labels all with a seperate name, but programmatically.

for (int i=0; i<fileLength; i++)
{
    Panel pnl = New Panel();
    pnl.Name = "pnl1"+i;
    //Set the other properties here
}

What i'm trying to do if use an iterator to append the current iteration to the end of the name. Am I going the right way about it? Or should I be doing a different method?

Rhydis
  • 13
  • 2
  • `Name` is just a string property not related to the variable's name. Not unique, not fixed, just a Property.. – TaW Aug 26 '15 at 09:57

1 Answers1

1

You cannot change variable/object name at runtime. If you want to write code against the object than you need to keep a reference to it. In your case you have changed the Name property of Panel but still you have to use it as pnl, not as pnl0 or pnl1.

The other way for doing this would be to use a Dictionary with key as the name as you assign and value as the object itself. This will help you in accessing your controls using its name that you have assigned to it.

Dictionary<string, Panel> panels = new Dictionary<string, Panel>();
for (i = 0; i <= 10; i++) {
    Panel pnl = new Panel();
    panels.Add("pnl" + i.ToString(), pnl);
}
//write code against panels
panels("pnl0").Width = 100;

For accessing within loop:

foreach (string pnlName in panels.Keys) {
    panels(pnlName).Visible = true;
}

for (i = 0; i <= 10; i++) {
    panels("pnl" + i).Visible = true;
}
Sarvesh Mishra
  • 2,014
  • 15
  • 30
  • So if I wanted to access this new panel within the for loop, would I want to use: panels("pnl"+i.ToString()).Width = 100; Or would there be a better way of doing this? – Rhydis Aug 26 '15 at 14:22