Selecting a given Node in a TreeView by code

  • Thread starter Thread starter Etienne-Louis Nicolet
  • Start date Start date
E

Etienne-Louis Nicolet

Might be a stupid question, but...

How do I select a Node in a TreeView by code?

Background: If the user selects a node which has childs, I'd like the code
to select the first child instead. I use VB in Visual Studio 2008.

Many thanks for any suggestions,
Etienne
 
Might be a stupid question, but...

How do I select a Node in a TreeView by code?

Background: If the user selects a node which has childs, I'd like the code
to select the first child instead. I use VB in Visual Studio 2008.

You loop through the nodes and find the one you want (i.e., get a reference
to that TreeNode object). Then, from what I can determine, you set the
Checked property of the node to True. Personally, I would have created a
Selected property, but there's only the read-only IsSelected property.
 
Jeff Johnson said:
You loop through the nodes and find the one you want (i.e., get a
reference to that TreeNode object). Then, from what I can determine, you
set the Checked property of the node to True. Personally, I would have
created a Selected property, but there's only the read-only IsSelected
property.
Thank you Jeff, but unfortunately this seems to work only if you set the
TreeView.CheckBoxes to True.

Since in my case I'd like to prevent multiple selections, I set the
CheckBoxes-property to false. Setting the Checked-property of the node did
not select it.

Any other ideas?

Many thanks & kind regards,
Etienne
 
Etienne-Louis Nicolet said:
Might be a stupid question, but...

How do I select a Node in a TreeView by code?

Set the selectedNode property.
Background: If the user selects a node which has childs, I'd like
the code to select the first child instead. I use VB in Visual
Studio 2008.

Private Sub tvw_BeforeSelect( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) _
Handles tvw.BeforeSelect

If e.Node.Nodes.Count > 0 Then
e.Cancel = True
tvw.SelectedNode = e.Node.Nodes(0)
End If

End Sub

Untested Code! Try AfterSelect event if it doesn't work.


Armin
 
tvw.SelectedNode = e.Node.Nodes(0)

Damn I feel stupid. This is how you do it in VB6 for the list view, at
least, and probably the tree view too (don't use them much). How could I
forget that?! I've been using the .NET list view so much recently that I had
"do it at the item level" on the brain.
 
Armin Zingler said:
Set the selectedNode property.


Private Sub tvw_BeforeSelect( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) _
Handles tvw.BeforeSelect

If e.Node.Nodes.Count > 0 Then
e.Cancel = True
tvw.SelectedNode = e.Node.Nodes(0)
End If

End Sub

Untested Code! Try AfterSelect event if it doesn't work.


Armin

Armin, Jeff,

Thank you very much. Armin's suggestion did the trick!

Regards,
Etienne
 
Back
Top