簡體   English   中英

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

[英]How can I check if a value already exists in a 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());

只需將列表中的項目與您要查找的值進行比較。 您可以將項目轉換為字符串。

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
}

希望有所幫助,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM