replacment TreeNodeCollection.Find methos

  • Thread starter Thread starter Marian
  • Start date Start date
M

Marian

Hello,
I'd like use well-know TreeNodeCollection.Find method from .NET in my
Pocket PC application, but this method isn't available in .NET CF. How
implement it in my code? I'm trying put into TreeView control data from
text file organized in this format:
cat_id;parent_cat_id;category_name
cat_id;parent_cat_id;category_name
......
cat_id;parent_cat_id;category_name


Regards,
Marian
 
You will probably need to use recursion to iterate through the
collection and find the matching ID/Name, and add it to your own
collection as you find a match.
 
ok, but how? In .NET CF properties like TreeNode.FirstNode or
TreeNode.NextNode are not available.
 
Just recursively iterate through child nodes. Here you are a sample how
to search a node by its text:

TreeNode [] tn = Find("NodeName", true);

....

public TreeNode [] Find(string text, bool searchAllChildren)
{
ArrayList res = new ArrayList();
Find(text, true, treeView1.Nodes, res);
return (TreeNode [])res.ToArray(typeof(TreeNode));
}

private ArrayList Find(string text, bool searchAllChildren,
TreeNodeCollection treeNodeCollectionToLookIn, ArrayList foundTreeNodes)
{
for (int i = 0; i < treeNodeCollectionToLookIn.Count; i++)
{
// can be replaced by StartsWith method
if (string.Compare(treeNodeCollectionToLookIn.Text, text, true) == 0)
foundTreeNodes.Add(treeNodeCollectionToLookIn);
}
if (searchAllChildren)
{
for (int i = 0; i < treeNodeCollectionToLookIn.Count; i++)
{
if (treeNodeCollectionToLookIn.Nodes.Count > 0)
foundTreeNodes = Find(text, searchAllChildren,
treeNodeCollectionToLookIn.Nodes, foundTreeNodes);
}
}

return foundTreeNodes;
}



if you want to find a node by Key then use Tag property to store its key
and modify code instead of:

if (string.Compare(treeNodeCollectionToLookIn.Text, text, true) == 0)
foundTreeNodes.Add(treeNodeCollectionToLookIn);

use

if (text.CompareTo(treeNodeCollectionToLookIn.Tag) == 0)
foundTreeNodes.Add(treeNodeCollectionToLookIn);



HTH
 
Back
Top