TreeNode.BeginEdit Method
Initiates the editing of the tree node label.
Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
| Exception | Condition |
|---|---|
| InvalidOperationException | TreeView.LabelEdit is set to false. |
The following code example lets the user edit nonroot tree nodes by using a ContextMenu. When the user right-clicks the mouse, the TreeNode at that position is determined and stored in a variable named mySelectedNode. If a nonroot tree node was selected, it is put into an editable state, allowing the user to edit the node label. After the user stops editing the tree node label, the new label text is evaluated and saved. For this example, several characters are considered not valid in the label text. If one of the invalid characters is in the label string, or the string is empty, the user is notified of the error and the label is returned to its previous text.
/* Get the tree node under the mouse pointer and save it in the mySelectedNode variable. */ private void treeView1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { mySelectedNode = treeView1.GetNodeAt(e.X, e.Y); } private void menuItem1_Click(object sender, System.EventArgs e) { if (mySelectedNode != null && mySelectedNode.Parent != null) { treeView1.SelectedNode = mySelectedNode; treeView1.LabelEdit = true; if(!mySelectedNode.IsEditing) { mySelectedNode.BeginEdit(); } } else { MessageBox.Show("No tree node selected or selected node is a root node.\n" + "Editing of root nodes is not allowed.", "Invalid selection"); } } private void treeView1_AfterLabelEdit(object sender, System.Windows.Forms.NodeLabelEditEventArgs e) { if (e.Label != null) { if(e.Label.Length > 0) { if (e.Label.IndexOfAny(new char[]{'@', '.', ',', '!'}) == -1) { // Stop editing without canceling the label change. e.Node.EndEdit(false); } else { /* Cancel the label edit action, inform the user, and place the node in edit mode again. */ e.CancelEdit = true; MessageBox.Show("Invalid tree node label.\n" + "The invalid characters are: '@','.', ',', '!'", "Node Label Edit"); e.Node.BeginEdit(); } } else { /* Cancel the label edit action, inform the user, and place the node in edit mode again. */ e.CancelEdit = true; MessageBox.Show("Invalid tree node label.\nThe label cannot be blank", "Node Label Edit"); e.Node.BeginEdit(); } } }
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Note