Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am playing with Treeview and the AfterLabelEdit function and IM having a problem where after validation it displays the MessageBox Twice before it goes back to Editing. Anyone see what I might be doing wrong here.

C#
private void treeView1_AfterLabelEdit(object sender, System.Windows.Forms.NodeLabelEditEventArgs e)
    {
        var HostsXML = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Hosts.xml");

        XmlDocument doc = new XmlDocument();
        doc.Load(HostsXML);

        foreach (TreeNode pChild in e.Node.Parent.Nodes)
        {
            if (pChild.Text == e.Label)
            {
                // same name found, cancel the edit operation
                MessageBox.Show("That Name Cannot be Used.  Please Select a Different Name");
                e.CancelEdit = true;
                e.Node.BeginEdit();
                //treeView1.Nodes.Remove(treeView1.SelectedNode);
                return;
            }
        }

        if (e.Label != null)
        {
            if (e.Label.Length > 0)
            {
                if (String.IsNullOrEmpty(selectedNode))
                {
                    XmlNode rootNode = doc.SelectSingleNode("Servers");
                    XmlNode recordNode = rootNode.AppendChild(doc.CreateNode(XmlNodeType.Element, "Server", ""));
                    recordNode.AppendChild(doc.CreateNode(XmlNodeType.Element, "Name", "")).InnerText = e.Label;
                }
                else
                {
                    XmlElement root = doc.DocumentElement;
                    XmlNodeList xnList = doc.SelectNodes("/Servers/Server[Name ='" + selectedNode + "']");

                    foreach (XmlNode xn in xnList)
                    {
                        xn["Name"].InnerText = e.Label;
                    }
                }
            }
            else
            {
                MessageBox.Show("You Did Not Enter a Valid Name:1");
                e.CancelEdit = true;
                e.Node.BeginEdit();
                //treeView1.Nodes.Remove(treeView1.SelectedNode);
                return;
            }
        }
        else
        {
            e.CancelEdit = true;
            MessageBox.Show("You Did Not Enter a Valid Name: 2");
            e.Node.BeginEdit();
            //treeView1.Nodes.Remove(treeView1.SelectedNode);
            return;
        }

selectedNode = null;
    doc.Save(HostsXML);

    }


I have stepped through the code and confirmed that when it hits the BeginEdit() it refires the afterlabeledit a second time.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900