gpt4 book ai didi

c# - 编译错误集合被修改

转载 作者:行者123 更新时间:2023-11-30 20:39:23 25 4
gpt4 key购买 nike

我收到类似这样的错误

Collection was modified; enumeration operation may not execute while executing my code.

我的要求如下 enter image description here在文本框中输入任何文本并选择单选按钮,该文本将作为项目添加到列表框中。如果您输入的文本已经存在于文本框中,则不允许

代码- enter image description here

这是我的代码-

            foreach (ListItem li in ListBox1.Items)
{
if (li.Text.ToUpper() != TextBox1.Text.ToUpper())
{
ListBox1.Items.Add(TextBox1.Text);
Label2.Text = "<b style='color:green'> item updated in list box </b>";
}
else
{
Label2.Text = "<b style='color:red'> access denied </b>";
}
}

我在foreach循环中遇到错误

最佳答案

很简单,不能修改foreach内部循环使用的变量。只需使用 for 循环即可:

for (int i = 0; i < ListBox1.Items.Count; i++)
{
ListItem li = ListBox1.Items[i];
if (li.Text.ToUpper() != TextBox1.Text.ToUpper())
{
ListBox1.Items.Add(TextBox1.Text); Label2.Text = "<b style='color:green'> item updated in list box </b>";
}
else { Label2.Text = "<b style='color:red'> access denied </b>"; }
}

附言如果您只想遍历现有项目而不是在循环内添加,则应将当前项目的 Count 保存在变量中:

var itemCount = ListBox1.Items.Count;
for (int i = 0; i < itemCount ; i++)
{
//...
}

关于c# - 编译错误集合被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com