复选框列表集合已修改枚举操作可能无法执行

Check Box list collection was modified enumeration operation may not execute

我在这个Question中看到了很多例子,但直到没有得出结论。我尝试了所有这些 EXAMPLES。我正在尝试从数据库中删除绑定的空复选框列表。

DataSet ds4 = getCheckBox(ViewState["id"].ToString());
        chkEnvironment.DataSource = ds4;
        chkEnvironment.DataTextField = "Environment";
        chkEnvironment.DataValueField = "Environmentid";
        chkEnvironment.DataBind();

但它在我的页面中显示空复选框。怎么做

protected void chkEnvironment_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem item in chkEnvironment.Items)
        {
            if (item.Value == "NULL")
            {
                chkEnvironment.Items.Remove(item);
            }
        }
    }

您不能在枚举期间修改集合。您可以存储稍后要删除的项目:

var itemsToRemove = new List<ListItem>();
foreach (ListItem item in chkEnvironment.Items)
{
    if (item.Value == "NULL")
    {
        itemsToRemove.Add(item);
    }
}
foreach(var item in  itemsToRemove)                 
    chkEnvironment.Items.Remove(item);

与 LINQ 相同:

var itemsToRemove = chkEnvironment.Items.Cast<ListItem>()
    .Where(i => i.Value ==  "NULL")
    .ToList();
foreach(var item in  itemsToRemove)                 
    chkEnvironment.Items.Remove(item);