Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom render CheckBoxList items to have a class set on the LI

Tags:

c#

asp.net

I have a CheckBoxList (framework version 4), with the RepeatLayout set to UnOrderedList. I would like to generate a class on each LI to simplify some client side coding and styling, however, I can't get it.

I override the RenderItem method as follows:

protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
    ListItem item = Items[repeatIndex];
    String id = ClientID + "_" + repeatIndex.ToString();
    String name = UniqueID + "$" + repeatIndex.ToString();

    writer.Write(@"<li class='{0}'>", "tcsdrp_day" + (item.Selected ? " selected" : ""));
    writer.Write(@"<input id='{0}' type='checkbox' name='{1}' value='{2}'>", new object[] { id, name, item.Value });
    writer.Write(@"<label for='{0}'>{1}</label>", new object[] { id, item.Text });
    writer.Write(@"</li>");
}

However, I get a load of blank LIs generated, so obviously they are being rendered in the caller, or somewhere else, and I can't for the life of me work out where.

Got around it now by adding the class to the ListItems, but that creates an extra SPAN which I would ideally like to lose.

Is there any good way of doing this?

EDIT: This is a cut down demo; the final version will have logic to generate different classes based on the original data item properties, in case anyone is wondering why I need to add a class at all.

EDIT 2: I have now got around my immediate problem of simplifying the markup by changing the RenderItem to use the label-wrapping-the-input style:

writer.Write(@"<label class='{0}'>", labelclass);
writer.Write(@"<input id='{0}' type='checkbox' name='{1}' value='{2}'{3}>", new object[] { id, name, item.Value, item.Selected ? " checked" : "" });
writer.Write(item.Text);
writer.Write(@"</label>");

I'd still like to know if there is any way to completely customize item rendering though.

like image 581
Whelkaholism Avatar asked Dec 20 '12 16:12

Whelkaholism


1 Answers

In the PreRender event, iterate through the Items-Collection, and assign classes as you need:

For Each l As ListItem In Items
  If l.Value = "1" Then
    l.Attributes.Add("class", "myClass")
  End If
Next l
like image 54
Alexander Avatar answered Sep 29 '22 11:09

Alexander