C # Stop Treeview by selecting one or more TreeNodes

I have a TreeView control showing multiple TreeNodes in an organized hierarchy. I want to stop the user by selecting the nodes with the highest level (this was achieved using the BeforeSelect event). I also want the TreeView not to highlight top-level nodes if the user selects them, i.e. Will stop the TreeView from changing the background color of the node and "selecting" it.

The TreeView I'm using is the WinForms version of the control.

Below is the source code I'm currently trying to use:

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

      

This deselects the node, but only after the unwanted flash appears (~ 200ms).

+1


source to share


3 answers


In addition to the existing code, if you add a MouseDown event handler to the TreeView with code and select a node using its location, you can set the colors of the nodes.

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 small issue in that the selected path still appears on MouseDown, but at least stops the blue background and a little further than you.



NTN

Oneshot

+2


source


This code prevents the drawing from being selected until it is canceled:



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

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

      

+10


source


If the selection is deselected by setting Cancel to true in the arguments of the BeforeSelect event, the node will not be selected, and thus the background color will not change.

+2


source







All Articles