无论如何得到TreeNode在ToolStripMenuItem单击处理程序中打开ContextMenuStrip?

时间:2012-08-27 09:50:37

标签: c# treeview treenode contextmenustrip

我有不同级别TreeNodes的TreeView 我向所有父TreeNode添加了相同的ContextMenuStrip,我希望通过打开ContextMenuStrip并按“全部删除”来删除所有子TreeNode

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
}

我不知道如何获得用户点击打开菜单的TreeNode 有什么想法吗?

3 个答案:

答案 0 :(得分:4)

您可以使用树视图中的HitTest()方法查找节点,如下所示

var hitTest = treeView1.HitTest(treeView1.PointToClient(new Point(contextMenuStrip1.Left, contextMenuStrip1.Top)));
if (hitTest.Node != null)
{
    // Place your code to delete nodes
}

或者您可以关注鼠标单击的节点并使用treeView1.SelectedNode属性来操作菜单项。通过这种方式,您可以避免在每个上下文菜单项上使用HitTest()...

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    var hitTest = treeView1.HitTest(treeView1.PointToClient(e.Location));
    if (hitTest.Node != null)
    {
         treeView1.SelectedNode = hitTest.Node;
    }
}

答案 1 :(得分:2)

目前尚不清楚您正在尝试使用上述代码。但是要做你需要的(即右键点击TreeNode并启动一个特定的ContextMenuStrip)使用代码simalar

private void customTreeViewSql_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    // Ensure selected node is selected.
    treeView.BeginUpdate();
    this.treeView.SelectedNode = e.Node;
    try
    {
        if (e.Node.Level == 0)
        {
            if (e.Button == MouseButtons.Right)
                contextMenuStripA.Show(MousePosition);
        }
        else if (e.Node.Level == 1)
        {
            if (e.Button == MouseButtons.Right)
                contextMenuStripB.Show(MousePosition);
        }
    }
    finally
    {
        this.treeView.EndUpdate();
    }
}

然后,您可以在ContexMenu中设置click事件,以根据所选的子节点删除所有子节点

private void toolStripMenuDeleteAll_Click(object sender, EventArgs e)
{
    TreeNode treeNode = this.treeView.SelectedNode;
    foreach (TreeNode n in treeNode.Nodes)
        n.Remove();
}

我希望这会有所帮助。

答案 2 :(得分:2)

我认为这比Krishnakumar的代码清晰易懂。 你可以将'toolStripMenuDeleteAll'设置为仅一些treenodes而不是所有这些。 此代码根本不会更改Selected TreeNode。

欢迎 CHADASH

TreeNode LastClickedTreeNode;
private void customTreeViewSql_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    // update last treenode clicked.
    LastClickedTreeNode = e.Node;
}

private void toolStripMenuDeleteAll_Click(object sender, EventArgs e)
{
    foreach (TreeNode n in LastClickedTreeNode.Nodes)
        n.Remove();
}