您的目的地Treeview
更改TreeViewDragDrop
:
private void treeView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
TreeNode NewNode;
if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
{
NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
if (!(sender as TreeView).Nodes.Contains(NewNode))
{
//Add the droped node
List<TreeNode> tt = new List<TreeNode>();
TreeNode tn = (TreeNode)NewNode.Clone();
tt.Add(tn);
//Prepare node with it's parents until the root note
while ((TreeNode)NewNode.Parent is TreeNode)
{
TreeNode tnp = (TreeNode)NewNode.Parent.Clone();
//prevent siblings to be added
tnp.Nodes.Clear();
tt.Add(tnp);
NewNode = NewNode.Parent;
}
//Construct the structure of the treenote to be added to the treeview
for (int i = tt.Count - 1; i > 0; i--)
{
tt[i].Nodes.Add(tt[i - 1]);
}
/*Add the whole structured treenode to the treeview*/
TreeNode rootnote = ExistNotes((sender as TreeView), tt[tt.Count - 1]);
if (rootnote != null)//Root node exists, add to the existing node
{
foreach (TreeNode tsub in tt[tt.Count - 1].Nodes)
{
AddNote(rootnote, tsub);
}
}
else//Root node not exist, add to the treeview as new node.
{
(sender as TreeView).Nodes.Add(tt[tt.Count - 1]);
}
// NewNode.Remove();
}
}
}
輔助功能:
/// <summary>
/// Recursive function to add node
/// </summary>
/// <param name="tnbase">RootNode</param>
/// <param name="tn">Node to be added</param>
private void AddNode(TreeNode tnbase, TreeNode tn)
{
bool exists = false;
foreach (TreeNode rt in tnbase.Nodes)
{
if (this.IsNodesEquals(rt, tn))
{
foreach (TreeNode srt in tn.Nodes)
{
this.AddNode(rt, srt);
}
exists = true;
}
}
if (!exists)
{
tnbase.Nodes.Add(tn);
}
}
/// <summary>
/// Get exist node from the treeview
/// </summary>
/// <param name="tv">Treeview to check</param>
/// <param name="tn">Node to compare</param>
/// <returns></returns>
private TreeNode ExistNode(TreeView tv, TreeNode tn)
{
TreeNode existsnote = null;
foreach (TreeNode rt in tv.Nodes)
{
if (this.IsNodesEquals(rt, tn))
{
existsnote = rt;
}
}
return existsnote;
}
/// <summary>
/// Compare two nodes by the text
/// </summary>
/// <param name="t1">node to compare</param>
/// <param name="t2">node to compare with</param>
/// <returns></returns>
private bool IsNodesEquals(TreeNode t1, TreeNode t2)
{
return (t1 != null && t2 != null && t1.Text == t2.Text);
}
這是一個小到具體的您的具體情況。用一種我從未使用過的技術的語言。我有點想法,但仍然無法找到一種方法來解釋我的情況。不管怎麼說,還是要謝謝你 – phadaphunk