Looping and finding controls is not really necessary. You should add all your panels to a same container, use the Controls
collection and pass in the name to get the control:
public void setMeVisible(string PanelName) {
PageMainScreen.Visible = false;
PageNewRegistration.Visible = false;
PageSelectedPatient.Visible = false;
Control c = sameContainer.Controls[PanelName];
if(c != null) c.Visible = true;
}
If each time there is only 1 panel visible, you should use some variable to track the current shown panel and hide only this (instead of all controls as you did) like this:
Control currentShown;
public void setMeVisible(string PanelName) {
Control c = sameContainer.Controls[PanelName];
if(c != null) {
c.Visible = true;
if(currentShown != null) currentShown.Visible = false;
currentShown = c;
}
}
And the last, if you don't want to use the same container for all your panels. You should declare some List<Panel>
to contain all your panels, then you can navigate through them easily:
List<Panel> panels = new List<Panel>();
panels.AddRange(new[]{PageMainScreen, PageNewRegistration, PageSelectedPatient});
public void setMeVisible(string PanelName) {
var c = panels.FirstOrDefault(panel=>panel.Name == PanelName);
if(c != null) {
c.Visible = true;
if(currentShown != null) currentShown.Visible = false;
currentShown = c;
}
}
NOTE: Don't try complicating your UI unnecessarily. I want to mean that you should place all your panels on the same container (such as your form). That's the way we do, that way you can use the first approach, no need to loop, easy to maintain. You should also consider the Dock
and the methods like BringToFront()
and SendToBack()
to show/hide the view.