C#-TreeView:在特定位置插入节点 [英] C# - TreeView: inserting node at certain position

查看:932
本文介绍了C#-TreeView:在特定位置插入节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#WinForms中将新子项插入TreeView中的特定节点?

How does one insert a new child to a particular node in a TreeView in C# WinForms?

我笨拙地在TreeViews上刺伤了近一个小时,我想像这样使用C#的TreeView:

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"));

这是我最后尝试过的方法(我认为这是C#绝对不允许我达到的毛羽水平):

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.

哦,这是一个懒惰的问题:您可以在这些节点中实际存储对象吗?还是TreeNode仅支持字符串而不支持字符串? (在这种情况下,我应该扩展TreeNode../sigh)

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)

请帮助,谢谢!

推荐答案

实际上,您的代码应该可以工作-为了添加子节点,您只需要做:

Actually your code should work - in order to add a sub node you just have to do:

myNode.Nodes.Add(new TreeNode("Sub node"));

也许问题出在您引用现有节点的方式上. 我猜测tree.Nodes [item.Name]返回null吗?

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:

treeView1.Nodes.Add("key", "root");
treeView1.Nodes["key"].Nodes.Add(new TreeNode("Sub node"));

如果我的答案不起作用,您能否添加更多有关发生的情况的详细信息?您有例外情况吗?还是什么都没发生?

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:为了将对象存储在节点中,而不是使用Tag属性,还可以从TreeNode派生您自己的类并将任何内容存储在其中.如果您正在开发库,这将更加有用,因为您将Tag属性留给用户使用.

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

这篇关于C#-TreeView:在特定位置插入节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆