Different styles in DropDownList items?

  • Thread starter Thread starter Gandalf
  • Start date Start date
G

Gandalf

I wish to apply different styles to items in a DropDownList. However, any
styles applied in the codebehind (using the ListItem.Addtributes property)
do not get rendered. This is an old question but I've yet to see a
satisfactory answer, other than it's a bug in the DropDownList. It seems to
work for a HtmlSelect control, but this does not provide the AutoPostBack
feature I require. Any help appreciated.
--
 
You pretty well have to do it in client-side script. Of course you can use the
codebehind to output the client-side script like this:

Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim sb As New System.Text.StringBuilder
If Not IsPostBack Then
lstArtTipo.Items.Add("First item")
lstArtTipo.Items.Add("Second item")
lstArtTipo.Items.Add("Third item")
lstArtTipo.Items.Add("Fourth item")
End If
sb.Append("<script language='javascript'>")
sb.Append("function docolorddl(selI)")
sb.Append("{document.Form1.lstArtTipo.options")
sb.Append("[selI].style.backgroundColor=")
sb.Append("'PowderBlue';}</script>")
Page.RegisterClientScriptBlock("bgcolor", sb.ToString)
sb.Length = 0
sb.Append("<script language='javascript'>")
sb.Append("docolorddl(document.Form1.lstArtTipo.selectedIndex);")
sb.Append("</script>")
Page.RegisterStartupScript("bgstart", sb.ToString)
lstArtTipo.Attributes.Add("onchange", _
"docolorddl(this.selectedIndex);")
End Sub

I wish to apply different styles to items in a DropDownList. However, any
styles applied in the codebehind (using the ListItem.Addtributes property)
do not get rendered. This is an old question but I've yet to see a
satisfactory answer, other than it's a bug in the DropDownList. It seems to
work for a HtmlSelect control, but this does not provide the AutoPostBack
feature I require. Any help appreciated.
--
 
Thanks Ken. WHat you are doing is setting the color of the selected item to
powderblue, whereas I want each item in the dropdown to be a different
color. I'm sure I could do it writing reams of jscript but i'd rather not.
;-)
 
Back
Top