C# - TreeView:在特定位置插入节点
如何将新子节点插入到 C# WinForms 中 TreeView 中的特定节点?
我已经笨拙地刺探 TreeViews 近一个小时了,我想像这样使用 C# 的 TreeView:
treeView.getChildByName("bob").AddChild(new Node("bob's dog"));
这是我最后尝试的(我认为这是 C# 永远不应该让我达到的毛茸茸的水平):
tree.Nodes[item.name].Nodes.Add(new TreeNode("thing"));
不用说,这是行不通的。
哦,这是一个懒惰的问题:你真的可以在这些节点中存储对象吗?或者 TreeNode 只支持字符串之类的吗? (在这种情况下我应该扩展 TreeNode../叹息)
请帮忙,谢谢!
How does one insert a new child to a particular node in a TreeView in C# WinForms?
I've been clumsily stabbing at TreeViews for almost an hour and I'd like to use C#'s TreeView like this:
treeView.getChildByName("bob").AddChild(new Node("bob's dog"));
Here's what I tried last (which I think is at a level of hairiness which C# should never have allowed me to reach):
tree.Nodes[item.name].Nodes.Add(new TreeNode("thing"));
Needless to say, it doesn't work.
Oh, and here's a lazy question: can you actually store objects in these nodes? Or does TreeNode only support strings and whatnot? (in which case I should extend TreeNode.. /sigh)
Please help, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用“插入”而不是“添加”。
You can use Insert instead of Add.
实际上你的代码应该可以工作 - 为了添加一个子节点,你只需要做:
也许问题出在你引用现有节点的方式上。
我猜测 tree.Nodes[item.Name] 返回 null?
为了让该索引器找到该节点,您需要在添加节点时指定一个键。您是否指定节点名称作为键?例如,以下代码适用于我:
如果我的答案不起作用,您能否添加有关发生情况的更多详细信息?您是否遇到了一些异常或根本没有发生任何事情?
PS:为了在节点中存储对象,您还可以从 TreeNode 派生自己的类并在其中存储任何内容,而不是使用 Tag 属性。如果您正在开发一个库,这会更有用,因为您将 Tag 属性留给用户使用。
然
Actually your code should work - in order to add a sub node you just have to do:
Maybe the problem is in the way you refer to your existing nodes.
I am guessing that tree.Nodes[item.Name] returned null?
In order for this indexer to find the node, you need to specify a key when you add the node. Did you specify the node name as a key? For example, the following code works for me:
If my answer doesn't work, can you add more details on what does happen? Did you get some exception or did simply nothing happen?
PS: in order to store an object in a node, instead of using the Tag property, you can also derive your own class from TreeNode and store anything in it. If you're developing a library, this is more useful because you are leaving the Tag property for your users to use.
Ran
好吧,首先,是的,您可以在每个节点中存储对象。每个节点都有一个
object
类型的Tag
属性。添加节点应该相当简单。根据 MSDN:
Well, to start out, yes you can store objects in each node. Each node has a
Tag
property of typeobject
.Adding nodes should be fairly straightforward. According to MSDN:
否则,如果 Davita 的不是完美答案,您需要保留对节点的引用,因此,如果您有对 bob 的引用,您可以添加 bob 的狗
TreeNode bob= new TreeNode("bob");
treeView1.Nodes.Add(bob);
bob.Nodes.Add(new TreeNode("Dog"));
Otherwise if Davita's isn't the perfect answer, you need to retain a reference to the nodes, so if you had a reference to bob you could add bob's dog
TreeNode bob= new TreeNode("bob");
treeView1.Nodes.Add(bob);
bob.Nodes.Add(new TreeNode("Dog"));