我看到很多帖子都在问一个与此类似的问题,但似乎没有人回答这个问题。我有这样的供应商的TreeView:
Soda
Regular
SmallCan
SmallBottle
Diet
SmallCan
Water
Regular
EcoBottle
我创建了一个上下文菜单,允许用户重命名所选节点,但是如果它生成重复的节点名称,则无法找到强制执行该操作的方法,要么拒绝更改,要么将节点文本恢复为先前的值。这是上下文更改事件和处理强制执行的方法:
private void contextMenuRename_Click(object sender, System.EventArgs e)
{
restoreNode = treProducts.SelectedNode;
treProducts.LabelEdit = true;
if (!treProducts.SelectedNode.IsEditing)
{
treProducts.SelectedNode.BeginEdit();
}
enforceNoTreeDuplicates();
}
private void enforceNoTreeDuplicates()
{
nodeNames.Clear();
if (treProducts.SelectedNode.Level != 0)
{
foreach (TreeNode node in treProducts.SelectedNode.Parent.Nodes)
{
nodeNames.Add(node.Text);
}
}
else
{
foreach (TreeNode node in treProducts.Nodes)
{
nodeNames.Add(node.Text);
}
}
int countDuplicates = 0;
foreach (string nodeName in nodeNames)
{
if (restoreNode.Text == nodeName)
{
countDuplicates++;
}
if (countDuplicates > 1)
{
treProducts.SelectedNode = restoreNode;
}
}
}
但是,如果enforceNoTreeDuplicates()方法在那里,则BeginEdit()似乎不会运行。有没有更好的方法来处理所选节点的编辑,或者enforceNoTreeDuplicates()方法有问题吗?
答案 0 :(得分:1)
通常,你会使用AfterLabelEdit,它有一个取消编辑的选项:
void treProducts_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {
foreach (TreeNode tn in e.Node.Parent.Nodes) {
if (tn.Text == e.Label) {
e.CancelEdit = true;
}
}
}