TREEVIEW节点拖拽
假设把A节点往B节点上拖拽
那么
A 为Node1,B为Node2
private void Form1_Load(object sender, EventArgs e)
{
treeView1.AllowDrop = true;
treeView1.HideSelection = false;
} |
private TreeNode node1 = null; //node1 当前选中的那个节点
private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
node1 = (TreeNode)e.Item;
DoDragDrop(e.Item, DragDropEffects.Move);
} |
private void treeView1_DragOver(object sender, DragEventArgs e)
{
TreeNode node2 = treeView1.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));
//节点2不存在
//节点1 = 节点2
//节点1 往它的父一级节点拖拽
if ((node2 == null) || (node1 == node2) || (node1.Parent == node2))
{
treeView1.SelectedNode = node1;
SetTreeNodeColorDefault();
e.Effect = DragDropEffects.None;
return;
}
else
{
e.Effect = DragDropEffects.Move;
treeView1.SelectedNode = node2;
SetTreeNodeColorBlue();
//当一个父节点往它的子节点中拖拽时
while (node2.Parent != null)
{
if (node2.Parent == node1)
{
e.Effect = DragDropEffects.None;
return;
}
node2 = node2.Parent;
}
}
}
|
private void treeView1_DragDrop(object sender, DragEventArgs e)
{
TreeNode node2 = treeView1.GetNodeAt( treeView1.PointToClient(new Point(e.X, e.Y)) );
if (node1 != node2)
{
if (node1.Parent != node2)
{
textBox1.Text = textBox3.Text + "\\" + node1.FullPath;
textBox2.Text = textBox3.Text + "\\" + node2.FullPath;
///MessageBox.Show("Finished");
if (node1.Parent == null)
treeView1.Nodes.Remove(node1);
else
node1.Parent.Nodes.Remove(node1);
node2.Nodes.Add(node1);
node2.Expand();
}
}
} |
//设置颜色部分
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
SetTreeNodeColorDefault();
} |
private void SetTreeNodeColorBlue()
{
if (node1 != null)
{
node1.BackColor = Color.FromArgb(51, 153, 255);//蓝色
node1.ForeColor = Color.White;
}
}
|
private void SetTreeNodeColorDefault()
{
if (node1 != null)
{
node1.BackColor = SystemColors.Window;
node1.ForeColor = Color.Black;
}
}
|
附件列表