本文實例講述了C#搜索TreeView子節點,保留父節點的方法。分享給大家供大家參考。具體如下:
C# 搜索TreeView子節點保留父節點:
private void selectNodeByName(string name)
{
//重新生生成樹,
InitTvCatalog();
//刪除節點
selectNode(tvCatalog.Nodes, name);
}
private void selectNode(TreeNodeCollection nodes, string name)
{
bool del = true;
for (int i = nodes.Count - 1; i >= 0; i--)
{
TreeNode node = nodes[i];
del = true;
if (node.Nodes.Count != 0)
{
selectNode(node.Nodes, name);
}
if (node.Text.StartsWith(name, StringComparison.OrdinalIgnoreCase))
{
del = false;
}
else
{
del = true;
}
if (del && node.Nodes.Count == 0)
{
node.Remove();
}
}
tvCatalog.ExpandAll();
}
WPF搜索TreeView子節點保留父節點:
private void selectNodeByName(string name)
{
//重新生生成樹,
method = new Common.PublicMethod();
method.TreeViewLoad();
//刪除節點
selectNode(RegimeSetting.Common.StaticVariables.treeView.Items, name);
method = null;
}
private void selectNode(ItemCollection nodes, string name)
{
bool del = true;
for (int i = nodes.Count - 1; i >= 0; i--)
{
TreeViewItem node = nodes[i] as TreeViewItem;
del = true;
if (node.Items.Count != 0)
{
selectNode(node.Items, name);
}
if (node.Header.ToString().StartsWith(name, StringComparison.OrdinalIgnoreCase))
{
del = false;
}
else
{
del = true;
}
if (del && node.Items.Count == 0)
{
if ((node.Parent as TreeViewItem) != null)
(node.Parent as TreeViewItem).Items.Remove(node);
else
(node.Parent as TreeView).Items.Remove(node);
}
}
(RegimeSetting.Common.StaticVariables.treeView.Items[0] as TreeViewItem).IsExpanded = true;
}