Custom Tooltips in WinForm TreeViews

This is one of those simple coding issues that I was recently faced with that I wish I had a simple example to show me how to knock this out. I had to create a treeview whose nodes were supposed to display a tooltip that could change based on the selected node. Pretty straightforward issue overall, but I ran into a problem: the tooltips weren't working. OK, so it was a big problem with a simple solution. Long story short, there are a few key ingredients in setting tooltips that change based on the node you have selected. My problem stemmed from forgetting to deactivate the tooltip and then reactivate it. I did not see this anywhere in the documentation but I stumbled across it by trying different properties out. Now, maybe this is common knowledge to some or even most of you, but to me it sure wasn't. But I have run into controls in the past that needed to be turned off and on to work properly. So I guess I just chalk this up as one more.

Anyway, here is a short list of things to look for:

  • drag a tooltip control onto your designer that has the treeview control
  • create a mousemove event handler on the treeview to kick off the tooltip
  • check to make sure that a node is selected, or get out
  • check to make sure a different node is selected than previously, or get out
  • Make the tooltip deactive (tip.Active = false;)
  • Set the tooltip text (tip.SetTooltip(tree, toolTipText);
  • Make the tooltip active (tip.Active = true;)
  • Now, I had an object stored in the tag of each treeview node. So I grab it, figure out which obejct I have and get a property of the object to use for the tooltip. This part is up to your implementation of course.


     private void tree_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { TreeNode currentNode = tree.GetNodeAt(e.X, e.Y); if ((currentNode == null) || (previousNode == currentNode) || (currentNode.Tag == null)) return; string toolTipText = string.Empty; previousNode = currentNode; object o = previousNode.Tag; if (o is Class1) toolTipText = Class1.Description; else if (o is Class2) toolTipText = Class2.Description; else if (o is Class3) toolTipText = Class3.Description; else toolTipText = string.Empty; // Turn off the tooltip so we can change the text if (tip.Active) tip.Active = false; // Change the tooltip text tip.SetToolTip(tree, toolTipText); // Turn on the tooltip  tip.Active = true; } 

Tweet Post Share Update RSS

Hi, I'm John Papa. I author this blog, create courses for Pluralsight and am a Google Developer Expert and Microsoft Regional Director. I travel speaking at events and train technology thought leaders