c# - 在树视图中删除树节点而不删除它们的子节点 [英] Deleting treenodes in treeview without deleting their children in c#

查看:50
本文介绍了c# - 在树视图中删除树节点而不删除它们的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 c# 的树视图中删除一个特定节点.它应该执行以下操作:

I am trying to delete one specific node in a treeview in c#. It is supposed to do the following:

假设root-->path1-->path1.1-->path1.2"是树视图中的路径之一.删除节点path1"时,应该只删除这个节点,而不是path1.1"和path1.2".根节点应该成为这两个节点的父节点.

Let's say "root-->path1-->path1.1-->path1.2" is one of the paths in the treeview. When deleting the node "path1", it is supposed to delete only this node and not also "path1.1" and "path1.2". The root node is supposed to become parent of these two nodes.

到目前为止,我使用了这段代码来删除节点及其所有子节点:

So far I used this code which deletes the node with all its children:

treeView1.Nodes.Remove(node);

有什么办法可以做到这一点吗?

Is there any way I can do this?

推荐答案

您可以在删除这些节点的当前父级之前更改这些节点的父级.例如:

You can change those nodes' parent before deleting their current parent. For example:

var selected = this.treeView1.SelectedNode;
TreeNodeCollection container;
if (selected.Parent == null)
    container = treeView1.Nodes;
else
    container = selected.Parent.Nodes;
var list = selected.Nodes.Cast<TreeNode>().ToList();
foreach (TreeNode n in list)
{
    n.Remove();
    container.Add(n);
}
selected.Remove();

这篇关于c# - 在树视图中删除树节点而不删除它们的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆