Show a tooltip (title) on DropDownList items in ASP.NET
When item texts are truncated, or need an explanation, a title attribute on each <option> shows the full text on hover in desktop browsers. In Web Forms you add it through ListItem.Attributes. There is one surprise: those attributes are not saved in view state.
Adding titles after binding
<asp:DropDownList ID="ddlPlan" runat="server" OnDataBound="ddlPlan_DataBound" ToolTip="Choose a support plan" />
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlPlan.DataSource = PlanRepository.All(); // Id, Name, Description
ddlPlan.DataTextField = "Name";
ddlPlan.DataValueField = "Id";
ddlPlan.DataBind();
}
}
protected void ddlPlan_DataBound(object sender, EventArgs e)
{
AddTitles();
}
private void AddTitles()
{
var descriptions = PlanRepository.All().ToDictionary(p => p.Id.ToString(), p => p.Description);
foreach (ListItem item in ddlPlan.Items)
{
if (descriptions.TryGetValue(item.Value, out string d))
item.Attributes["title"] = d; // rendered as <option title="..."> and HTML-encoded
}
}
The control's own ToolTip property sets a title on the <select> itself, shown when the closed list is hovered.
The postback problem
ListItem stores its text, value, selection and enabled state in view state, but not its Attributes. After a postback, the items are restored without titles. Re-apply them on every request, after view state has been loaded:
protected void Page_PreRender(object sender, EventArgs e)
{
AddTitles(); // runs on the first request and on every postback
}
With PreRender in place, the DataBound handler above becomes optional. Cache the descriptions if loading them is expensive.
Browser behaviour
- Desktop browsers generally show option titles when the open list is hovered; behaviour has varied between browsers and versions, so test yours.
- Touch devices show native pickers that ignore
title. - Screen readers may or may not read it.
So treat the tooltip as a convenience. If users need the description to choose correctly, show it next to the list for the selected item:
var ddl = document.getElementById("<%= ddlPlan.ClientID %>");
var help = document.getElementById("planHelp");
function showHelp() { var o = ddl.options[ddl.selectedIndex]; help.textContent = o ? o.title : ""; }
ddl.addEventListener("change", showHelp); showHelp();
Binding the list in the first place is covered in Bind a DropDownList from SQL Server.
Common mistakes
- Adding attributes in
Page_Loadinsideif (!IsPostBack)only: they vanish on the first postback. UsePreRender. - Expecting
ListItem.Attributesto work on items generated afterDataBindin a later event: add the attributes after the final binding of the request. - Putting essential information only in tooltips: it is not visible on phones and tablets.
Official documentation
- Microsoft Learn: ListItem.Attributes, WebControl.ToolTip
- MDN: title attribute, <option>