Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 439
la la lu Avatar asked Feb 06 '11 11:02

la la lu


2 Answers

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();
            }
        }
like image 152
Adrian Fâciu Avatar answered Nov 14 '22 22:11

Adrian Fâciu


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.

like image 38
Hans Passant Avatar answered Nov 14 '22 21:11

Hans Passant