Home > Software design >  Search for word in ListBox written on InputBox (C# VS)
Search for word in ListBox written on InputBox (C# VS)

Time:11-29

I have a ListBox with words and I need to click a button that opens an InputBox where I can search for a word and the program will run the ListBox and highlight the word I wrote in the InputBox if it's there. If the program reaches the end of the list and doesn't find the word then I'll get a MessageBox saying the word I'm looking for isn't there. I need to use some sort of cycle for this program.

I know how to make the button, InputBox and the error MessageBox, but I don't know how to do the searching and cycle.

I've read a lot of similar questions here but I don't think any of them return the result I'm looking for.

Can anyone help me? Or redirect me to a post with the answer?

This is for Winforms.

CodePudding user response:

That should get you on track, it's pretty much self-explanative:

  • whenever text changes
  • find matching items in list
  • select them

enter image description here

Code:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    var textBox = sender as TextBox ?? throw new InvalidOperationException();

    var text = textBox.Text;

    if (string.IsNullOrWhiteSpace(text))
        return; // nothing to search for

    const StringComparison comparison = StringComparison.InvariantCultureIgnoreCase; // maybe change this

    // find items matching text

    var indices = new List<int>();

    for (var i = 0; i < listBox1.Items.Count; i  )
    {
        var item = listBox1.Items[i];

        if (string.Equals(item?.ToString(), text, comparison))
            indices.Add(i);
    }

    // select them in list

    if (!indices.Any())
        return;

    listBox1.SelectedIndices.Clear();

    foreach (var index in indices) 
        listBox1.SelectedIndices.Add(index);
}

Of course, list selection mode has to be multiple for it to work properly.

Also, you will need to clear selection if there are no matches so as to not leave the UI in an ambiguous state (not done).

  • Related