如何在Asp.Net中更改ListBox选定项目的背景颜色

时间:2014-09-19 11:33:01

标签: c# css asp.net listbox

列表框

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

如何设置所选项目&#39;背景到蓝色。 我尝试了以下解决方案,但在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");
            }

我们可以看到所选项目&#39;此图片上的背景颜色[1]是灰色的,但项目&#39;此图像上的背景属性为蓝色[2]。

浏览器的默认样式似乎覆盖了我的背景属性。

2 个答案:

答案 0 :(得分:1)

如下所述,有三种方法可以做到:

1。尝试在列表项中提供style,如下所述:

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

2。您可以从后面的代码更改它,如下所述: Change color of list item

3。您可以按照以下说明申请css:

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>

注意:第四种方式是使用Javasript或JQuery。但是,当您想要更改运行时

时,这将非常有用

答案 1 :(得分:1)

首先,我会使用类而不是在代码中定义颜色(将来更容易更改)。

编辑: 您要求更改UI的行为方式,您可能会混淆用户。据我所知,没有办法覆盖应用于所选项目的默认灰色和蓝色样式。如果你必须这样,那么你需要看一些自定义控件。

这将属于您想要的区域,因此您可以对其应用完全自定义:reinventing a drop-down with css and jquery/

Custom SelectBox

相关问题