Search code examples
c#searchtextboxlistboxtext-files

search a textfile with a textbox


I have a textbox that I want to use to autosearch my text file and display the results in the listbox. the listbox already contains the first item of each line in the text file, so I basically want to search using only the first item of every line in the text file. The code I currently have does nothing.

private void custsearchbox_TextChanged(object sender, EventArgs e)
    {
        string[] autosource = File.ReadAllLines(@"data\Suppliers.txt");
        for (int g = 0; g < autosource.Length; g++)
        {
            custsearchbox.AutoCompleteCustomSource.Add(autosource[g]);
        }

            custsearchbox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
    }

I want to type the first item in my text box and search my listbox, as I enter my text I want the list to filter out the items that does not match. Please help me achieve this.


Solution

  • I tried this:

    private void supsearchtxt_TextChanged(object sender, EventArgs e)
        {
            listsup.Items.Clear();
            Supfile = System.AppDomain.CurrentDomain.BaseDirectory + "data\\Suppliers.txt";
            List<string> proName = new List<string>();
            using (StreamReader rdr = new StreamReader(Supfile))
            {
                string line;
                while ((line = rdr.ReadLine()) != null)
                {
                    if (line.Contains(supsearchtxt.Text))
                    {
                        string[] val = line.Split(',');
                        listsup.Items.Add(val[0]);
                    }
                }
            }
    
        }
    

    and it works great.