views:

195

answers:

2

I'm having trouble figuring this out. If I have a checkboxlist inside a usercontrol, how do I loop through (or check, really) what boxes are checked in the list?

As I said in the comment below, I'd like to expose the checked items through a property in the control itself.

+3  A: 

From your page you can do

var checkboxes = (CheckBoxList)userControl1.FindControl("checkBoxList1");

But a better solution in my mind would be to expose the checked items through a property or method.

In user control

public string[] CheckedItems {
    get {
        List<string> checkedItems = new List<string>();
        foreach (ListItem item in checkbox1.Items)
            checkedItems.Add(item.Value);

        return checkedItems.ToArray();
    }
}

Then in the page

var checkedItems = userControl1.CheckedItems;

You could also just return checkbox1.Items in the property, but that isn't good encapsulation.

Bob
Right, that's what I want to do - expose the checked items through a property.
somacore
I changed my code to use a property instead of a method.
Bob
Awesome. Thank you!
somacore
+1  A: 

If you are using .net 3.5, you can create a readonly property that uses LINQ to return an IList of just the selected values:

  public IList<string> SelectedItems{
       get {
          return checkbox1.Items.Cast<ListItem>.Where(i => i.Selected).Select(j => j.Value).ToList();
       }

    }
Dan Appleyard
Only barely using .net 3.0 =\
somacore