ASP.NET: ListBox Tooltip
Posted
Sun, Jan 31 2010 16:47
by
Deborah Kurata
The ASP.NET ListBox does not display a horizontal scroll bar by default, which can be a problem if any of your list items are too long to fit. One solution to this problem is to use a tooltip. As the user moves the mouse over the ListBox entries, the full text appears in a tooltip.
The code to accomplish this is as follows:
In C#:
private void LB_PreRender(object sender, System.EventArgs e)
{
foreach (ListItem item in LB.Items) {
item.Attributes.Add("title", item.Text);
}
In C#, you also need to set up the event handler. In this example, the event handler is set up in the Page_Load event, but you could put it where it makes sense for your application.
LB.PreRender += LB_PreRender;
In VB:
Private Sub LB_PreRender(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles LB.PreRender
For Each item As ListItem In LB.Items
item.Attributes.Add("title", item.Text)
Next
End Sub
The ListBox, named LB in this example, has a PreRender event. In the PreRender event the code loops through the ListBox items and sets the title attribute to the text of the item.
Use this technique any time you want to display a tooltip over your ListBox items.
Enjoy!