Display a different tooltip for each item in a ListBox in C#

When you move the mouse over an item in this example's ListBox, the program uses the following code to display a tooltip for that item.

// 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's IndexFromPoint to see which items is under the mouse. This example just copies the ListBox item to use as the tooltip. In a more useful application, you could make the code look up additional information for each item.

Next the code uses the tipWeirdAnimals ToolTip component's GetToolTip method to see if the ListBox's current tooltip is different from the new tooltip value. If the two values are different, the code uses the ToolTip's SetToolTip method to set the new tooltip. (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.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.