Darren Young
Darren Young

Reputation: 11090

Setting TreeView ForeColor using C#

I have a treeview that when the user interacts with individual nodes, the colours change. The code is:

treeview.selectednode.forecolor = color.red;

When the user presses a button, I want the whole set of nodes to change to black for example. So I code as such:

treeview.forecolor = color.black;

It works fine, except for the nodes that I have previously changed to red. Is there a way to get around this?

Upvotes: 3

Views: 1838

Answers (2)

Genius
Genius

Reputation: 1114

Use this recursive function:

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    (sender as TreeView).SelectedNode.ForeColor = Color.Red;
}

private void button1_Click(object sender, EventArgs e)
{
    foreach (TreeNode tn in treeView1.Nodes)
    {
        tn.ForeColor = Color.Blue;
        ColorNodes(tn);
    }
}

private void ColorNodes(TreeNode t)
{
    foreach (TreeNode tn in t.Nodes)
    {
        tn.ForeColor = Color.Blue;
        ColorNodes(tn);
    }
}

Upvotes: 2

user441660
user441660

Reputation: 555

Keep a reference to the previously selected node, turn it into black whenever you change treeview to black.

Upvotes: 0

Related Questions