[英]How can I check if a value already exists in a ListBox?
I want to check the value of a possible entry before I add it to the ListBox
.我想在将它添加到
ListBox
之前检查可能条目的值。
I have TextBox
which contains the possible entry value.我有包含可能的条目值的
TextBox
。
So I want check if the ListBox
already contains the value.所以我想检查
ListBox
已经包含该值。
if (!listBoxInstance.Items.Contains("some text")) // case sensitive is not important
listBoxInstance.Items.Add("some text");
if (!listBoxInstance.Items.Contains("some text".ToLower())) // case sensitive is important
listBoxInstance.Items.Add("some text".ToLower());
Just compare the items in you list with the value you are looking for.只需将列表中的项目与您要查找的值进行比较。 You can cast the item to String.
您可以将项目转换为字符串。
if (this.listBox1.Items.Contains("123"))
{
//Do something
}
//Or if you have to compare complex values (regex)
foreach (String item in this.listBox1.Items)
{
if(item == "123")
{
//Do something...
break;
}
}
You can use linq,您可以使用 linq,
bool a = listBox1.Items.Cast<string>().Any(x => x == "some text"); // If any of listbox1 items contains some text it will return true.
if (a) // then here we can decide if we should add it or inform user
{
MessageBox.Show("Already have it"); // inform
}
else
{
listBox1.Items.Add("some text"); // add to listbox
}
Hope helps,希望有所帮助,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.