Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare a string to all items in a listbox?

Tags:

c#

winforms

I'm creating an application that allows the user to store information about their classes. There is a button in my application that allows the user to enter information and if it matches any item in the listBox then it should display information about it.

I can only get it to work if I specify a particular item by position (e.g. Items[0]) of the listBox and then convert it to a string. My aim is to compare all items in the listBox.

private void button3_Click(object sender, EventArgs e)
{
    if (listBox2.Items[0].ToString() == "PersonalInfo")
    {
        label.Text = "test";               
    }
}
like image 744
Hashey100 Avatar asked Jun 13 '12 19:06

Hashey100


3 Answers

You need to loop through all of the items in the list. Try something like this:

foreach(var item in listBox2.Items)
{
  if(item.ToString() == stringToMatch)
  {
    label.Text = "Found a match";
  }
}

An alternate, simpler implementation (which will stop if/when it finds a match instead of continuing to check every item) would be

if(listBox2.Items.Any(item => item.ToString() == stringToMatch))
{
  label.Text = "Found a match";
}
like image 74
yoozer8 Avatar answered Oct 21 '22 07:10

yoozer8


Write a loop to check each item

foreach(var item in listBox2.Items)
{
  if (item.ToString()== "PersonalInfo")
  {
     label.Text = "test";
     break; // we don't want to run the loop any more.  let's go out              
  }    
}
like image 37
Shyju Avatar answered Oct 21 '22 08:10

Shyju


Well you could use LINQ... something like this:

if (listBox2.Items
            .Cast<object>()
            .Select(x => x.ToString())
            .Contains("PersonalInfo"))
{
    label.Text = "test";
}

Or if you want to get the details of the first match:

var match = listBox2.Items
                    .Cast<object>()
                    .FirstOrDefault(x => x.ToString() == "PersonalInfo");
if (match != null)
{
    // Use match here
}
like image 5
Jon Skeet Avatar answered Oct 21 '22 08:10

Jon Skeet