ASP.NET: Hide CheckBox items in CheckBoxList control

Michael Itzoe picture Michael Itzoe · Sep 20, 2011 · Viewed 7.8k times · Source

I have a data-bound CheckBoxList control that can grow quite large, so I'm trying to create a filter for it. Here's what I'm doing:

foreach( ListItem item in this.UserRolesList.Items ) {
    if( !item.Value.StartsWith( this.RolesFilterList.SelectedValue ) ) {
        item.Attributes.CssStyle["display"] = "none";
    } else item.Attributes.CssStyle["display"] = "inline";
}

This mostly works, except that when ASP.NET renders the CheckBoxList, it does so using a table, with each CheckBox control nested within its own <TR> element. This means that even though the items I don't want to see aren't displayed, the white space for their rows is, so there's quite a bit of whites pace I still need to content with.

I'm not aware that I can access the <TR> element without subclassing the control, which this being a "nice-to-have" feature I don't have time to do, so I'm wondering if there's a CSS trick I can use to access an element's parent's parent (e.g., <input type="checkbox"/> -> <td> -> <tr>). I've used the :first-child pseudo-element before, but my web searches for this kind of trick have been fruitless, so I have my doubts. Can't hurt to ask though, right?

Answer

patmortech picture patmortech · Sep 20, 2011

This might work for you. It removes the item from the list completely so that it does not get rendered at all:

string value = this.RolesFilterList.SelectedValue;
int count = this.UserRolesList.Items.Count - 1;

for(var i=count;i>=0;i--)
{
    ListItem item = this.UserRolesList.Items[i];
    if (!item.Value.StartsWith(value))
    {
        this.UserRolesList.Items.RemoveAt(i);
    }
}

Update

Based on your comment above about how you want this to operate from a user's standpoint, you would probably be better off doing this all client-side in javascript, rather than doing it on a postback in this manner.

In jQuery, you could create a function to run when the select list is changed that would then find all the checkboxes in the UserRolesList table, and then loop through them, and based on their value use the .closest('tr') function to hide/show the whole table row that contains them.