Friday, July 3, 2009

Edit the TreeView Node by pressing F2 Key

We may want to edit the treeview nodes by pressing F2 Key like how we are renaming the folders in Windows.

How to achive this in Windows Forms TreeView Control.

We need to check whether any treeview node is selected while pressing F2 Key. If so make the node as Editable.

To edit the tree node by pressing F2 Key you can use the following code.


Private Sub TreeView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TreeView1.KeyDown

'Check Whether the Key is F2

If e.KeyCode = Keys.F2 Then

'Check the tree view node is selected
If Not TreeView1.SelectedNode Is Nothing Then


TreeView1.LabelEdit = True

'this will start edit on selected node

TreeView1.SelectedNode.BeginEdit()
else
MsgBox ("Select the node")

End If

End If
End Sub


Private Sub treeView1_AfterLabelEdit(sender As Object, _
e As System.Windows.Forms.NodeLabelEditEventArgs)
If Not (e.Label Is Nothing) Then

'this will stop edit on selected node

Me.treeView1.LabelEdit = False
End If
End Sub

2 comments: