Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C# -- I have a winform that has 1 to n panels on it, where n could equal 50 or more. I do know the name (and can assign the name to a string variable) of the current panel that is visible, but if I want to make that panel visible = false and another visible = true, I need to know how to do that know only the name that is in a string variable.
Posted
Updated 12-Sep-12 10:45am
v2
Comments
[no name] 12-Sep-12 16:43pm    
How exactly is "panel visible = false and another visible = true" any kind of a problem?

You are storing the names of your variables (panels), as strings? In some sort of collection? I really have to ask why?

I recommend storing the variables (panels) in a collection. Are they stored anywhere?
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 12-Sep-12 17:03pm    
My 5. That was my idea, too, but also: doing this is awkward with the Designer. Creation of so many controls should be in code -- please see my answer.
--SA
wizardzz 12-Sep-12 17:06pm    
I agree with you.
You should not use the Name property. Using string data instead of actual data is one of the worst trends of the beginners these days, hard to say why. You need to store objects themselves, references. Now, I can only assume you created all 50 or more panels in Designer. This is totally wrong — a lot of manual work, nothing else. You should create them in your code, not auto-generated code. (Don't use <codename> at all!) This way, you can store the reference in an array or some other collection, for easy access and to avoid manual labor. (Are you a software developer, anyway? :-)). And then, yes, <code>panel.Visible = false; /* … */ panel.Visible = true; … you cannot go wrong with that…

—SA
 
Share this answer
 
You can get the panel out of the Controls collection using LINQ and the name of the Panel that you want to work with. This gets a panel out of the collection that has the name "panel1".

C#
var p = from c in this.Controls.Cast<Control>()
                      where c.Name == "panel1"
                      select c;
            Panel pan = (Panel)p.FirstOrDefault();


From there you can do whatever you want with it, make it visible, invisible, change the background color.
 
Share this answer
 
v2
Comments
Kim Togo 18-Sep-12 2:12am    
Good approach with LINQ, makes it easy to read.
You can change the
this.Controls.Cast<control>()
to
this.Controls.OfType<Panel>()

Then it will only return Controls of type Panel.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900