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.
精彩评论