문제

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();
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top