BACKGROUND
I have a DataGridView
table that populates a TreeView
with TreeNodes
. The TreeNode.Tag
property value is determined by the table RowIndex
. When I select a Cell
in the table the TreeView
node with the selected tablerowindex as tag should also be selected and it's parent expanded.
But how do I get the nodes tag value and compare it to the RowIndex
? I use this extention method to get all TreeNode
objects from the TreeView
as follows
var select = from node in treeView.Descendants()
where (node.Tag as string) == e.RowIndex.ToString()
select node as TreeNode;
But var select
return an empty WhereSelectListIterator
? Where did I go wrong?
UPDATE 1
The TreeNode
where TreeNode.Tag
is the IndexRow
is at TreeNode.Level
3 and the Descendants()
method only return root level nodes and root level child nodes, and that is why my WhereSelectListIterator
is empty.
The question is now How do I get the Descendants()
method to include TreeNodes
at TreeNode.Level
3?
UPDATE 2
Instead of using the Descendants()
method I use this extention method to get a list of all TreeNodes
in TreeView
and it included all nodes no matter what level.
But now I cannot compare the node.Tag
to the e.RowIndex
?
The method this far:
private void headerGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
List<TreeNode> oNodeList = treeView.GetAllNodes();
var select = from node in oNodeList
where (node.Tag as string) == e.RowIndex.ToString()
select node as TreeNode;
foreach (TreeNode node in select)
{
// This never happens because the select is empty
}
}
I tested the oNodeList like this so I know(!) there is nodes with tags in the list.
StringBuilder sb = new StringBuilder();
foreach (TreeNode node in oNodeList)
{
if (node.Tag != null) sb.AppendLine(node.Name);
}
MessageBox.Show(sb.ToString());
SOLUTION
I found a solution to my problem. There is really no need to use Linq to select nodes and add to a WhereSelectListIterator. The solution was much simpler than that.
private void headerGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
List<TreeNode> oNodeList = treeView.GetAllNodes();
foreach (TreeNode node in oNodeList)
{
if (node.Tag == null) continue;
if ((int)node.Tag == e.RowIndex)
{
treeView.SelectedNode = node;
if (!treeView.SelectedNode.Parent.IsExpanded) treeView.SelectedNode.Parent.Expand();
}
}
}
CONCLUTION
Don't over complicate things.