向 TreeNode 添加或删除级别

Adding or Removing a level to a TreeNode

我想知道是否可以使用 windows 形式的 TreeView 添加或删除级别?

例如: 我的树视图是这样开始的:

ParentNode  
|    Child1  
|    Child2  

如果用户点击一个按钮来为 Child2 添加一个级别,它将变为:

ParentNode   
|    Child1  
|    |    Child1.1  

有一个 Node.Level 函数,但只能用于获取级别,不能用于设置级别。

编辑:
节点是自动构建的,级别是根据 excel 单元格的样式分配的。问题是,碰巧创建的节点不在正确的位置,因为 excel 文件制作不当。所以我看到 2 个选项可以解决这个问题:

1-用户直接修改excel文件
2- 我在选择的节点上创建了一个 Move Left Move Right 按钮。

我想提供第二种可能性。

这是我用来构建节点的代码:

public static void AddNodes(Excel.Application app,
                                    TreeView treeView)
    {
        Excel.Range selection = app.Selection;

        ArrayList style = new ArrayList();

        TreeNode parentNode = treeView.SelectedNode;

        //Selected Node => Last used node
        for (int i = 1; i <= selection.Rows.Count; i++)
        {
            TreeNode tn;

            int fontSize = Convert.ToInt32(selection.Cells[i].Font.Size);

            if (!style.Contains(fontSize))
            { 
                style.Add(fontSize); 
            }

            else if (style[style.Count - 1].Equals(fontSize))
            {
                try
                { 
                    treeView.SelectedNode = treeView.SelectedNode.Parent; 
                }
                catch (Exception x)
                { 
                    ErrorBox(x); 
                }
            }

            else
            {
                int indexPreviousCellofSameColor = style.IndexOf(fontSize);

                //Select TN parent
                for (int j = 1; j <= (style.Count - indexPreviousCellofSameFont); j++)
                { treeView.SelectedNode = treeView.SelectedNode.Parent; }

                style.RemoveRange(indexPreviousCellofSameFont + 1, style.Count - indexPreviousCellofSameFont - 1);
            }

            if (selection.Cells[i].Value2 == null)
            {
                //if empty cell, do something ... or nothing
                treeView.SelectedNode = treeView.SelectedNode.LastNode;
            }
            else
            {
                //Add new TN to parent - TN object corresponds to excel cell
                tn = new TreeNode()
                {
                    Text = selection.Cells[i].Value2,
                    Tag = selection.Cells[i],
                };
                treeView.SelectedNode.Nodes.Add(tn);
                tn.ToolTipText = tn.Level.ToString();

                //selected TN => created TN
                treeView.SelectedNode = tn;
            }
        }
    }

我不得不完全改变我对改变后的问题的回答。 这似乎在我的测试中完成了工作。它将选定的节点移动到一个新的级别,在它上面的级别之下。 它需要更多的检查以确保您不会将节点移动到遗忘...

private void button1_Click(object sender, EventArgs e)
{
    TreeNode selected = treeViewFilter.SelectedNode;
    TreeNode parent = selected.Parent;

    // find the node just above the selected node
    TreeNode prior = parent.Nodes[selected.Index - 1];

    if (parent != prior)
    {
        treeViewFilter.Nodes.Remove(selected);
        prior.Nodes.Add(selected);
    }
}