views:

33

answers:

1

i have a event handler that moves the selected treenode up. I don't know why is crash in the line with comented. treeviewdocxml is a treeview object, from System.Windows.Forms

        treeViewDocXml.BeginUpdate();
        TreeNode sourceNode = treeViewDocXml.SelectedNode;

        if (sourceNode.Parent == null)
        {
            return;
        }
        if (sourceNode.Index > 0)
        {
            sourceNode.Parent.Nodes.Remove(sourceNode);
            sourceNode.Parent.Nodes.Insert(sourceNode.Index - 1, sourceNode); //HERE CRASH
        }
        treeViewDocXml.EndUpdate();
+3  A: 

It's because you're referencing sourceNode.Index after you removed it from the tree. Try storing the index in a variable before removing it:

    treeViewDocXml.BeginUpdate();
    TreeNode sourceNode = treeViewDocXml.SelectedNode;

    if (sourceNode.Parent == null)
    {
        return;
    }
    if (sourceNode.Index > 0)
    {
        var sourceIndex = sourceNode.Index;
        var parentNode = sourceNode.Parent;
        parentNode.Nodes.Remove(sourceNode);
        parentNode.Nodes.Insert(sourceIndex - 1, sourceNode); //HERE CRASH
    }
    treeViewDocXml.EndUpdate();

[Update]

The reference to parent node was incorrect as well, so I fixed that in the example.

Prutswonder
+1, beat me by 1 second!!!
leppie
is still crash, treeViewDocXml.BeginUpdate(); TreeNode sourceNode = treeViewDocXml.SelectedNode; TreeNode copy = (TreeNode)sourceNode.Clone(); int index = sourceNode.Index; if (sourceNode.Parent == null) { return; } if (sourceNode.Index > 0) { sourceNode.Parent.Nodes.Remove(sourceNode); sourceNode.Parent.Nodes.Insert(index - 1, copy); } treeViewDocXml.EndUpdate();
voodoomsr
Updated the example already ;-)
Prutswonder
ou yea thanks, that works. (always happend me that when I'm writing a reply the previous answers change at the same time and the reply i sent has no senses anymore, xD)
voodoomsr