1

I have panel that visibility is false. I want when click on treeview list, that list will retrive the panel name that i stored in database. i know how to retrieve that panel name from database in string. But how to change that 'string' into panel to make able to write like this:

panelNamethatLoadFromDB.visible = true;

My Code:

DataTable dtPanelToView = MyLibrary.getResults("SELECT LEVEL1_ID, LEVEL1_PATH FROM LEVEL1_TREEVIEW WHERE LEVEL1_DESC='" + clickLink + "'");
if (dtPanelToView.Rows.Count > 0)
{
string panelToDisplay = dtPanelToView.Rows[0]["LEVEL1_PATH"].ToString();
}

So, currently this "panelToDisplay" is string that contains panel name. i want to change this panel visibilty. Example : panelToDisplay.visible = true;

Ifwat Ibrahim
  • 1,523
  • 4
  • 16
  • 28

1 Answers1

3

WinForms stores the controls diplayed on a form in the Form.Controls collection.
You could loop over this collection to find your panel

 foreach(var pan in yourForm.Controls.OfType<Panel>())
 {
     if(pan.Name == panelToDisplay)
     {
        pan.Visible = true;
     }
 }

Using the IEnumerable extensions you could also avoid the explicit loop with

 var pan = yourForm.Controls.OfType<Panel>().FirstOrDefault(x => x.Name == panelToDisplay);
 if(pan != null)
     pan.Visible = true;

Keep in mind that the Controls collection of the form stores only the first level of controls. If a control contained in the Form's Controls collection is a control container then it has its Controls collection where other controls could be stored.

EDIT
As from the comment below from TaW you could also use the Controls collection with a string indexer

if(this.Controls.ContainsKey(panelToDisplay))
    this.Controls[panelToDisplay].Visible = false;
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • 3
    Actually `Controls[name]` should also work, __if__ it exists. – TaW Nov 01 '14 at 21:13
  • @TaW yes for the purpose stated by the OP this could be enough, but to get back the strongly typed Panel and use its specific properties you need to add also a cast. Will update the answer with your comment – Steve Nov 02 '14 at 11:38