Tuesday, June 3, 2008

Treenodes and Context Meny

Make a tree structure with "Copy/paste" context menu....

private System.Windows.Forms.TreeView treeView1;
private ContextMenu cMenu = new ContextMenu();
TreeNode tmpNode, tNode;
Point pPt;

...

this.treeView1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseUp);

...

private void Form1_Load(object sender, System.EventArgs e)
{
cMenu.MenuItems.Add("Copy",new EventHandler(eCopy));
cMenu.MenuItems.Add("Paste", new EventHandler(ePaste));

TreeNode aNode;
aNode = treeView1.Nodes.Add("Dong");
aNode.Nodes.Add("Ning");
aNode.Nodes.Add("Yamei");

aNode = treeView1.Nodes.Add("Jing");
aNode.Nodes.Add("Yahong");
aNode.Nodes.Add("Ying");

treeView1.AllowDrop = true;
}
private void eCopy(object sender, System.EventArgs e)
{
// TreeNode tNode = treeView1.SelectedNode; //does not work.
tmpNode = treeView1.GetNodeAt(pPt);
tNode = tmpNode;
MessageBox.Show("Path is " + tNode.FullPath.ToString());
}
private void ePaste(object sender, System.EventArgs e)
{
//insert tNode to the pPt postion
TreeNode nodeTarget = treeView1.GetNodeAt(pPt);
TreeNode nodeSource = tNode;
MessageBox.Show("Path is " + nodeTarget.FullPath.ToString());
nodeTarget.Nodes.Add((TreeNode)tNode.Clone()); //needed
nodeTarget.Expand();
}

private void treeView1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
switch(e.Button)
{
case MouseButtons.Right:
cMenu.Show(treeView1, new Point(e.X,e.Y));
pPt = new Point(e.X,e.Y);
break;
default:
break;
}
}

No comments: