Denis Soto Denis Soto -3 years ago 117
ASP.NET (C#) Question

set Different colors in asp:DropDownList Items

I have an in my form, with 4 different options (items)
What I need to do it's to set a different color from client side, without PostBack.


  • Select... (white)

  • Complete (green)

  • Running (yellow)

  • Waiting in SEV1 (red)

Could somebody help me with this?

Edit (with Dropdown code)

<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Waiting in SEV 1</asp:ListItem>
<asp:ListItem>No Batch</asp:ListItem>

I have only looked for a solution for this, with no success yet. That's why I haven't tried anything yet.

Answer Source

This markup applies a different background color to each item, and sets the onchange event handler:

<asp:DropDownList ID="DropDownList1" runat="server" onchange="SetDropDownListColor(this);">
    <asp:ListItem style="background-color: White !important;" >Select...</asp:ListItem>
    <asp:ListItem style="background-color: Green !important;" >Complete</asp:ListItem>
    <asp:ListItem style="background-color: Yellow !important;" >Running</asp:ListItem>
    <asp:ListItem style="background-color: Red !important;" >Waiting in SEV 1</asp:ListItem>
    <asp:ListItem style="background-color: Blue !important;" >No Batch</asp:ListItem>

The following Javascript ensures that the color of the selection box matches the color of the selected item:

function SetDropDownListColor(ddl) {
    for (var i = 0; i < ddl.options.length; i++) {
        if (ddl.options[i].selected) {
            switch (i) {
                case 0:
           = 'White';

                case 1:
           = 'Green';

                case 2:
           = 'Yellow';

                case 3:
           = 'Red';

                case 4:
           = 'Blue';

The !important modifier is set in the markup of the items in the list, in order to override the background color set to the whole control in the Javascript function.

In order to preserve the color of the DropDownList after a postback, the following line of code can be added to the Javascript block. It defines a handler for the load event of the page, in which the color of the selected item is applied to the selection box:

window.addEventListener('load', function () { SetDropDownListColor(document.getElementById('<%= DropDownList1.ClientID %>')); }, false);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download