C#CheckedListBox在foreach循环上的InvalidOperationException
问题描述:
我不知道我在做什么错,但我不断收到此错误。有谁知道这可能是什么原因造成的?C#CheckedListBox在foreach循环上的InvalidOperationException
InvalidOperationException 该枚举器绑定的列表已被修改。 仅当列表不更改时才能使用枚举数。
public static string[] WRD = new string[] {"One","Two","Three","Four"}
public static string[] SYM = new string[] {"1","2","3","4"}
//this is how I'm populating the CheckedListBox
private void TMSelectionCombo_SelectedIndexChanged(object sender, EventArgs e)
{
TMSelection.Items.Clear();
switch (TMSelectionCombo.SelectedItem.ToString())
{
case "Words":
foreach (string s in WRD)
{
TMSelection.Items.Add(s);
}
break;
case "Symbols":
foreach (string s in SYM)
{
TMSelection.Items.Add(s);
}
break;
}
}
//this is where the problem is
private void AddTMs_Click(object sender, EventArgs e)
{
//on this first foreach the error is poping up
foreach (Object Obj in TMSelection.CheckedItems)
{
bool add = true;
foreach (Object Obj2 in SelectedTMs.Items)
{
if (Obj == Obj2)
add = false;
}
if (add == true)
TMSelection.Items.Add(Obj);
}
}
答
的枚举,如果列表不改变,只能使用。
烨
创建的要添加,然后加入你要修改的列表列表什么其他列表。
像这样:
List toAdd = new List()
for(Object item in list) {
if(whatever) {
toAdd.add(item);
}
}
list.addAll(toAdd);
答
不能更改TMSelection列举的项目。
例
List<string> myList = new List<string>();
foreach (string a in myList)
{
if (a == "secretstring")
myList.Remove("secretstring"); // Would throw an exception because the list is being enumerated by the foreach
}
要解决此问题,使用临时表。
例
List<string> myList = new List<string>();
List<string> myTempList = new List<string>();
// Add the item to a temporary list
foreach (string a in myList)
{
if (a == "secretstring")
myTempList.Add("secretstring");
}
// To remove the string
foreach (string a in myTempList)
{
myList.Remove(a);
}
因此,在你〔实施例,添加新的项目到一个临时目录,然后foreach循环后的每个项目添加到主列表。
什么是TMSelection?这可能是因为你在foreach循环中添加了一个项目。 – 2012-02-14 22:06:56