sim.plified.com

Chris Pollock

Chris Pollock - web developer (PHP/mySQL & ASP.NET)
undivided… my thoughts on world, family, church, business, technology and Jesus Christ (all in all)

CheckBoxList as and Unordered List (CSS Stylable)

The CheckBoxList control in ASP.NET is great because the control handles all the data for you.  However, if you want to enhance the UI a little bit the control is left wanting for sure.  This led me to do some searching for CheckBoxList alternatives.  I came up with two blogs posts (one here, the other here) that recommended creating a Custom Server Control that encapsulated the CheckBoxList inside of an unordered list. I went this route and the results were fantastic:

Roberts-Wesleyan-College---Rochester,-NY_1208529940272

I used the Server Control to change the CSS Class of the enclosing list item when the item is selected.  That allowed me to apply some nice CSS styling to to any item that was selected.  (As a side note the entire block is enclosed in an UpdatePanel, so clicking the options changes the data below dynamically).

I have enclosed my code for my custom server control below.  I borrowed from the the two blog posts above, but added some additional data to account for "AutoPostBack" and the applying CSS Styling to the selected item.  I'm am also making the compiled DLL available for download here.

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace edu.roberts.its.CustomWebControls

    <DefaultProperty("Text"), ToolboxData("<{0}:ULCheckBoxList runat=server></{0}:ULCheckBoxList>")> _
    Public Class ULCheckBoxList
        Inherits CheckBoxList

        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)

            Controls.Clear()

            Dim inputFormatString As String = "<input id={0}{1}{0} name={0}{2}{0} type={0}checkbox{0} value={0}{3}{0} {4} {5} />"
            Dim labelFormatString As String = "<label for={0}{1}{0}>{2}</label>"

            If (Not MyBase.CssClass Is Nothing AndAlso MyBase.CssClass <> "") Then
                writer.WriteLine("<ul class=""" & MyBase.CssClass & """>")
            Else
                writer.WriteLine("<ul>")
            End If

            For index As Integer = 0 To Items.Count - 1

                Dim inputBuilder As New StringBuilder
                Dim labelBuilder As New StringBuilder
                Dim checked As String = ""

                If (Items(index).Selected) Then
                    checked = "checked=""checked"""
                End If

                'Add selected class to the list item if the checkbox is checked.
                writer.Indent += 1
                writer.WriteLine("<li class=""" & IIf(Items(index).Selected, "selected", "") & """>")
                writer.Indent += 1

                Dim postbackScript As String = ""
                If MyBase.AutoPostBack = True Then
                    postbackScript = String.Format("onclick=""javascript:setTimeout('__doPostBack(\'{0}\',\'\')', 0)""", MyBase.UniqueID & "$" & index.ToString())
                End If

                inputBuilder.AppendFormat(inputFormatString, """", MyBase.ClientID & "_" & index.ToString(), MyBase.UniqueID & "$" & index.ToString(), Items(index).Value, checked, postbackScript)
                labelBuilder.AppendFormat(labelFormatString, """", MyBase.ClientID & "_" & index.ToString(), Items(index).Text)

                writer.WriteLine(inputBuilder.ToString())
                writer.WriteLine(labelBuilder.ToString())

                writer.Indent -= 1

                writer.WriteLine("</li>")
                writer.WriteLine()
                writer.Indent -= 1

            Next

            writer.WriteLine("</ul>")

        End Sub

    End Class

End Namespace

13 Comments, Comment or Ping

  1. Travis

    Great article - can you provide the CSS for it as well?

  2. Sure here it is:

    ul.colorCheck { list-style: none; margin: 0; padding: 0; }
    .colorCheck li { float: left; width: 210px; line-height: 18px; padding: 0; margin: 0 5px 5px 0; border: 1px solid #ccc; height: 23px; overflow: hidden; background: #fff; }
    .colorCheck li.selected { background: #00B200; color: #fff; }

  3. Chris

    Fantastic help thanks. I'm having trouble implementing the CSS though, it actually causes an overflow and all my items are highlighted as though they are all selected, any ideas?

  4. @Chris

    First thought: Are you clearing the "checked" variable when you go through the loop in the control?

  5. Dhruv Patel

    I believe this is the same technique you used for patterntap also correct? would you be able to elaborate on that anytime soon? thanks

  6. leo

    Hi,
    I'm just new with c# I will happy to get help about the integration to aspx page.
    I created in the app code the class but I don't know how to use it in aspx page:
    In code behind I see the control…but i don't see it in the designer.
    I looked for but i didn't find it.
    I'll happy to get help.
    Thanks a lot
    Leo

  7. Dave

    Hi Chris,

    Great article! I am not using it as-is, but am modifying it to use a with multiple s per row (so I can simulate the hanging indent when the text wraps).

    I noticed that if I didn't have the ID for the tag, the selected state wasn't getting posted back.

    ""
    works, whereas
    ""
    does not work.

    I just figured I'd mention it in case the tag or other tags run into issues with a missing ID.

    Thanks for the writeup!

  8. Dave

    Oops - I guess the comment editor doesn't like tags…

    <table id=""" & MyBase.UniqueID & """>
    works whereas
    <table>
    does not.

    Let's see if this code snippet shows up :)

  9. Superb! Thanks for the compiled DLL… worked like a charm!

  10. Shahid Lone

    Superb.. Thanks!

  11. dameron

    For those who asked about how to use it… Here is a sample html and code behind

    ul.colorCheck { list-style: none; margin: 0; padding: 0; }
    .colorCheck li { float: left; width: 210px; line-height: 18px; padding: 0; margin: 0 5px 5px 0; border: 1px solid #ccc; height: 23px; overflow: hidden; background: #fff; }
    .colorCheck li.selected { background: #00B200; color: #fff; }

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
    ULCheckBoxList1.DataTextField = "skill"
    ULCheckBoxList1.DataValueField = "id"
    ULCheckBoxList1.DataSource = GetSomeData()
    ULCheckBoxList1.DataBind()
    End If
    End Sub

  12. dameron

    Sorry it didn't put all of my text in… here is a link to download the sample
    http://incasestudio.com/checkbox-sample.txt

Reply to “CheckBoxList as and Unordered List (CSS Stylable)”

Things I see

Niagara FallsNiagara FallsNiagara FallsNiagara FallsNiagara FallsFishing TripFishing TripFishing TripFishing TripFishing TripFishing TripFishing TripFishing TripFishing TripFishing Trip

Chris Pollock

Web Developer - proficient in both PHP and ASP.NET.
Rochester, New York

View my web developement site.

View Chris Pollock's LinkedIn profile

My Pictures

Niagara FallsNiagara FallsNiagara FallsNiagara FallsNiagara FallsFishing TripFishing TripFishing TripFishing TripFishing TripFishing TripFishing TripFishing TripFishing TripFishing Trip