Display tooltips for ListView items in C#

[tooltips]

This example shows how to display different tooltips for the items in a ListBox. When you move the mouse over an item in the ListBox, the program uses the following code to display a tooltip for it.

// Display a tooltip for the animal under the mouse.
private void lstWeirdAnimals_MouseMove(
  object sender, MouseEventArgs e)
{
    // See what item is under the mouse.
    int index = lstWeirdAnimals.IndexFromPoint(e.Location);

    // Just use the item's value for the tooltip.
    string tip = lstWeirdAnimals.Items[index].ToString();

    // Display the item's value as a tooltip.
    if (tipWeirdAnimals.GetToolTip(lstWeirdAnimals) != tip)
        tipWeirdAnimals.SetToolTip(lstWeirdAnimals, tip);
}

When the ListBox receives a MouseMove event, the event handler uses the ListBox control’s IndexFromPoint method to see which items is under the mouse. This example just uses the ListBox items’ text for the tooltips, but you could modify the program to look up appropriate tooltips for the items, perhaps in a Dictionary.

Next the code uses the tipWeirdAnimals ToolTip component’s GetToolTip method to see if the ListBox control’s current tooltip is different from the new one. If the two values are different, the code uses the ToolTip component’s SetToolTip method to set the new tooltip for the ListBox. (The code doesn’t set the tooltip if the new and old values are the same to prevent a really annoying flicker. Comment out the if statement to see it.)


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls and tagged , , , , , , , , , , , , . Bookmark the permalink.

3 Responses to Display tooltips for ListView items in C#

  1. Ekta says:

    Wow. Thanks. It was the most straight forward solution i came across so far.

  2. Ajay says:

    Hey it is showing : The name ‘tipWeirdAnimals’ does not exist in current context.

    • RodStephens says:

      My guess is that you tried to recreate the program from scratch rather than downloading the example program. If you do, you need to add a ToolTip component named tipWeirdAnimals to the form at design time. Then I think it should work.

Leave a Reply

Your email address will not be published. Required fields are marked *