C# Treeview doesn't refresh after moving nodes

2019-05-26 22:28发布

问题:

In my windows application I have a treeview. I made custum buttons to move a node downwards. This is what happens when a button is clicked:

Node destNode = tvCategories.SelectedNode.NextNode;
Node srcNode = tvCategories.SelectedNode;
Node parentNode = srcNode.Parent;

// Switch nodes
parentNode.Nodes[destNode.Index] = srcNode;
parentNode.Nodes[srcNode.Index] = destNode;

The code works fine, but my treeview isn't updated. I don't see the switch of the nodes.

tvCategories.Refresh() or tvCategories.Invalidate() or tvCategories.Update() doesn't work.

Anybody knows how to fix this?

PS: I'm using a 3rd party treeview of DevComponents.

回答1:

You can try to remove one node and to insert it again:

Node destNode = tvCategories.SelectedNode.NextNode;
// Check for null (what happens, if the last node is selected?)

// Switch nodes
destNode.Parent.Nodes.Remove( destNode );
destNode.Parent.Nodes.Insert( tvCategories.SelectedNode.Index, destNode );


回答2:

Setting Focus on the Treeview will cause a refresh as I have found by using

TreeView.Focus()