2

Dropdown list needs to display items with varying text colors. Color is decided by server-side. Uses <style> tags versus CSS styling sheet. See example:

protected void Page_Load(object sender, EventArgs e)
    {
        ListItem li = CreateListItemWithColor("Hello", "myValue", "blue");
        employeeDropDownBox.Items.Add(li);

    }
public ListItem CreateListItemWithColor(string text, string value, string color)
    {
        //Create the list item based on input text/value
        ListItem li = new ListItem();
        li.Text = text;
        li.Value = value;
        li.Attributes.Add("style", "color="+color);
        return li;
    }

From what I have read in other SO posts about formatting list item text, my general procedure seems close. But my ListItem is always black. What am I missing?


Abbreviated HTML:

<style>
    #employeeDropDownBox {
        height: 65px;
        width: 425px;
        font-size: 27px;
        margin-left: 5px;
    }

</style>

<div>
    <asp:DropDownList ID="employeeDropDownBox" runat="server" ></asp:DropDownList>
</div>
3
  • I didn't think individual option elements in a select even could be styled. That's always been an issue in web development, since different hosts render select elements their own way. Generally the solution has been to use JavaScript plugins to create custom elements which mimic the behavior of a select and synchronize with a hidden select. Commented Aug 5, 2016 at 14:22
  • See stackoverflow.com/questions/2609344/… Commented Aug 5, 2016 at 14:23
  • @MehdiDehghani Extra css file is unnecessary. I am modifying other ASP control attributes using the <style> tags successfully. Commented Aug 5, 2016 at 14:29

1 Answer 1

3

Instead of adding style, add css class & use this class in your css file to handle the color

li.Attributes.Add("class", "blue"); // you can use the `color` parameter as well

In your css:

.blue {
    color: blue;
}

Update

So, you need to use : instead of =

    li.Attributes.Add("style", "color:" + color);
Sign up to request clarification or add additional context in comments.

4 Comments

This does not solve the issue. I specifically am using the <style> tag approach for other controls. A css class is not the answer here.
If you use css for styling, your life will be easy in future, imagine maybe tomorrow your customer ask for another color, editing css is much easier than editing C#
I appreciate your perspective. However I have a much larger application using <style> tags that I am modifying. CSS style sheets are a consideration for future updates.
So, please tell me an example of generated option tag, use the browser's console

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.