How to add a title attribute to every option of an ASP.NET DropDownList

Posted by zuallauz on Stack Overflow See other posts from Stack Overflow or by zuallauz
Published on 2012-10-01T03:34:31Z Indexed on 2012/10/01 3:37 UTC
Read the original article Hit count: 177

Filed under:
|

I'm working on an older ASP.NET project (not MVC I don't think) and one of the features they require is to view a description of an item when they hover over that item in a dropdown list. This can be simply done with HTML using the following code and making use of title text:

<select>
    <option value="1" title="Option 1 Desc">Option 1</option>
    <option value="2" title="Option 2 Desc">Option 2</option>
    <option value="3" title="Option 3 Desc">Option 3</option>
</select>

Ok so how do I do this using ASP.NET DropDownList control? I have the following code:

<asp:DropDownList ID="DropDownListLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownListLocation_OnSelectedIndexChanged" CssClass="editorFieldServerControl" ClientIDMode="Static"></asp:DropDownList>

And in the 'code behind' page:

private void PopulateFacilityDropdown(List<FacilityAvailableByLocation> facilities, int? selectedID)
{
    DropDownListFacility.DataSource = facilities;
    DropDownListFacility.DataTextField = "FacilityName";
    DropDownListFacility.DataValueField = "FacilityID";
    DropDownListFacility.DataBind();            
    DropDownListFacility.Items.Insert(0, new System.Web.UI.WebControls.ListItem("", ""));                   

    if (selectedID.HasValue && selectedID.Value > 0)
        DropDownListFacility.SelectedIndex = facilities.FindIndex(b => b.FacilityID == selectedID.Value);
        else DropDownListFacility.SelectedIndex = 0;
    }
}

Basically each facility in the list of facilities there has properties for an ID, Name, Description that I can get out. I just want to be able to put a title attribute on each <option> that gets rendered and put the description into it. Either that or be able to add a custom attribute like 'data-description' to each <option> tag then I can add the title into each option tag myself using a bit of jQuery which is easy enough.

I miss the days where you could just loop through a list and output the custom dropdown code manually.

Any ideas? Many thanks

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about html.dropdownlist