Highlighting ListItems in a DropDownList

March 17, 2011

I’ve just completed adding functionality to a system that allowed the user to select a persons name from a DropDownList. The list was structured hierarchically, in that each person in the list was shown indented under his/her manager. To make the structure clearer, I wanted to highlight managers in a different colour. Heres how I did it:

In the loop, where I was creating ListItems for each person (Which were than added to the DropDownList) I added an attribute to the ListItem to apply a CSS class:

Method 1
When items are explicitally added to the DropDownList

foreach (DataRow drSomeRow in someDataTable.Rows)
            String name= drSomeRow ["Name"].ToString();
            String id = drSomeRow ["ID"].ToString();

            ListItem liPerson = new ListItem(name, id);

            liPerson.Attributes.Add("class", "highlightedListItem");
            // Note: In this example, the CSS class is applied to all items in the list
            // In reality you would probably wrap this line in an if statement, checking a record value


Method 2
DropDownLists that are DataBound to a list of objects/DataTable etc?

Often, DropDownLists (and other DataBound controls) will be bound to a DataSource, rather than populated item by item as in example 1 above. In this case, we need to loop the items in the DropDownList after they have been added. Note that this method does depend upon either:

A) Having some way of determining whether or not the ListItem should be highlighted, based on either the Value or Text properties
B) Making an external call passing either the Text or Value propertie values as a key to retrieve some other information
(I would suggest steering clear of B as this potentially means a database/webservice call for each item in your list – Inefficient and slow!

foreach (ListItem liPerson in DropDownListTeams)
                if liPerson.Value.Contains(SomeValue) {
                    liPerson.Attributes.Add("class", "highlightedListItem");



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: