本文介绍了将所有treeView父级和子级复制到另一个treeView c# WinForms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用此代码将树视图的整个树(完全是所有节点)(完全)复制到另一个树视图:
I am trying to copy the entire tree (exactly all nodes) of a treeview (completely) to another treeview using this code:
TreeNodeCollection myTreeNodeCollection = treeView1.Nodes;
TreeNode[] myTreeNodeArray = new TreeNode[treeView1.Nodes.Count];
treeView1.Nodes.CopyTo(myTreeNodeArray, 0);
treeView2.Nodes.AddRange(myTreeNodeArray);
但这不允许我这样做,它要求删除源树视图中的节点或使用它克隆!我怎样才能做到这一点?我不希望我的源树视图在这个过程中丢失任何东西.
But this does not allow me to do so, it asks to either delete the nodes in source treeview or use it Clone! How can I do that? I dont want my source treeview to lose anything in this process.
** 更新 **好吧,伙计们,我找到了一个复杂的代码(对我来说!!)但是我该如何使用它呢?
** UPDATE ** Ok guys I found a complicated code (for me!!) but how can I use this?
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;
}
推荐答案
试试这个
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);
}
}
我的问候
这篇关于将所有treeView父级和子级复制到另一个treeView c# WinForms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!