在C#中实现TreeView节点的拖放操作

//从TreeView2控件中,拖放节点到TreeView1中

 


 

using System;

 

using System.Collections.Generic;

 

using System.ComponentModel;

 

using System.Data;

 

using System.Drawing;

 

using System.Text;

 

using System.Windows.Forms;

 

 

namespace TreeViewDrap

 

{

 

public partial class Form1 : Form

 


{

 

public Form1()

 


{

 


InitializeComponent();

 


}

 

 

private void treeView1_DragEnter(object sender, DragEventArgs e)

 


{

 

if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))

 


{

 


e.Effect =
DragDropEffects.Copy;

 

 


}

 

else

 


{

 


e.Effect =
DragDropEffects.None;

 


}

 


}

 

 

private void Form1_Load(object sender, EventArgs e)

 


{

 

this.treeView1.AllowDrop = true;

 

this.treeView2.AllowDrop = true;

 

this.treeView2.ExpandAll();

 

this.treeView1.ExpandAll();

 


}

 

 

private void treeView1_DragDrop(object sender, DragEventArgs e)

 


{

 

TreeNode TempNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");

 

if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))

 


{

 

Point pt;

 

TreeNode DestNode;

 


pt = ((
TreeView)sender).PointToClient(new Point(e.X, e.Y));

 


DestNode = ((
TreeView)sender).GetNodeAt(pt);

 

if (DestNode.TreeView != TempNode.TreeView)

 


{

 


DestNode.Nodes.Add((
TreeNode)TempNode.Clone());

 


DestNode.Expand();

 


}

 


}

 


}

 

 

private void treeView2_ItemDrag(object sender, ItemDragEventArgs e)

 


{

 

int itemIndex;

 


itemIndex =
this.treeView2.SelectedNode.Index;

 



if (itemIndex >= 0)

 


{

 


treeView2.DoDragDrop(treeView2.SelectedNode,
DragDropEffects.Copy);

 


}

 


}

 


}

 

}

 

posted on 2009-03-23 12:59  J-Pei  阅读(854)  评论(0编辑  收藏  举报

导航