How can I disable selection of a TreeNode in a TreeView in VB.NET?

I'm currently implementing a navigation menu using a TreeView control.

In the menu I'm using headers (root nodes) to group menu items. These headers should only have one purpose: double-click collapse/uncollapse. For this reason it should'nt be possible to select and mark the node, but as default this is possible. What can I do to avoid that the headers can be selected? And is there a way to do this by setting TreeNode properties so that selection events doesn't have to be handled?
andreas_rafnAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
IceBird26Connect With a Mentor Commented:
You could add some code in the treeview's BeforeSelect event. Since you don't want any selections on the root nodes, you could do the following:

     private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Parent == null)    //if a node doesn't have any parents, it's a root
            {
                e.Cancel = true;
            }
        }



The only drawback is that the node will still be highlighted for a short while while the mouse click is in the down position. Hopefully, your users are not very picky ;)
0
 
Luis PérezSoftware Architect in .NetCommented:
Are you using Windows Forms or Web Forms?
0
 
andreas_rafnAuthor Commented:
Windows Forms (System.Windows.Forms.TreeView)
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Use the BeforeSelect() event and set Cancel to True if the Node does not have a Parent (because it's a root):
    Private Sub TreeView1_BeforeSelect(sender As Object, e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeSelect
        e.Cancel = IsNothing(e.Node.Parent)
    End Sub

Open in new window


*The node does get selected momentarily.  =\
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Hehe...guess I'm 20 seconds too late!  =)
0
 
andreas_rafnAuthor Commented:
The fastest submitter gets a little more :) The approach seems good, I'll try to combine it with a handling of the selection color so that the temporary selection will be invisible.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.