la la lu
la la lu

Reputation: 123

How can I disable node renaming for the TreeView in WinForms?

Is it possible to disable the option to get into "Rename" mode when clicking on a tree-node?
I don't want to disable renaming completely, only to not allow doing it by clicking on the node.

Upvotes: 5

Views: 6282

Answers (2)

Hans Passant
Hans Passant

Reputation: 941457

You'll have to turn the LabelEdit property on and off as needed:

    private void startLabelEdit() {
        treeView1.LabelEdit = true;
        treeView1.SelectedNode.BeginEdit();
    }

    private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {
        treeView1.LabelEdit = false;
    }

Beware that this has side effects, the LabelEdit property is a style flag for the native Windows control. Changing it requires completely destroying the window and re-creating it from scratch. The most visible side-effect is a small flicker when the window redraws itself after getting created. There could be other ones, I didn't see anything go wrong myself.

Upvotes: 4

Adrian Fâciu
Adrian Fâciu

Reputation: 12552

I don't know why would you change the default behavior, but anyway here's a possible solution to edit the nodes with LabelEdit set to true.

Just catch BeforeLabelEdit event and cancel it, unless your specific action occurred. The following code does this for F2 key press:

        bool _allowNodeRenaming;

        private void treeView1_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (!_allowNodeRenaming)
            {
                e.CancelEdit = true;
            }

            _allowNodeRenaming = false;
        }

        private void treeView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F2)
            {
                _allowNodeRenaming = true;
                treeView1.SelectedNode.BeginEdit();
            }
        }

Upvotes: 6

Related Questions