2
votes

The ListBox

  <asp:ListBox ID="YearListBox" runat="server" Rows="11" SelectionMode="Multiple" AutoPostBack="True"></asp:ListBox>

How can I set the selected items' background to blue. I have tried the following solution, but not working correctly in chrome.

 int[] YearIndexes = YearListBox.GetSelectedIndices();
            for (int i = 0; i < YearIndexes.Length; i++)
            {
               //do something...
                YearListBox.Items[YearIndexes[i]].Attributes.Add("style", "background-color:blue");
            }

We can see the selected items' background color on this image [1] is gray, but the items' background property is blue on this image [2].

It seems that browser's default style is override my background property .

2
I want to set the selected items' background color to blue after posting back .Pin-Lin Huang

2 Answers

1
votes

First up I'd use classes instead of defining the colours in your code (it's just easier to change in the future).

Edit: You're asking to change the way the UI behaves, you could potentially confuse the user. As far as I know there's no way to override those default gray and blue styles that are applied to selected items. If you must go that way then you need to look at some sort of custom control.

This'll be in the region of what you want so you can apply full customisation to it: reinventing a drop-down with css and jquery/

or Custom SelectBox

1
votes

There are 3 ways you can do it as mentioned below:

1. Try to provide style in list item as mentioned below:

<asp:ListItem style="background-color:red">Item 2</asp:ListItem>

2. you can change it from code behind as mentioned here : Change color of list item

3. you can apply css as mentioned below:

CSS :

.listContainer option {
    background-color: gray;
}

Html :

<asp:ListBox runat="server" ID="listTest" CssClass="listContainer">
    <Items>
        <asp:ListItem >Test 1</asp:ListItem>
        <asp:ListItem >Test 2</asp:ListItem>
        <asp:ListItem >Test 3</asp:ListItem>
    </Items>
</asp:ListBox>

Note: Fourth way is using Javasript or JQuery. But that will be useful when you want to change it runtime