如何检查ListBox中是否已存在值?

时间:2016-09-28 10:37:56

标签: c#

我想在将其添加到ListBox之前检查可能条目的值。

我有TextBox,其中包含可能的条目值。

所以我想检查ListBox是否已包含值。

  • 如果已插入此值:不要添加它。
  • 如果不是:添加它。

3 个答案:

答案 0 :(得分:2)

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());

答案 1 :(得分:0)

只需将列表中的项目与您要查找的值进行比较即可。您可以将项目转换为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;
   }
}

答案 2 :(得分:0)

您可以使用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
}

希望有所帮助,