Skip generic parameter for Treeview & TreeNode
I have the following two methods that connect a TreeView or TreeNode that I want to combine into one method. Instead of passing a TreeView / TreeNode, I could pass an object and check the type, but would like to know if there is a better way?
private TreeNode SearchNode(string nodetext, TreeNode node)
{
foreach (TreeNode nd in node.Nodes)
{
if (nd.Text == nodetext)
{
return nd;
}
}
return null;
}
private TreeNode SearchParentNode(string nodetext, TreeView trv)
{
foreach (TreeNode node in trv.Nodes)
{
if (node.Text == nodetext)
{
return node;
}
}
return null;
}
source to share
You need one method that can look up the value in NodesCollection
, so just extract the contents of both methods into one, the third one that takes NodesCollection
:
private TreeNode SearchNodes(string nodeText, TreeNodesCollection nodes)
{
foreach (TreeNode node in nodes)
{
if (node.Text == nodeText)
{
return node;
}
}
return null;
}
And pass it any collection you want to find:
return SearchNodes(nodetext, node.Nodes);
return SearchNodes(nodetext, trv.Nodes);
Alternatively, you can reduce the method SearchNodes
to one line using LINQ:
private TreeNode SearchNodes(string nodeText, TreeNodesCollection nodes)
{
return nodes.Cast<TreeNode>().FirstOrDefault(n => n.Text == nodeText);
}
source to share
Data structures that resemble a tree are best searched using a recursive algorithm. It might look like this:
public static TreeNode SearchNode(string tofind, TreeNodeCollection nodes) {
foreach (TreeNode node in nodes) {
if (node.Text == tofind) return node;
var nested = SearchNode(tofind, node.Nodes);
if (nested != null) return nested;
}
return null;
}
Sample usage:
var node = SearchNode("foo", treeView1.Nodes);
if (node != null) {
node.Expand();
node.EnsureVisible();
}
Note how this works for any TreeView, not just one, which is limited to one parent-child relationship. This is a depth-first search, searching for the first line in the order in which the user sees them on the screen.
source to share
private TreeNode SearchNode(string nodetext, object obj)
{
if(obj.GetType() Is TreeView)
{
t = (TreeView)obj;
foreach (TreeView tv in obj.Nodes)
{
if (tv.Text == nodetext)
{
return nd;
}
}
}
else
{
n = (TreeNode)obj;
foreach (TreeNode nd in obj.Nodes)
{
if (nd.Text == nodetext)
{
return nd;
}
}
}
return null;
}
source to share