title: C# TreeView Collapse/Expand on parent select
body: <p>This one is hard to explain so i will just tell you what i want to achieve and how i am doing it so maybe someone witll have an idea on what i am doing wrong.</p>
  
  <p>In my winForm i have a TreeView control that i populate. All parents have children (any number of them) but no children have children of their own. Example:</p>
  
  <pre><code>- Parent 1
          Child 1
          Child 2
          Child 3
  - Parent 2
         Child 4
  </code></pre>
  
  <p>The behaviour i want is the following:</p>
  
  <ol>
  <li>when the user clicks a child it get's selected (done by default)</li>
  <li>When the user clicks a parent, it should either collapse or expand but not change any selection</li>
  </ol>
  
  <p>Point 1 is no problem as it is the default behaviour of a TreeView, Point 2 however is another story.</p>
  
  <p>Here is what i have done so far:</p>
  
  <p>To prevent the parent from being selected i add a BeforeSelect event handler and put in it the following code:</p>
  
  <pre><code>if (e.Node.Parent == null)
      e.Cancel = true;
  </code></pre>
  
  <p>This does the job perfectly. So now that i canceled the selection of the parent i want to expand or collapse it. So i changed the above code to:</p>
  
  <pre><code>if (e.Node.Parent == null)
  {
      if (e.Node.IsExpanded)
      {
          e.Node.Collapse();
      }
      else
      {
          e.Node.Expand();
      }
      e.Cancel = true;
  }
  </code></pre>
  
  <p>This somewhat works - except that, unlike clicking the + sign, calling Expand() or Collapse() makes the parent node be selected, ignoring the e.Cancel = true; line.</p>
  
  <p>I tried getting the SelectedNode before i call Collapse() or Expand() and then setting it back - it works but when i do that it will expand the parent again to make the selection.</p>
  
  <p>Somewhow the + sign does exactly what i want to happen when i click on a parent - i just can't seem to get it to work.</p>
  
  <p>Ideas?</p>
  
  <p>Thanks in advance</p>