当我的页面打开时,它运行此方法:
private void PrintRecursive(TreeNode treeNode, string problemValue)
{
// Print the node.
System.Diagnostics.Debug.WriteLine(treeNode.Text);
if (treeNode.Value == problemValue.Split(':')[0])
{
treeNode.Checked = true;
// Then expand the SelectedNode and ALL its parents until no parent found
treeNode.Expand();
while (treeNode.Parent != null)
{
treeNode = treeNode.Parent;
treeNode.Expand();
}
if (problemValue.Contains(":"))
treeNode.Text += problemValue.Split(':')[1];
return;
}
// Print each node recursively.
foreach (TreeNode tn in treeNode.ChildNodes)
{
PrintRecursive(tn, problemValue);
}
}
treeNode.Checked = true
工作正常!
treeNode.Expand()
工作得很棒!
然而treeNode.Text += problemValue.Split(':')[1];
什么也没做!
problemValue
的值为"111:someproblem"
我做错了什么?
答案 0 :(得分:1)
你需要移动
if (problemValue.Contains(":"))
treeNode.Text += problemValue.Split(':')[1];
在while语句之上。
问题在于,在扩展父节点时,您正在更新treeNode的值,因此当您尝试设置treeNode的文本时,您实际上处于其中一个父节点。
答案 1 :(得分:1)
如果您想了解如何执行此操作,请查看此前的StackOverFlow发布以及有关如何枚举TreeNodes的其他提示Implementing IEnumerable
如果您想要打印TreeNodes,请递归查看此示例
private void PrintRecursive(TreeNode treeNode)
{
// Print the node.
System.Diagnostics.Debug.WriteLine(treeNode.Text);
MessageBox.Show(treeNode.Text);
// Print each node recursively.
foreach (TreeNode tn in treeNode.Nodes)
{
PrintRecursive(tn);
}
}
// Call the procedure using the TreeView.
private void CallRecursive(TreeView treeView)
{
// Print each node recursively.
TreeNodeCollection nodes = treeView.Nodes;
foreach (TreeNode n in nodes)
{
PrintRecursive(n);
}
}
如果您想以IEmumerable的方式执行此操作,请尝试以下
public static class Extensions
{
public static IEnumerable<T> GetRecursively<T>(this IEnumerable collection,
Func<T, IEnumerable> selector)
{
foreach (var item in collection.OfType<T>())
{
yield return item;
IEnumerable<T> children = selector(item).GetRecursively(selector);
foreach (var child in children)
{
yield return child;
}
}
}
}
以下是如何使用它的示例
TreeView view = new TreeView();
// ...
IEnumerable<TreeNode> nodes = view.Nodes.
.GetRecursively<TreeNode>(item => item.Nodes);