Tree
|
A-A1
-A2
|
B-B1
-B2
-B3
|
C-C1
-C2
private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
foreach (TreeNode tn in treeView1.Nodes)
{
if (!tn.Equals(e.Node) && tn.Text.ToUpper() == e.Label.ToUpper() )
{
MessageBox.Show("Name already available for parent. Cannot give same name.", "Rename element");
e.CancelEdit = true;
return;
}
}
string l_strOldDisplayName = treeView1.SelectedNode.Text;
this.BeginInvoke(new Action(() => RenameTreeElement(l_strOldDisplayName, e.Node)));
treeView1.LabelEdit = false;
treeView1.SelectedNode.EndEdit(false);
}
private void RenameElement(string f_strOldDisplayName, TreeNode updatedNode)
{
foreach (TreeNode currentNode in treeView1.Nodes)
{
if (currentNode.Level == 0)
{
if (updatedNode.Text == currentNode.Text)
{
MessageBox.Show("Name already available for parent. Cannot give same name.", "Rename element");
return;
}
}
}
}
我在0级(A,B,C)重命名树节点(A到B),但是当时我想在树视图中显示B我要显示消息“名称已经可用于父级。不能给出相同的名称。“
因为我已经写了上面的代码,但是当我给父节点名称'A'给树中任何不允许的子节点说'A'时它是失败的。它应该允许因为父名称可能在子节点中重复< / p>
更新了代码........
void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {
foreach (TreeNode tn in treeView1.Nodes) {
if (!tn.Equals(e.Node) && tn.Text == e.Label&& !IsChildNodeHaveSameName(e.Label, e.Node)) {
MessageBox.Show("Name already in use.");
e.CancelEdit = true;
}
}
}
private bool IsChildNodeHaveSameName(string newName)
{//if new parent node name is under child node then skip
foreach (var node in Collect(treeView1.Nodes))
{
if (node.Text.ToUpper() == newName.ToUpper())
{
return true;
}
}
return false;
}
IEnumerable<TreeNode> Collect(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
yield return node;
foreach (var child in Collect(node.Nodes))
yield return child;
}
}
答案 0 :(得分:1)
e.Label
属性为您提供用户在浮动标签中写入的文本。有了它,您可以将代码简化为:
void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {
if (e.Node.Level == 0) {
foreach (TreeNode tn in treeView1.Nodes) {
if (!tn.Equals(e.Node) && tn.Text == e.Label) {
MessageBox.Show("Name already in use.");
e.CancelEdit = true;
}
}
}
}