Question

I have a TreeView control showing multiple TreeNodes in an organised heirarchy. I want to stop the user selecting the highest level Nodes (this was achieved by using the BeforeSelect Event). I also want to stop the TreeView from highlighting the top level nodes if the user selects them i.e. stop the TreeView from changing the background color of the node and 'selecting' it.

The TreeView that I am using is the WinForms version of the control.

Below is the source code I am currently attempting to use:

private void tree_BeforeSelect ( object sender, TreeViewCancelEventArgs e )
{
    if ( e.Node.Level == 0 )
    {
        e.Cancel = true;
    }
}

This does de-select the Node but only after a noticible flash (~200ms) which is undesirable.

Was it helpful?

Solution

In addition to your existing code if you add a handler to the MouseDown event on the TreeView with the code and select the node out using it's location, you can then set the nodes colours.

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    TreeNode tn = treeView1.GetNodeAt(e.Location);
    tn.BackColor = System.Drawing.Color.White;
    tn.ForeColor = System.Drawing.Color.Black;
}

There is still a slight problem in that the select outline still shows on MouseDown but it atleast stops the blue background and gets you a little further.

HTH

OneSHOT

OTHER TIPS

This code prevents drawing the selection before it is canceled:

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    treeView1.BeginUpdate();
}

private void treeView1_MouseUp(object sender, MouseEventArgs e)
{
    treeView1.EndUpdate();
}

If the selecting is cancelled by setting Cancel to true in the BeforeSelect's event args, the node will not be selected and thus the background color won't change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top