问题
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