Read EDIT 2 first
I am trying to set up some way to visually distinguish the nodes in a winform app. For example, alternating colors.
Can some one start me down that path? Also, has anyone else had to do that before and how did you do it?
Thanks
I had seen the backcolor setting as well(Thank You) but I am having trouble getting it to work. I do not see a Paint() event for treeviews. I tried putting the below code in my Form Load() but it isn't working. Possibly because the treeview is loaded yet??
private void frmCaseNotes_Load(object sender, System.EventArgs e)
{
foreach (TreeNode treeNode in treeView1.Nodes[0].Nodes)
{
treeNode.BackColor = Color.DeepSkyBlue;
}
}
Okay, I have the initial problem out of the way using the below on Form_Load()
foreach (TreeNode treeNode in treeView1.Nodes)
{
if (treeNode.Index % 2 == 0)
{
treeNode.ForeColor = Color.DodgerBlue;
}
else
{
treeNode.ForeColor = Color.Goldenrod;
}
Now what I need to figure out, with someone's help, is how to Loop through ALL layers of nodes and apply my alternating coloring. If I do something along the below lines I can achieve this.
foreach (TreeNode treeNode in treeView1.Nodes[1].Nodes[0].Nodes)
{
if (treeNode.Index % 2 == 0)
{
treeNode.ForeColor = Color.DodgerBlue;
}
else
{
treeNode.ForeColor = Color.Goldenrod;
}
How do I iterate through ALL layers programatically?
Recursion?
Edit: added code for eliminating color repetition
protected void ColorNodes(TreeNode root, Color firstColor, Color secondColor)
{
Color nextColor;
foreach (TreeNode childNode in root.Nodes)
{
nextColor = childNode.ForeColor = childNode.Index % 2 == 0 ? firstColor : secondColor;
if (childNode.Nodes.Count > 0)
{
// alternate colors for the next node
if (nextColor == firstColor)
ColorNodes(childNode, secondColor, firstColor);
else
ColorNodes(childNode, firstColor, secondColor);
}
}
}
private void frmCaseNotes_Load(object sender, System.EventArgs e)
{
foreach (TreeNode rootNode in treeView1.Nodes)
{
ColorNodes(rootNode, Color.Goldenrod, Color.DodgerBlue);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With