ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

C# TreeView problem

(1/1)

Ruffnekk:
Hi,

I'm having a bit of a problem in C#. I have an MDI Form that contains a Treeview (directly on the form, docked left). The remaining space contains some MDI child windows.

When I programmatically add a treenode to the treeview at runtime, I want the user to be able to edit the default label text of the new node immediately. This saves the trouble of either a dialog to prompt for the name of the new element, or having the user click the node to change the name manually. The code I have so far:


--- ---        private void SelectAndEditNode(string id)
        {
            TreeNode[] temp = tvwProjects.Nodes.Find(id, true);
            if (temp != null && temp.Length > 0)
            {
                tvwProjects.SelectedNode = temp[0];
                tvwProjects.SelectedNode.EnsureVisible();
                tvwProjects.SelectedNode.BeginEdit();
            }
        }

The string id is the unique key and the Find function theoretically always returns one node. The code works fine, the node gets selected, is visible and the label of the node is in edit mode so the user can start typing a name.

The problem is, when I start typing a name, the label accepts one character and then the last active MDI child window is activated and the rest of what I type is put in the MDI child window:

C# TreeView problem

If there are no MDI child windows then it works fine. I tried tvwProjects.Focus() before calling BeginEdit() but that makes no difference.

Any one got an idea?

wmain:
What if you disabled the MDI forms, if any, before enabling the edit mode of the new node. Then on the node's changed event you re-enable the MDI forms?

Code:

--- ---using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TreeviewNodeEditMDI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Form2 childform = new Form2();
            childform.MdiParent = this;
            childform.Visible = true;
            childform.Enabled = false;
            TreeNode node = this.treeView1.Nodes.Add("Test");
            treeView1.LabelEdit = true;
            node.EnsureVisible();
            node.BeginEdit();
        }

        private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            foreach (Form child in this.MdiChildren)
                child.Enabled = true;
        }
    }
}

Ruffnekk:
Thanks for the tip! I'll check it out when I have time :) I might work I think!

Navigation

[0] Message Index

Go to full version