Multiselect Treeview Implementation
September 20, 2007
An extension of the .NET Treeview control to provide multiselect capabilites
Why doesn’t .NET have a mutiselect treeview? There are so many uses for one and turning on checkboxes in the treeview is a pretty lousy alternative. I tried some 3rd party treeviews and I think what turned me off the most is that the object model is different than the .NET treeview I’m used to working with. All I want is the standard .NET treeview with a
SelectedNodes property as well as a
SelectedNode property. After a quick search on CodeProject, I found Jean Allisat’s implementation here TreeViewMultiSelect.asp. I wasn’t satisfied though because some things didn’t behave correctly. For example you click on a node then as you Ctrl+Click on a second node, the first node loses its highlighting until the click operation is completed. Strange. So it looks a little bit choppy, but it works. I started with Jean’s implementation and took it to the next level to try and clean up the UI behaviour a bit.
The “choppy” problem I was having with the original implementation of the multiselect treeview was that we were letting the treeview select and highlight the selected node, while in the overidden events we would deal with manually highlighting other selected nodes. The conclusion I came to was to do all of the highlighting myself and not fight with the treeview. So the first thing we need to do is cripple the treeview so that it can NEVER have a
SelectedNode. We do this by overrideing the
OnAfterSelect events and setting
base.SelectedNode to null as well as setting
e.Cancel in some of the events to stop them from processing. We also hide the treeview’s
SelectedNode property (with the new keyword) and reimplement our own version.
Now that we have a treeview that is crippled we can implement new logic for selecting node(s). When you click on a node it becomes the
SelectedNode and it is highlighted. If you were not holding down a ModifierKey then we can clear the previous selection. If you were holding down the Ctrl ModifierKey then we decide whether to add this node to the selection or remove it if it was already in the selection. If you were holding down the Shift ModifierKey then we have to select all the nodes from the current
SelectedNode to this one. All of this logic resides in the
SelectNode() helper function.
One gothca here. All of the treeview’s
KeyDown messages are processed off of the
SelectedNode and since there never is a
SelectedNode (we’ve crippled it…) then you can’t use the keyboard to navigate/edit the tree. Well that’s no good… So we have to trap the
OnKeyDown event and handle Left, Right, Up, Down, Home, End, Page Up, Page Down, and any alpha-numeric character. Each of these key commands can have different behaviours if the Ctrl or Shift ModifierKey are pressed and possibly different behaviours if a branch is expanded or not.
Check out the code here:
Multiselect Treeview on CodeProject