更新时间:2023-11-25 23:48:52
尝试这个
try this
private void btnSubmit_Click(object sender, EventArgs e)
{
if (check())
{
}
else
{
bool isExists = false;
foreach (ListViewItem item in listView1.Items)
if (item.SubItems[2].Text == txtName.Text)
{
isExists = true;
break;
}
if (isExists)
MessageBox.Show("Your list already contains one person with that Name.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
else
add();
}
}
从调试器开始,查看check
返回的内容.
在处理程序的第一行上放置一个断点,然后逐步执行代码以查明发生了什么.
我的怀疑是check
返回的是true,因此它永远不会添加任何内容-但您不会向我们展示该方法的作用,它取决于您无法访问的数据,因此我们可以不说.
但是...如果您的add
方法将项目添加到列表视图中,则仍然可以正常工作.您不能从该集合的foreach循环内部修改该集合!
即使可以,您也会添加很多次!
Start with the debugger and see whatcheck
is returning.
Put a breakpoint on the first line of the handler, and step through your code to find out exactly what is happening.
My suspicion is thatcheck
is returning true so it never adds anything - but you don''t show us what that method does, and it will be dependant on your data which we don''t have access to so we can''t tell.
But...if youradd
method adds items to your listview, it work work anyway. You can''t modify a collection from inside a foreach loop on that collection!
And even if you could, you would add it an awful lot of times!