WinForms: Show individual tooltip for each ListBox item
Unlike ListViewItem we don’t have a built-in way to set individual tooltip text for each item in ListBox. But there is an easily realizable workaround. Add the following handler to your ListBox‘s MouseMove event:
private void listBox_MouseMove(object sender, MouseEventArgs e)
{
ListBox lb = (ListBox)sender;
int index = lb.IndexFromPoint(e.Location);
if (index >= 0 && index < lb.Items.Count)
{
string toolTipString = lb.Items[index].ToString();
// check if tooltip text coincides with the current one,
// if so, do nothing
if (toolTip1.GetToolTip(lb) != toolTipString)
toolTip1.SetToolTip(lb, toolTipString);
}
else
toolTip1.Hide(lb);
}
The toolTip1 is a System.Windows.Forms.ToolTip control, which should be dropped on your form.
If your ListBox items are more complex rather than a string, and you want tooltip to have a value different from the returned by ToString(), you can take as a basis the following code sample:
public class FileListItem
{
public string FilePath { get; set; }
public override string ToString()
{
// return file name without directory path
return Path.GetFileName(FilePath);
}
}
...
private void listBox_MouseMove(object sender, MouseEventArgs e)
{
ListBox lb = (ListBox)sender;
int index = lb.IndexFromPoint(e.Location);
if (index >= 0 && index < lb.Items.Count)
{
string toolTipString = lb.Items[index].ToString();
// if the item is a FileListItem object,
// set tooltip to the value of FilePath property
FileListItem fileListItem = lb.Items[index] as FileListItem;
if (fileListItem != null)
toolTipString = fileListItem.FilePath;
// check if new tooltip text coincides with the current one,
// if so, do nothing
if (toolTip1.GetToolTip(lb) != toolTipString)
toolTip1.SetToolTip(lb, toolTipString);
}
else
toolTip1.Hide(lb);
}