Home > OS >  C# - Dealing with Panels as a member in array
C# - Dealing with Panels as a member in array

Time:04-10

In C Sharp form, I have some Panels, and I want to change their format as a group. So I put all their names in an array, and I put my command in a loop.

The problem in C# is that it's dealing with the Panel name from the array as text only, not as an object. It's not allowing me to change the format of the Panel from this type of command.

If I put the Panel name directly, it will work, but if I take the name from the array as Array[], it will give an error.

How can I reach the panels from their names in the array ?.

My code is this:-

        string[] AllPanels = new string[] { "pnl_1_Listening1", "pnl_2_Undrestand", "pnl_3_SayAfter", "pnl_4_SayWith", "pnl_5_TakeArole", "pnl_6_Exam", "pnl_7_Listening2" };
        int PanelsCount = AllPanels.Count(); 
       
        for (int PanelLoop=0; PanelLoop <= PanelsCount-1; PanelLoop  )
        {
            AllPanels[PanelLoop].Location = new Point(100,100);
        }

CodePudding user response:

Declare your array of type Panel, then use a foreach loop:

Panel[] AllPanels = new Panel[] {pnl_1_Listening1, pnl_2_Undrestand, 
    pnl_3_SayAfter, pnl_4_SayWith, pnl_5_TakeArole,
    pnl_6_Exam, pnl_7_Listening2};

foreach(Panel p in AllPanels) {
    p.Location = new Point(100,100);
}

Or if you'd prefer an indexed for loop:

for (int i=0; i<AllPanels.Length; i  )
{
    AllPanels[i].Location = new Point(100,100);
}

If you absolutely want to work with strings, then search for the control:

string[] AllPanels = new string[] {"pnl_1_Listening1",
    "pnl_2_Undrestand", "pnl_3_SayAfter", "pnl_4_SayWith", 
    "pnl_5_TakeArole", "pnl_6_Exam", "pnl_7_Listening2" };

foreach(string ctlName in AllPanels) {
    Panel p = this.Controls.Find(ctlName, true).FirstOrDefault() as Panel;
    if (p != null) {
        p.Location = new Point(100, 100);
    }
}

CodePudding user response:

The problem is that you are trying use a string like your Panel object. If you do this:

Panel panel = new Panel() { Name = "myPanel" };

You can't do:

myPanel.Location = ...

Because myPanel doesn't exists as a variable. The confussion maybe because the name of your panel is the same as your variable, like in this line:

Panel myPanel = new Panel() { Name = "myPanel" };
  • Related