TreeNode.BeginEdit 方法

定義

啟始樹狀節點標籤的編輯。

C#
public void BeginEdit();

例外狀況

範例

下列程式碼範例可讓使用者使用 ContextMenu 編輯非根樹狀節點。 當使用者以滑鼠右鍵按一下滑鼠時, TreeNode 該位置的 會決定並儲存在名為 的 mySelectedNode 變數中。 如果選取了非根樹狀節點,則會進入可編輯的狀態,讓使用者編輯節點標籤。 使用者停止編輯樹狀節點標籤之後,會評估並儲存新的標籤文字。 在此範例中,標籤文字中會將數個字元視為無效。 如果其中一個不正確字元位於標籤字串中,或字串是空的,使用者會收到錯誤通知,且標籤會傳回其先前的文字。

C#
/* 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();
     }
   }
}

備註

使用這個方法的一般案例是在 或 ContextMenu 的事件 MenuItemClick 呼叫它。

注意

只有在 的 TreeView 屬性設定為 trueLabelEdit ,這個方法才能運作。 如果 LabelEdit 設定為 false ,則會擲回例外狀況,且樹狀節點不會進入可編輯的狀態。

適用於

產品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另請參閱