此函数仅在treeview中找到第一个节点,该节点包含SearchText。
private TreeNode SearchNode(string SearchText,TreeNode StartNode)
{
TreeNode node=null;
while (StartNode!= null)
{
if (StartNode.Text.ToLower().Contains(SearchText.ToLower()))
{
node = StartNode;
break;
};
if (StartNode.Nodes.Count != 0)
{
node=SearchNode(SearchText, StartNode.Nodes[0]);//Recursive Search
if (node != null)
{
break;
};
};
StartNode = StartNode.NextNode;
};
return node;
}
private void button1_Click(object sender, EventArgs e)
{
string SearchText = this.textBox1.Text;
if (SearchText == "")
{
return;
};
TreeNode SelectedNode = SearchNode(SearchText, treeView1.Nodes[0]);
if (SelectedNode != null)
{
this.treeView1.SelectedNode = SelectedNode;
this.treeView1.SelectedNode.Expand();
this.treeView1.Select();
};
}我应该如何更改它,以便函数不仅能够找到第一个节点,而且能够找到所有节点,每次单击button1时,它都会找到下一个节点,直到结束,然后从开始开始?所以我不应该从TreeView1.Nodes[0],而应该从TreeView1.SelectedNode.
发布于 2012-07-17 21:35:37
下面这样的内容应该可以添加到表单代码中。
private List<TreeNode> CurrentNodeMatches = new List<TreeNode>();
private int LastNodeIndex = 0;
private string LastSearchText;
private void button1_Click(object sender, EventArgs e)
{
string searchText = this.textBox1.Text;
if (String.IsNullOrEmpty(searchText))
{
return;
};
if (LastSearchText != searchText)
{
//It's a new Search
CurrentNodeMatches.Clear();
LastSearchText = searchText;
LastNodeIndex = 0;
SearchNodes(searchText, treeView1.Nodes[0]);
}
if (LastNodeIndex >= 0 && CurrentNodeMatches.Count > 0 && LastNodeIndex < CurrentNodeMatches.Count)
{
TreeNode selectedNode = CurrentNodeMatches[LastNodeIndex];
LastNodeIndex++;
this.treeView1.SelectedNode = selectedNode;
this.treeView1.SelectedNode.Expand();
this.treeView1.Select();
}
}
private void SearchNodes(string SearchText, TreeNode StartNode)
{
TreeNode node = null;
while (StartNode != null)
{
if (StartNode.Text.ToLower().Contains(SearchText.ToLower()))
{
CurrentNodeMatches.Add(StartNode);
};
if (StartNode.Nodes.Count != 0)
{
SearchNodes(SearchText, StartNode.Nodes[0]);//Recursive Search
};
StartNode = StartNode.NextNode;
};
}这有两部分;
List<TreeNode>中List<TreeNode>页面。如果搜索已更改,请清除列表并重置索引。我已经用运行在.Net 4下的Windows测试了这一点--它通过包含搜索文本的TreeView中的每个节点进行分页,直到它到达最后一个节点为止。
发布于 2012-07-17 20:54:54
您需要创建一个节点集合(如List),并将每个已找到的节点添加到该列表中,并返回该节点,而不是单个节点。另外,您还必须删除所有break语句
发布于 2016-01-21 01:48:57
I使用此解决方案搜索树节点上的文本
int currentSearch = 0;
int loop = 0;
int found = 0;
private bool FilterTreeNode(TreeNodeCollection nodes, string keyword)
{
bool result = false;
for (int i = 0; i < nodes.Count; i++)
{
if(result)
break;
loop++;
if (currentSearch < loop)
{
currentSearch++;
if (nodes[i].Text.Contains(keyword))
{
found++;
_treeView.SelectedNode = nodes[i];
_treeView.SelectedNode.Expand();
_treeView.SelectedNode.EnsureVisible();
OnFindResult(string.Format("Current result: {0} on total {1} nodes. FilePath: {2}",
found, _treeView.GetNodeCount(true), nodes[i].Name));
return true;
}
}
result = FilterTreeNode(nodes[i].Nodes, keyword);
}
return result;
}https://stackoverflow.com/questions/11530643
复制相似问题