如何更改ListBox所选项目';Asp.Net中的背景色

本文关键字:Asp Net 背景色 ListBox 何更改 选项 项目 | 更新日期: 2023-09-27 18:22:28

列表框

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

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

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

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

如何更改ListBox所选项目';Asp.Net中的背景色

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

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

这将在您想要的区域内,因此您可以对其进行完全定制:使用css和jquery/重新创建下拉列表

或自定义SelectBox

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

1.尝试在下面提到的列表项中提供style

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

2.您可以从代码后面更改它,如下所述:更改列表项的颜色

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。但当您想在运行时更改它时,这将是有用的