working with controls(linklabels, treeview) in winforms
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 tr开发者_如何学Cee 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;
}
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
Try this:
foreach (Control ctrl in panel1.Controls)
{
LinkLabel link = ctrl as LinkLabel;
if(link != null)
link.LinkColor = Color.White;
}
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.
精彩评论