1

I have a Panel and two LinkLabels added on the panel and a treeview.

now in the panel_Paint event i want that the linklabel colors become white and background color of treeview turns black. how do i do this?

the below code works only when there is no tree view in the panel but when i add a treeview also in the panel then it says :

Unable to cast object of type 'System.Windows.Forms.TreeView' to type 'System.Windows.Forms.LinkLabel'.

foreach (LinkLabel link in panel1.Controls)
{         
    link.LinkColor = Color.White; 
}

3 Answers 3

3

Your panel contains all the controls - one of them is a TreeView which cannot be cast into a LinkLabel. In your loop you need to check the type of the control like this:

foreach (Control control in panel1.Controls)
{
   if (control is LinkLabel)
   {
       ... set link color
   }
   else if (control is TreeView)
   {
       ... set background
   }
}

Alternatively if you only have one LinkLabel and one TreeView you would not need a loop - just access them by name like you did with panel1

2

Try this:

foreach (Control ctrl in panel1.Controls)
{
     LinkLabel link = ctrl as LinkLabel;
     if(link != null)
        link.LinkColor = Color.White; 
}
2

Your getting the error because your trying to cast all controls in panel1 to a LinkLabel. You need to try something like this

foreach (Control control in panel1.Controls)
{
       if (control.GetType() == typeof(LinkLabel))
       {
            LinkLabel link = (LinkLabel)control;
            link.LinkColor = Color.White; 
       } 
}

Hope this helps.

Edit: I knew there was a method but wasn't sure 100% of the name or syntax. See below an improved answer.

foreach (LinkLabel link in panel1.Controls.OfType<LinkLabel>())
{
    link.LinkColor = Color.White;
}

Hope this is better for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.