1

Is there a property or a method on the CheckBoxList class that will return an array of ints that represents all of the selected indexes? This is in ASP.NET.

3
  • According to the MSDN documentation, there doesn't appear to be. You'll have to iterate the items yourself. Commented Oct 20, 2015 at 17:07
  • Yeah, @j.f. I don't know why that isn't built in. Thanks, though. Commented Oct 20, 2015 at 17:10
  • Hey, @j.f., would you mind voting up my question so I can earn my Student badge? Commented Oct 20, 2015 at 20:08

2 Answers 2

1

According to the MSDN documentation, there doesn't appear to be. You'll have to iterate the items yourself.

Here is a method that does just that. It iterates each item, checks if it is selected, then adds the index to a list. I use a list because a list is mutable whereas an array is not. Then to return an array, I just call ToArray() on the list.

public int[] selectedIndexesOfCheckBoxList(CheckBoxList chkList)
{
    List<int> selectedIndexes = new List<int>();

    foreach (ListItem item in chkList.Items)
    {
        if (item.Selected)
        {
            selectedIndexes.Add(chkList.Items.IndexOf(item));
        }
    }

    return selectedIndexes.ToArray();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, j.f., would you mind up-voting my question so I can earn my Student badge?
1

You could create an extension method to simulate the behavior you want. The benefit of that being that you could re-use it on any list control. Below is a rough example (I'm just returning the list of strings of the values, you could return anything though, the index, the value, the entire list item, etc.).

public static List<string> SelectedValues(this ListControl lst)
{
    List<string> returnLst = new List<string>();

    foreach (ListItem li in lst.Items)
    {
        if (li.Selected == true)
        {
            returnLst.Add(li.Value);
        }

    return returnLst;
}

2 Comments

That's not how you define an extension method in C#, BTW.
You're right @DStanley, I updated the example. This would need to be in a static class also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.