在 ASP.NET 中获取 CheckBoxList 的选定索引数组的简单方法

Easy way to get array of selected indexes of CheckBoxList in ASP.NET

CheckBoxList class 上是否有 属性 或方法 return 表示所有选定索引的整数数组?这是在 ASP.NET.

您可以创建一个扩展方法来模拟您想要的行为。这样做的好处是您可以在任何列表控件上重复使用它。下面是一个粗略的例子(我只是 return 值的字符串列表,你可以 return 任何东西,索引、值、整个列表项等)。

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;
}

根据 MSDN documentation,似乎没有。您必须自己迭代这些项目。

这里有一个方法可以做到这一点。它迭代每个项目,检查它是否被选中,然后将索引添加到列表中。我使用列表是因为列表是可变的而数组不是。然后给return一个数组,我只要调用ToArray()就行了

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();
}