There have been several times when a designer has come to me with a grumpy face and said “Hey Naveed!, this <asp:CheckBoxList runat=”server” ID=”myCheckBoxList”/> spits out <span> or <table> tags instead of <ul> and <li> tags for list items. It doesn’t match my templated HTML/CSS and is not going to pass W3C validation, can you fix it please?”
This issue is actually fixed in .NET 4 (why it took Microsoft so long, don’t know), but if you are not using .NET 4 then here is a simple server side control which you can use to render items as unordered list
Step 1: Add a new class file from VS and name it as ULCheckBoxList
Step 2: Inherit the class from standard .NET CheckBoxList
Step 3: Overwrite the Render() method of the control
Complete code snippet is given below
[ToolboxData("<{0}:ULCheckBoxList runat=server></{0}:ULCheckBoxList>")] public class ULCheckBoxList : CheckBoxList { protected override void Render(HtmlTextWriter writer) { // We start our un-ordered list tag. writer.WriteBeginTag("ul"); // If the CssClass property has been assigned, we will add // the attribute here in our <ul> tag. if (this.CssClass.Length > 0) { writer.WriteAttribute("class", this.CssClass); } // We need to close off the <ul> tag, but we are not ready // to add the closing </ul> tag yet. writer.Write(">"); // Now we will render each child item, which in this case // would be our checkboxes. for (int i = 0; i < this.Items.Count; i++) { // We start the <li> (list item) tag. writer.WriteBeginTag("li"); writer.Write(">"); this.RenderItem(ListItemType.Item, i, new RepeatInfo(), writer); // Close the list item tag. writer.WriteEndTag("li"); } // We finish off by closing our un-ordered list tag. writer.WriteEndTag("ul"); } }
In your web.config or in your control’s .ascx add the reference to the control something like
<%@ Register Assembly="Web.Helper" TagPrefix="myControls" Namespace="Web.Helper.WebControls" %>
and use it as
<myControls:ULCheckBoxList runat="server" CssClass="list" ID="myCheckBoxList" />
Set the DataSource for the control in code behind and bind the data something like
myCheckBoxList.DataSource = myItems; myCheckBoxList.DataBind();
Enjoy!
One thought on “CSS Friendly CheckboxList”