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.
-
According to the MSDN documentation, there doesn't appear to be. You'll have to iterate the items yourself.j.f.– j.f.2015-10-20 17:07:50 +00:00Commented Oct 20, 2015 at 17:07
-
Yeah, @j.f. I don't know why that isn't built in. Thanks, though.Lorek– Lorek2015-10-20 17:10:25 +00:00Commented Oct 20, 2015 at 17:10
-
Hey, @j.f., would you mind voting up my question so I can earn my Student badge?Lorek– Lorek2015-10-20 20:08:58 +00:00Commented Oct 20, 2015 at 20:08
2 Answers
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();
}
1 Comment
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;
}