如何在Windows窗体TreeView中按标签选择节点 [英] How to select a Node by Tag in Windows Forms TreeView
问题描述
我正在尝试通过标签选择一个节点。我已经搜寻了我能找到的,但仍然没有运气。我用它为我的 treeview
I'm trying to select a node by tag. I've searched what I can, but still with no luck. I used this to assign a tag to each node in my treeview
foreach (DataRow dataRow in databaseFunc.dataTable.Rows)
{
TreeNode nodes = new TreeNode();
nodes.Text = dataRow["LastName"].ToString().Trim() + ", " +
dataRow["FirstName"].ToString().Trim();
nodes.Tag = dataRow[0].ToString().Trim();
treeView.Nodes.Add(nodes);
}
我知道您可以使用以下方式选择节点:
I know you can select a node using:
TreeNodeCollection nodeCollect = treeView.Nodes;
treeView.SelectedNode = nodeCollect[index];
推荐答案
按标签查找
通过标记
查找特别有用,当标记
包含
Finding by Tag
is useful specially when the Tag
contains a complex object or you want to find based on a non-string key.
要能够在子节点上进行搜索,可以看一下在此处答复,并使用 Descendants
扩展方法来查找所有节点,包括子节点。然后,您可以通过 Tag
找到该节点。例如,如果标记
包含产品
,而您想根据其查找产品id
,您可以使用以下代码:
To be able to search on child nodes, you can take a look at the answer here and use Descendants
extension method to find all nodes including child nodes. Then you can find the node by Tag
. For example if the Tag
contains a Product
and you want to find the product based on its Id
, you can use such code:
var result = tree.Descendants().Where(x=>((x.Tag as Product) != null) &&
(x.Tag as Product).Id = someId).FirstOrDefault();
或者使用简单的字符串搜索键:
Or for a simple string search key:
var result = tree.Descendants().Where(x=>(x.Tag as string) == searchkey).FirstOrDefault();
if(result!=null)
tree.SelectedNode = result;
如果只想在根节点之间搜索,请使用:
If you want to search just between root nodes, use:
var result = tree.Nodes.Cast<TreeNode>().Where(... the rest is like above.
按名称查找
您可以使用 查找
方法,以根据其 节点
集合的名称
(不是文本)。当您要基于字符串键查找节点时,使用 Find
方法非常有用。为此,应设置创建节点时的节点名称
。
You can use Find
method of Nodes
collection to find a node based on its Name
(not the Text). Using Find
method is useful when you want to find a node based on a string key. To do so, you should set the Name
of node when you create the node.
var result = tree.Nodes.Find(searchKey , true).FirstOrDefault();
if(result !=null)
tree.SelectedNode = result;
如果只想在根节点之间搜索,请使用:
If you want to search just between root nodes, use:
var result = tree.Nodes.Find(searchKey , false).FirstOrDefault();
注意
最后,可以使用 Tag
属性将复杂对象存储在 Tag
中,并在需要时将其取消装箱。对于字符串搜索键,最好使用
As a conclusion you can use the Tag
property to store a complex object in Tag
and unbox it when you need. For string search keys, it's better to use Name
property as said in the comments.
这篇关于如何在Windows窗体TreeView中按标签选择节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!