I have some TreeView’s in my winform application. I am trying to make mass changes to all of them in one go. So I wrote the code below:
private void ResetTreeViewColors()
{
foreach (TreeView tv in this.Controls)
{
foreach(TreeNode tn in tv.Nodes)
{
tn.BackColor = Color.White;
tn.ForeColor = Color.Black;
}
}
}
it compiles, but when I call this method, I get an error which says:
Unable to cast object of type ‘System.Windows.Forms.Button’ to type ‘System.Windows.Forms.TreeView’.
Well obviously, I have some other controls like buttons and etc… I am wondering that what is wrong with my code that comiples but fails in action!
The
this.Controlscollection contains all controls, not just treeviews and I’m surprised that doesn’t come up with a compile error or even a warning.You need to check the type of each control before you try and use it as a TreeView: