Reputation: 2901
I am moving a TreeNode in a Windows Forms TreeView control as a consequence of a DragDrop event:
void treeViewDragDrop(object sender, DragEventArgs e)
{
// ...
sourceNode.Remove();
targetNode.Nodes.Add(sourceNode);
}
However, the Remove call triggers the AfterSelect event of the TreeView, which I need to react to if the selection really changes.
But in this case, the apparent selection change is only a result of temporarily removing the node. I don't want the selection to change at all after the node has finally moved to its target location in the tree.
So what would be the correct way to deal with that situation, i.e. how to suppress selection changes due to moving nodes?
Upvotes: 1
Views: 816
Reputation: 5373
If you do not set selection programmatically, you can cancel the selection in BeforeSelect
event if the action is not user-generated:
private void TreeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (e.Action == TreeViewAction.Unknown)
e.Cancel=true;
}
If you change selection programmatically, you may use a simple workaround by extending the TreeView class and setting a sort of "flag":
public class MyTreeViwe : TreeView
{
public bool IsSuspendSelection { get; set; }
protected override void OnBeforeSelect(TreeViewCancelEventArgs e)
{
if (IsSuspendSelection)
e.Cancel = true;
else base.OnBeforeSelect(e);
}
}
then do:
var tv = sourceNode.TreeView;
tv.IsSuspendSelection=true;
sourceNode.Remove();
tv.IsSuspendSelection=false;
You could also unsubscribe and then subscribe again to the AfterSelect
event on sourceNode.TreeView
, but I personally find this method accident-prone. There's no way to know if a given delegate is currently subscribing to a given event, and how many times. You may end up subscribing to the event multiple times and then your AfterSelect
delegate method will run more than once.
Upvotes: 2