C # List Search Box

I have a large number of items in a listBox called listBox1. I also have textBox (textBox1) at the top. I want to be able to type in a textBox, and the listBox searches through it for an element and finds those that contain what I am typing.

For example, say listBox contains

"Cat"

"Dog"

"Carrot"

and "brocolli"

If I start typing the letter C, then I want it to show both Cat and Carrot, when I type, it should show both of them, but when I add r, it should remove Cat from the list. Is there any way to do this?

+3
source share
5 answers

Filter the list. Try the following:

    List<string> items = new List<string>();
    private void Form1_Load(object sender, EventArgs e)
    {
        items.AddRange(new string[] {"Cat", "Dog", "Carrots", "Brocolli"});

        foreach (string str in items) 
        {
            listBox1.Items.Add(str); 
        }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        listBox1.Items.Clear();

        foreach (string str in items) 
        {
            if (str.StartsWith(textBox1.Text, StringComparison.CurrentCultureIgnoreCase))
            {
                listBox1.Items.Add(str);
            }
        }
    }
+5
source

; ...

    public partial class Form1 : Form
    {
        List<String> _animals = new List<String> { "cat", "carrot", "dog", "goat", "pig" };

        public Form1()
        {
            InitializeComponent();

            listBox1.Items.AddRange(_animals.ToArray());
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            String search = textBox1.Text;

            if (String.IsNullOrEmpty(search))
            {
                listBox1.Items.Clear();
                listBox1.Items.AddRange(_animals.ToArray());
            }

            var items = (from a in _animals
                        where a.StartsWith(search)
                        select a).ToArray<String>();

            listBox1.Items.Clear();
            listBox1.Items.AddRange(items);
        } 
    }
+1
source

To get the result that the request expects, you should use the Contains method instead of the StartWith method. Like this: -

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        listBox1.Items.Clear();

        foreach (string str in items)
        {
            if (str.ToUpper().Contains(textBox1.Text.ToUpper()))
            {
                listBox1.Items.Add(str);
            }
        }
    }

I was looking for it.

+1
source

I think you need to use the linq query and then databind the result. An example of this in WPF is here , but I believe that you can do the same in winforms.

0
source

Source: https://habr.com/ru/post/1789579/


All Articles