我正在所有 treeview的父级和子级节点中以递归方式搜索文本,但该文本无法正常工作。
请参阅下面的代码,其中我在父母和子女的所有节点中搜索文本,但无法正常工作。请指导我我需要修理的东西。
private void txtSerach_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (txtSerach.Text.Trim() != "")
{
if (treeView1.Nodes.Count > 0)
{
nodefound = false;
TreeNodeCollection nodes = treeView1.Nodes;
foreach (TreeNode n in nodes)
{
if (!nodefound)
PrintRecursive(n);
else
return;
}
}
}
}
}
bool nodefound = false;
private void PrintRecursive(TreeNode treeNode)
{
if (treeNode.Text.ToUpper().Contains(txtSerach.Text.ToUpper().ToString()))
{
treeView1.SelectedNode = treeNode;
treeView1.SelectedNode.Expand();
treeView1.Focus();
nodefound = true;
return;
}
foreach (TreeNode tn in treeNode.Nodes)
{
PrintRecursive(tn);
}
}
应在所有父级和所有嵌套节点中搜索文本,如果找到,则应选择该节点。
谢谢
答案 0 :(得分:1)
尝试。
private void txtSerach_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (txtSearch.Text.Trim() != "")
{
if (treeView1.Nodes.Count > 0)
{
TreeNodeCollection nodes = treeView1.Nodes;
var selected = PrintRecursive(nodes, txtSearch.Text);
treeView1.SelectedNode = selected;
treeView1.SelectedNode.Expand();
treeView1.Focus();
}
}
}
}
private TreeNode PrintRecursive(TreeNodeCollection parents, string txtSearch)
{
foreach (TreeNode node in parents)
{
if (node.Nodes != null && node.Nodes.Count > 0)
{
var rs = PrintRecursive(node.Nodes, txtSearch);
if (rs != null)
{
return rs;
}
}
if (node.Text.ToUpper().Contains(txtSearch.ToUpper().ToString()))
{
return node;
}
}
return null;
}
答案 1 :(得分:1)
此代码从树中找到密钥:
public TreeNode Find(TreeNodeCollection nodes, string key)
{
key = key.ToUpper();
Stack<TreeNode> stackNodes = new Stack<TreeNode>();
foreach (TreeNode item in nodes)
{
stackNodes.Push(item);
}
while (stackNodes.Count > 0)
{
TreeNode currentNode = stackNodes.Pop();
if (currentNode.Text.ToUpper() == key)
return currentNode;
else
foreach (TreeNode item in currentNode.Nodes)
{
stackNodes.Push(item);
}
}
return null;
}
您可以这样称呼它:
private void findButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(keyTextBox.Text.Trim()))
{
var result = Find(treeView1.Nodes, keyTextBox.Text.Trim());
if (result != null)
{
treeView1.SelectedNode = result;
treeView1.Focus();
}
}
}
答案 2 :(得分:0)
尝试一下:
private void txtSerach_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var searchFor = txtSerach.Text.Trim().ToUpper();
if (searchFor != "")
{
if (treeView1.Nodes.Count > 0)
{
if (SearchRecursive(treeView1.Nodes, searchFor))
{
treeView1.SelectedNode.Expand();
treeView1.Focus();
}
}
}
}
}
private bool SearchRecursive(IEnumerable nodes, string searchFor)
{
foreach (TreeNode node in nodes)
{
if (node.Text.ToUpper().Contains(searchFor))
{
treeView1.SelectedNode = node;
return true;
}
if (SearchRecursive(node.Nodes, searchFor))
return true;
}
return false;
}