I have TreeView with different level TreeNodes
I added same ContextMenuStrip to all parent TreeNodes and i want to get possibility to delete all child TreeNodes by opening that ContextMenuStrip and pressing "Delete all"
private void btn_delete_all_objects_Click(object sender, EventArgs e)
{
ToolStripMenuItem tsmi = (ToolStripMenuItem)sender; //that way i receive button "Delete all"
ContextMenuStrip cms = (ContextMenuStrip)tsmi.Owner; //this is ContextMenuStrip where this button...
TreeView tw = (TreeView)cms.SourceControl; //i can get TreeView :( BUT I NEED TreeNode!
TreeNode tn = tw.SelectedNode; //bah... if i select some of child nodes, then right click to open menu on parent, selected node is still that child
}
And i don't know how to get that TreeNode where user clicked to open menu
Any ideas?
you can use HitTest()
method from tree view to find the node, like this,
var hitTest = treeView1.HitTest(treeView1.PointToClient(new Point(contextMenuStrip1.Left, contextMenuStrip1.Top)));
if (hitTest.Node != null)
{
// Place your code to delete nodes
}
or you can focus the node on which the mouse clicked and use treeView1.SelectedNode
property to manipulate in your menu items. By this way you can avoid using HitTest() on every context menu item...
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
var hitTest = treeView1.HitTest(treeView1.PointToClient(e.Location));
if (hitTest.Node != null)
{
treeView1.SelectedNode = hitTest.Node;
}
}