如果ListBox包含,请不要添加
我有一个方法:
FillListBox();
我从不同的地方调用这个方法..但有时会发生,事情被加载了两次!
现在我正在尝试做类似的事情:
if (listBox.Items[1].ToString() == "hello") { DO NOT FILL } else { FILL }
这不行! 🙁
Fault: InvalidArgument=Value of '1' is not valid for 'index'. Parameter name: index
这样的事情:
if(listBox.Items.Contains("hello")) { DONT FILL }
也不工作:(
我能做什么?
试试这个
if(ListBox.NoMatches != listBox.FindStringExact("StringToFind")) { listBox.Items.Add("StringToAdd"); }
或者只是试试这个
bool found = false; foreach (var item in listBox.Items) { if(item.ToString().Equals("StringToAdd")) { found = true; break; } } if(!found) listBox.Items.Add("StringToAdd");
尝试:
if ( listBox.Items.Cast().Any(x => x.Text == "hello"))
做这个:
var item = listBox.Items.FindByValue("hello") // or FindByText if (item != null) { DONT FILL }
你应该尝试一些方法
foreach(ListItem item in listBox) { if(item.Value == "YourFilter") { DONT FILL } }
如果您的项目是ASP
你应该做
foreach(object item in listBox) { if(item == "YourFilter") { DONT FILL } }
如果它是WPF,不确定你在谈论哪个ListBox。 显然这不是最优雅的解决方案,但我认为如果你刚开始学习C#是合适的。
我解决了问题..我刚使用myListBox.Items.Clear();
listBox.Items.Contains("hello")
应该可以正常工作。
String newValue = "hello"; if (listBox1.Items.Cast