Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treeview Node click behavior

I have a Winform application where I am using TreeView. Some users of this application have a problem that they must double click on a node to expand it. So I added this code to use single click to expand nodes:

Private Sub MyTreeView_NodeMouseClick(sender As System.Object, 
     e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles MyTreeView.NodeMouseClick

    If e.Node.IsExpanded Then
        e.Node.Collapse()
    Else
        e.Node.Expand()
    End If

End Sub

This works but I noticed strange behavior regarding clicking on a nodes. I noticed that there are 2 places with different behavior. First place is with +/- symbol and dots next to it (first circle in the picture), second place is a text of the node (second circle):

enter image description here

Normally single click on the first place is enough to expand node and double click must be done on the second place to expand node. Then when I use my code, single click on the second place is enough to expand the node but when I do single click on the first place, the node is expanded and collapsed.

Why the user must do twice more clicks on the second place to expand node? What can I do to expand nodes with single click on both places? Thank you guys!

like image 339
DanielH Avatar asked May 20 '14 11:05

DanielH


People also ask

How do I know if TreeView node is selected?

SelectedNode; if ( tn == null ) Console. WriteLine("No tree node selected."); else Console. WriteLine("Selected tree node {0}.", tn.Name ); You can compare the returned TreeNode reference to the TreeNode you're looking for, and so check if it's currently selected.

How many root nodes can a TreeView control have?

A typical tree structure has only one root node; however, you can add multiple root nodes to the TreeView control. The Nodes property can also be used to manage the root nodes in the tree programmatically. You can add, insert, remove, and retrieve TreeNode objects from the collection.

What is TreeView node?

The Nodes property holds a collection of TreeNode objects, each of which has a Nodes property that can contain its own TreeNodeCollection.

Which property in the TreeView control represent the node?

The TreeNode class represents a node of a TreeView.


1 Answers

The plus/minus is still considered part of the Node - and when the user clicks it, your code toggles the expansion but the framework continues and does the same.

Add to your code to not act on the plus/minus:

private static void TreeView_OnNodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    var hitTest = e.Node.TreeView.HitTest(e.Location);
    if (hitTest.Location == TreeViewHitTestLocations.PlusMinus)
        return;

    if (e.Node.IsExpanded)
        e.Node.Collapse();
    else
        e.Node.Expand();
}
like image 168
John Arlen Avatar answered Oct 11 '22 11:10

John Arlen