[ACCEPTED]-Applying Styles To ListItems in CheckBoxList-coding-style

Accepted answer
Score: 27

You can add Attributes to ListItems programmatically 5 as follows.

Say you've got a CheckBoxList 4 and you are adding ListItems. You can add 3 Attributes along the way.

ListItem li = new ListItem("Richard Byrd", "11");
li.Selected = false;
li.Attributes.Add("Style", "color: red;");

This will make 2 the color of the listitem text red. Experiment 1 and have fun.

Score: 14

It seems the best way to do this is to create 3 a new CssClass. ASP.NET translates CheckBoxList 2 into a table structure.

Using something like


.chkboxlist td 


<asp:CheckBoxList ID="chkboxlist1" runat="server" CssClass="chkboxlist" />

will 1 do the trick

Score: 6

In addition to Andrew's answer...

Depending 20 on what other attributes you put on a CheckBoxList or 19 RadioButtonList, or whatever, ASP.Net will render the output 18 using different structures. For example, if 17 you set RepeatLayout="Flow", it won't render as a TABLE, so 16 you have to be careful of what descendant 15 selectors you use in your CSS file.

In most cases, you 14 can can just do a "View Source" on 13 your rendered page, maybe on a couple of 12 different browsers, and figure out what 11 ASP.Net is doing. There is a danger, though, that 10 new versions of the server controls or different 9 browsers will render them differently.

If 8 you want to style a particular list item 7 or set of list items differently without 6 adding in attributes in the code-behind, you 5 can use CSS attribute selectors. The only 4 drawback to that is that they aren't supported 3 in IE6. jQuery fully supports CSS 3 style attribute 2 selectors, so you could probably also use 1 it for wider browser support.

Score: 5

You can also achieve this in the markup.

<asp:ListItem Text="Good" Value="True" style="background-color:green;color:white" />
<br />
<asp:ListItem Text="Bad" Value="False" style="background-color:red;color:white" />

The 3 word Style will be underlined with the warning 2 that Attribute 'style' is not a valid attribute of element 'ListItem'., but the items are formatted as desired 1 anyway.

Score: 2

You can even have different font styles 1 and color for each word.

<asp:ListItem Text="Other (<span style=font-weight:bold;>please </span><span>style=color:Red;font-weight:bold;>specify</span>):" Value="10"></asp:ListItem>
Score: 1
public bool Repeater_Bind()
    RadioButtonList objRadioButton = (RadioButtonList)eventArgs.Item.FindControl("rbList");
    if (curQuestionInfo.CorrectAnswer != -1) {
        objRadioButton.Items[curQuestionInfo.CorrectAnswer].Attributes.Add("Style", "color: #b4fbb1;");


More Related questions