摘要:Treeview 節點編輯
參考別人的資料改寫了一篇Treeview 節點拖曳,因為我喝了茶就會睡不著, 所以又有了這篇。
我讓這Treeview除了移動之外,也可以複製(按住Ctrl)、刪除(按Delete)
public partial class Form1 : Form
{
bool controlKey;
bool addNode;
bool AddNode
{
set { addNode = value; }
get { return addNode; }
}
bool ControlKey
{
set
{
controlKey = value;
this.Cursor = value ? Cursors.Cross : Cursors.Default;
if (!controlKey)
if (AddNode)
AddNode = false;
}
get { return controlKey; }
}
public Form1()
{
InitializeComponent();
TreeNode treeNode1 = new TreeNode("Node1");
TreeNode treeNode2 = new TreeNode("Node2");
TreeNode treeNode3 = new TreeNode("Node3");
TreeNode treeNode4 = new TreeNode("Node0", new TreeNode[] { treeNode1, treeNode2, treeNode3 });
TreeNode treeNode5 = new TreeNode("Node6");
TreeNode treeNode6 = new TreeNode("Node4", new TreeNode[] { treeNode5 });
TreeNode treeNode7 = new TreeNode("Node5");
this.treeView1.Nodes.AddRange(new TreeNode[] { treeNode4, treeNode6, treeNode7 });
this.treeView1.ExpandAll();
this.treeView1.DragDrop += new DragEventHandler(this.treeView1_DragDrop);
this.treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag);
this.treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter);
}
void treeView1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
if (ControlKey)
AddNode = true;
}
void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
DoDragDrop(e.Item, DragDropEffects.Move);
}
private void treeView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
{
Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y)); //找出目前位置
TreeNode destinationNode = ((TreeView)sender).GetNodeAt(pt); //找出目的節點
TreeNode moveNode = (e.Data.GetData("System.Windows.Forms.TreeNode")) as TreeNode; //取出要移動的節點
if (!AddNode)
{
if (CheckForefather(moveNode, destinationNode)) //排除將父節點移到子節點的情況
{
MessageBox.Show("error!");
return;
}
moveNode.Remove(); //移去要移動的節點
}
destinationNode.Nodes.Add((TreeNode)moveNode.Clone()); //加到新節點之下
destinationNode.ExpandAll(); //展開顯示
}
} private bool CheckForefather(TreeNode fatherNode, TreeNode childNode)
{
if (fatherNode.Equals(childNode))
return true;
foreach (TreeNode tn in fatherNode.Nodes)
{
if (CheckForefather(tn, childNode))
return true;
}
return false;
}
private void treeView1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode & Keys.ControlKey) != 0)
ControlKey = true;
}
private void treeView1_KeyUp(object sender, KeyEventArgs e)
{
if ((e.KeyCode & Keys.ControlKey) != 0)
ControlKey = false;
if (e.KeyCode == Keys.Delete)
{
TreeNode tn = ((TreeView)sender).SelectedNode;
if (MessageBox.Show(String.Format("確定要刪除 {0} ?", tn.Text)) == DialogResult.OK)
tn.Remove();
}
}
}