开发者

crash in the handler that moves up a treenode in a treeview c#

开发者 https://www.devze.com 2022-12-27 20:17 出处:网络
i have a ev开发者_C百科ent handler that moves the selected treenode up. I don\'t know why is crash in the line with comented.

i have a ev开发者_C百科ent 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消