user3620337
user3620337

Reputation: 11

Check if a ListBox Item has same Text as a TextBox Text

I make it short:

How can I check if a TextBox contains the same text as a ListBox item? I try to add this function to a timer which scans it each second.
If there is a name which is in the TextBox it should show a msgbox.

Is that possible?

Upvotes: 1

Views: 1524

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460148

You can use LINQ:

bool contains = listBox1.Items.Cast<object>().Contains(textToFind);

Note that C# is case-sensitive, if you want a case insensitive search

contains = listBox1.Items.Cast<object>()
     .Any(o => o.ToString().Equals(textToFind, StringComparison.CurrentCultureIgnoreCase));

if(contains)
   MessageBox.Show("ListBox contains " + textToFind);

Upvotes: 3

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26645

Check this in TextChanged event of your TextBox.

void textBox1_TextChanged(object sender, EventArgs e)
{
    if(ListBox1.Items.Cast<string>().Any(x => x == TextBox1.Text))
    {
         MessageBox.Show("Message");
    }
}

Upvotes: 3

Related Questions