Thursday, 5 February 2009

Adding tooltips to list items in DropDownList

I needed to add tooltips to the items on the standard DropDownList asp control. I'm using custom data source to retrieve the list of items rather than static list defined in html.

Solution:
Add a ondatabound event handler to your DropDownList control:
<asp:DropDownList runat="server"
DataSourceId="MyCustomDatasource"
DataTextField="SomeName"
DataValueField="SomeValueCode"
ondatabound="ApplyOptionTitles"
... />
Then implement handler:
protected void ApplyOptionTitles(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
if (ddl != null)
{
foreach (ListItem item in ddl.Items)
{
item.Attributes["title"] = item.Text;
}
}
}
Answer found here.

3 comments:

Taphop said...

great stuff, but i want to disable item in dropdownlist. How to do it?

http://tatca.vn
http://taphop.net

Filip Czaja said...

It should be as simple as that:

item.Attributes["disabled"] = true;

Arshi said...

Good articale