问题
I was wondering if it was possible with a TreeView in a windows form to add or remove a level?
For example: my treeview is like this to begin with:
ParentNode
| Child1
| Child2
if user clicks on a button to add a level to Child2 it becomes:
ParentNode
| Child1
| | Child1.1
There is a a Node.Level
function but only usable to get the level and not to set it.
EDIT:
The nodes are built automatically, the level is assigned depending on the style of an excel cell. The problem is, it happens that the created node is not at it's correct place because the excel file is not well made. So I see 2 options o resolve this problem:
1- the user modifies the excel file directly
2- I create a Move Left
Move Right
button on a selection of nodes.
I'd like to offer the 2nd possibility.
Here's the code I used to build the nodes:
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;
}
}
}
回答1:
I had to change my answer completely to the changed question. This seems to do the job in my tests. It moves the selected node to a new level, under the one that was just above it. It needs more checks offcourse to make sure your not moving nodes to oblivion...
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);
}
}
来源:https://stackoverflow.com/questions/42346249/adding-or-removing-a-level-to-a-treenode