我想在将其添加到ListBox
之前检查可能的条目的值。如何检查列表框中是否存在某个值?
我有TextBox
其中包含可能的输入值。
所以我想检查一下ListBox
是否已经包含这个值。
- 如果这个值已经被插入:不要添加它。
- 如果不是:添加它。
我想在将其添加到ListBox
之前检查可能的条目的值。如何检查列表框中是否存在某个值?
我有TextBox
其中包含可能的输入值。
所以我想检查一下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());
谢谢这对我有帮助:) –
yw!祝你好运!! –
只是比较的项目在您与您正在寻找的值列表。您可以将该项目转换为字符串。
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;
}
}
您可以使用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
}
希望帮助,
你有搜索或尝试过的东西?这是正常的添加您的问题。 – JTIM
您是否尝试在列表框中运行查找或循环并通过列表框中的项目进行比较? –
对不起,我是编程新手,所以我不太了解'C#中的代码' –