how to replace TreeView's selected node with newly created node

霸气de小男生 提交于 2020-02-24 17:00:29

问题


I have a populated treeView with Node I created, there are several node classes, all inherit from treeNode.

When i edit a node (using a GUI dialog), it may change to different class, so I'm creating a new node in that process, and trying to replace the selected node with my new node, but that doesn't work, the node stays the old one, cant figure out what i'm doing wrong.

Code:

TreeNodeMission mission = (TreeNodeMission)treeView.SelectedNode;
TreeNodeMission newMission = ChangeMissionDialog(mission);

treeView.SelectedNode = newMission; // doesn't work

Also tried removing and adding it, also doesn't work

index = treeView.Nodes.IndexOf(treeView.SelectedNode);  // index returns -1
treeView.Nodes.Remove(treeView.SelectedNode);
treeView.Nodes.Insert(index, newMission);

What am i doing wrong?

Update: treeView.SelectedNode is not null, its a valid node i selected.


回答1:


Solved it, found the bug.

I found a way to replace the node, by removing and re-adding it. I guess i thought asking for index will give me general index in the tree, but it gives index to the parent only, so using the parent node, i can replace it:

int index = treeView.SelectedNode.Index;
treeView.SelectedNode.Parent.Nodes.RemoveAt(index);
treeView.SelectedNode.Parent.Nodes.Insert(index, mission);
treeView.SelectedNode = mission;

Thanks



来源:https://stackoverflow.com/questions/14953041/how-to-replace-treeviews-selected-node-with-newly-created-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!