The TreeView in Windows Forms always seems to want a node selected when it regains focus. If I have no nodes selected, and that treeview gains focus, I'll get an AfterSelect
event with the first node selected, even though I didn't select it using the keyboard, mouse, or programmatically. The only workaround I can find is to check if the TreeViewCancelEventArgs.Action
equals TreeViewAction.Unknown
and then canceling the selection. This seems really hacky, so I'm wondering if there's another way to fix this.
C# – Windows Forms TreeView always selects a node on focus
ctreeviewwinforms
Best Answer
I agree that using
TreeViewAction.Unknown
in this case is less than desirable. Consider using theBeforeSelect
event, which provides an opportunity to prevent theAfterSelect
event.Create a
GotFocus
event handler that sets a flag. Then, create aBeforeSelect
event handler that, if the flag is set, cancels the event and clears the flag. For example: