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.

Items:




  • 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>Select...</asp:ListItem>
<asp:ListItem>Complete</asp:ListItem>
<asp:ListItem>Running</asp:ListItem>
<asp:ListItem>Waiting in SEV 1</asp:ListItem>
<asp:ListItem>No Batch</asp:ListItem>
</asp:DropDownList>


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>
</asp:DropDownList>

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:
                    ddl.style.backgroundColor = 'White';
                    return;

                case 1:
                    ddl.style.backgroundColor = 'Green';
                    return;

                case 2:
                    ddl.style.backgroundColor = 'Yellow';
                    return;

                case 3:
                    ddl.style.backgroundColor = 'Red';
                    return;

                case 4:
                    ddl.style.backgroundColor = 'Blue';
                    return;
            }
        }
    }
}

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