using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{//添加樹形視圖子節點
this.treeView1.Nodes.AddRange(new TreeNode[] {
new TreeNode("中國直轄市", new TreeNode[] {
new TreeNode("北京市", new TreeNode[] {
new TreeNode("東城區"), new TreeNode("西城區"),new TreeNode("朝陽區")}),
new TreeNode("上海市", new TreeNode[] {new TreeNode("長寧區"),
new TreeNode("黃埔區"), new TreeNode("浦東區")}),
new TreeNode("重慶市", new TreeNode[] {
new TreeNode("長壽區", new TreeNode[] {new TreeNode("雲臺鎮"),
new TreeNode("鳳城鎮", new TreeNode[] {new TreeNode("黃桷灣"),new TreeNode("關口")})}),
new TreeNode("渝北區"),new TreeNode("北碚區")})})});
this.treeView1.AllowDrop = true;
this.treeView1.ExpandAll();
}
private void treeView1_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
{ //處理 treeView1控件ItemDrag事件
//設置拖放類型為移動
DoDragDrop(e.Item, DragDropEffects.Move);
}
private void treeView1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{//處理 treeView1控件DragEnter事件
//獲取節點的數據內容
object MyData = e.Data.GetData(typeof(TreeNode));
//如果節點有數據,拖放目標允許移動
if (MyData != null)
{
e.Effect = DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
TreeView MyTreeView = (TreeView)sender;
TreeNode MyNode = MyTreeView.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));
if (MyNode != null)
{ //改變進入節點的背景色
MyNode.BackColor = Color.Blue;
//保存此節點,進入下壹個時還原背景色
MyOldNode = MyNode;
}
}
private void treeView1_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
{//處理 treeView1控件DragOver事件
//修改鼠標進入節點的背景色,還原上壹個節點的背景色
TreeView MyTreeView = (TreeView)sender;
TreeNode MyNode = MyTreeView.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));
if ((MyNode != null) && (MyNode != MyOldNode))
{
MyOldNode.BackColor = Color.White;
MyNode.BackColor = Color.Blue;
MyOldNode = MyNode;
}
}
private void treeView1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{//處理 treeView1控件DragDrop事件
TreeNode MyNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
TreeView MyTreeView = (TreeView)sender;
//得到當前鼠標進入的節點
TreeNode MyTargetNode = MyTreeView.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));
if (MyTargetNode != null)
{
TreeNode MyTargetParent = MyTargetNode.Parent;
//刪除拖放的節點
MyNode.Remove();
//添加到目標節點
MyTargetNode.Nodes.Add(MyNode);
MyTargetNode.BackColor = Color.White;
MyTreeView.SelectedNode = MyTargetNode;
}
}
//保存前壹個鼠標進入的節點
private TreeNode MyOldNode;
}
}