views:

1738

answers:

3

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.

+2  A: 

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.

Frans Bouma
That's just wrong. As you can see in the question, he is doing just that and still the background color changes.
configurator
Though not really noticable. What happens is that he clicks the node, the node gets selected when the button is still down, then the selection is denied and the node is de-selected when the mouse button goes up.
Frans Bouma
+1  A: 

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

OneSHOT
A: 

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();
}
Arjan