1

我正在使用 Treeview 和 AfterLabelEdit 函数,而 IM 遇到问题,在验证后它会在返回编辑之前两次显示 MessageBox。任何人都知道我在这里可能做错了什么。

    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);

    }
4

0 回答 0