我正在尝试使用以下代码将树视图(完全)的整个树(完全是所有节点)复制到另一个树视图中:
TreeNodeCollection myTreeNodeCollection = treeView1.Nodes;
TreeNode[] myTreeNodeArray = new TreeNode[treeView1.Nodes.Count];
treeView1.Nodes.CopyTo(myTreeNodeArray, 0);
treeView2.Nodes.AddRange(myTreeNodeArray);
但这不允许我这样做,它要求删除源treeview中的节点或使用它克隆!我怎样才能做到这一点?我不希望我的源treeview在这个过程中丢失任何东西。
**更新** 好吧,我发现了一个复杂的代码(对我来说!!),但我怎么能用它?
public static T DeepTreeCopy<T>(T obj)
{
object result = null;
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
result = (T)formatter.Deserialize(ms); ms.Close();
}
return (T)result;
}
答案 0 :(得分:12)
试试这个
public void Copy(TreeView treeview1, TreeView treeview2)
{
TreeNode newTn;
foreach (TreeNode tn in treeview1.Nodes)
{
newTn = new TreeNode(tn.Text, tn.Value);
CopyChilds(newTn, tn);
treeview2.Nodes.Add(newTn);
}
}
public void CopyChilds(TreeNode parent, TreeNode willCopied)
{
TreeNode newTn;
foreach (TreeNode tn in willCopied.ChildNodes)
{
newTn = new TreeNode(tn.Text, tn.Value);
parent.ChildNodes.Add(newTn);
}
}
我的问候
答案 1 :(得分:8)
与MohD的答案一样,但是通过递归来获取所有节点。 (子节点的节点)
public void CopyTreeNodes(TreeView treeview1, TreeView treeview2)
{
TreeNode newTn;
foreach (TreeNode tn in treeview1.Nodes)
{
newTn = new TreeNode(tn.Text, tn.ImageIndex, tn.SelectedImageIndex);
CopyChildren(newTn, tn);
treeview2.Nodes.Add(newTn);
}
}
public void CopyChildren(TreeNode parent, TreeNode original)
{
TreeNode newTn;
foreach (TreeNode tn in original.Nodes)
{
newTn = new TreeNode(tn.Text, tn.ImageIndex, tn.SelectedImageIndex);
parent.Nodes.Add(newTn);
CopyChildren(newTn, tn);
}
}
答案 2 :(得分:5)
使用node.Clone()函数也可以...
foreach (TreeNode node in treeViewSource.Nodes)
{
treeViewTarget.Nodes.Add((TreeNode)node.Clone());
}
添加根节点有助于确保&#34; PlusMinus&#34;功能是可见的。
TreeNode rootNode = new TreeNode("Root Node");
treeViewTarget.Nodes.Add(rootNode);
foreach (TreeNode node in treeViewSource.Nodes)
{
rootNode.Nodes.Add((TreeNode)node.Clone());
}
rootNode.Expand();
答案 3 :(得分:-1)
您可以在所需级别使用此
public void RootCopy(TreeView treeview1, TreeView treeview2)
{
TreeNode newNode;
foreach (TreeNode tnode in treeview1.Nodes)
{
newNode = new TreeNode(tnode.Text);
treeview2.Nodes.Add(newNode);
if (tnode.Nodes.Count != 0)
{
int _1index = tnode.Index;
ChildsCopyLevel2(_1index, treeview1, treeview2);
}
}
}
public void ChildsCopyLevel2(int index1, TreeView TV1, TreeView TV2)
{
foreach (TreeNode Tnode in TV1.Nodes[index1].Nodes)
{
string Childtext = Tnode.Text;
TV2.Nodes[index1].Nodes.Add(Childtext);
if (Tnode.Nodes.Count != 0)
{// ChildsCopyLevel3(Tnode.Nodes.Count, TV1, TV2);
int _2index = Tnode.Index;
ChildsCopyLevel3(index1, _2index, TV1, TV2);
}
}
}
public void ChildsCopyLevel3(int index1, int index2, TreeView TV1, TreeView TV2)
{
foreach (TreeNode Tnode in TV1.Nodes[index1].Nodes[index2].Nodes)
{
string Childtext = Tnode.Text;
TV2.Nodes[index1].Nodes[index2].Nodes.Add(Childtext);
}
}