Thursday, March 29, 2012

Set css class on list box option

Hi,

I want to programatically set the css class on a single list item. I tried the following code but it does nothing...


<html>
<script language="VB" runat="server"
Sub Page_Load(Src As Object, E As EventArgs)
categories.Items(0).Attributes.Add("class", "option.primary")
End Sub

</script
<style>
.primary {background-color:green;color:red; }
</style
<body>
<form runat="server">
<asp:listbox id="categories" Runat="server" SelectionMode="Multiple" Rows="6" Width="400">
<asp:listItem>Item 1</asp:listItem>
</asp:listbox>
</form>
</body>
</html>

Does anyone know how to achieve this?

WT.use the "cssclass" property of the listbox, then you can set it without doing the attributes.add thing.
<option> elements do not have class attributes, but it *is* strange that it doesn't write it out anyway. If you look at the rendered HTML, it probably reads:

<select name="categories">
<option value="Item 1">Item 1</option
That is because, as said, option elements don't have class attributes. Additionally, you're specifying "option.primary" where really the css class you want to use is "primary". If you want to add the class to the whole categories listbox, you could. And an easier way is to use this syntax:


categories.CssClass = "primary"

Which will work just the same as:


categories.Attributes.Add("class","primary")

Thanks for the replies.

I presume that the listItems not rendering their attributes must be a bug.

Looking at the source for the ListBox control, it doesn't appear to be rendering the attributes of its list items. Thus, I'll override the 'RenderContents' method or something and get the attributes rendered.
I think it is a bug too,

but the class browser indicated that the attributes property of the ListItem is readonly which would explain the attributes not being added to the listitem... maybe it is by design.

0 comments:

Post a Comment