简体   繁体   中英

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 .

I have TextBox which contains the possible entry value.

So I want check if the ListBox already contains the value.

  • If this value is already inserted: DON'T add it.
  • If not: Add it.
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,

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM