如何在 ASP.net 的下拉列表中伪造标题或选项组

How to fake headings or optgroups in dropdownlist in ASP.net

如果之前有人发布过,我深表歉意,但如果是的话,我经过多次搜索后还是找不到。

我正在尝试找出如何将 optgroups/headings 包含在 asp.net 下拉列表中。 大多数答案只说 'no',但我找不到不包括覆盖下拉列表的答案,这似乎有点过分了。

当我发现它是多么简单时,我想我会分享,以防它对其他人有帮助!

我的示例解决方案。 CSS 为清楚起见是内联的。

<asp:DropDownList runat="server" ID="DropDownList1" >    
   <asp:ListItem style="font-weight:bold; color:black;" disabled="true">Heading 1</asp:ListItem>
   <asp:ListItem Text="Item 1" Value="11"></asp:ListItem>
   <asp:ListItem Text="Item 2" Value="12"></asp:ListItem>
   <asp:ListItem style="font-weight:bold; color:black;" disabled="true">Heading 2</asp:ListItem>
   <asp:ListItem Text="Item 1" Value="21"></asp:ListItem>
   <asp:ListItem Text="Item 2" Value="22"></asp:ListItem>
   <asp:ListItem Text="Item 3" Value="23"></asp:ListItem>
</asp:DropDownList> 

尽管浏览器存在一些差异,但呈现效果很好: 在 Chrome 和 Firefox 中,标题是漂亮的黑色,但 I.E.呈现为禁用的灰色。

重要的是,在所有这些标题中,标题都是不可选择的,并且在视觉上与项目不同。