Introduction
If you have found this article then it means that you could not get the background style of a ListItem
control to work properly with such web controls as a DropDownList
. Yes, it's supposed to work because the ListItem
control does contain an Attribute
collection, but for some reason, none of the styles nor the supplied attributes will work. Well, a more tedious solution can be found here: List Control Items and Attributes by Scott Mitchell.
My solution, however, works just as well with one (known) flaw. The AutoPostBack
property can not be used. I'm sure there are some JavaScript capabilities that can be implemented to duplicate this feature, so we won't consider it a major issue. At this point, you are probably wondering why the AutoPostBack
property will be unavailable. Well my question to you is, "Why are you trying to use a DropDownList
if its ListItem
attributes don't work?".
If the handling of attributes for a DropDownList
's ListItem
s are an obvious bug, then how about the ListItem
s for a System.Web.UI.HtmlControls.HtmlSelect
control? I'm sure you know of all the ways to bind data with ASP.NET controls, so I'm positive that you'll use the simplicities of this example in more advanced ways.
ASPX
<form id="Form1" method="post" runat="server">
<select name="ddlTest" id="ddlTest" runat="server" style="width:125px">
</select>
</form>
Code Behind
Protected WithEvents ddlTest As System.Web.UI.HtmlControls.HtmlSelect
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
If Not Me.IsPostBack Then
Dim l As ListItem
l = New ListItem("Lions", "1")
l.Attributes.Add("style", "background: yellow;")
ddlTest.Items.Add(l)
l = New ListItem("Tigers", "2")
l.Attributes.Add("style", "background: orange;")
ddlTest.Items.Add(l)
l = New ListItem("Bears", "3")
l.Attributes.Add("style", "background: brown;")
ddlTest.Items.Add(l)
l = New ListItem("Oh My!", "4")
l.Attributes.Add("style", "background: red; color: white;")
ddlTest.Items.Add(l)
End If
End Sub
That's It
There's always a solution, even if it is just a quick fix.