Master Chef
Master Chef

Reputation: 65

Filling listbox with items from text file - inventory application

So I'm trying to fill a listbox using items from a text file then I need to be able to sort the listbox items using a combo box, for example if I pick burger on the combo box only burgers should be in the listbox.

So far I have this code:

private void categoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(@"inventory.txt"))
        {
            while (!sr.EndOfStream)
            {
                for (int i = 0; i < 22; i++)
                {
                    string strListItem = sr.ReadLine();
                    if (!String.IsNullOrEmpty(strListItem))
                    listBox.Items.Add(strListItem);
                }
            }
        }
    }
}

Problem is, it will populate the listbox but if I click anything on the combobox it just adds all the items on gain and I end up with twice as many items.

Upvotes: 0

Views: 203

Answers (1)

sujith karivelil
sujith karivelil

Reputation: 29036

Because you are adding items to the listbox in every selection changed event of the combobox, if it is not necessary to add the items in every selection changed event then you can move the code to the constructor. If you really want to refresh the items in every selection change means use listBox.Items.Clear() as Nino suggested in the comment. In short the best thing that you can do is as follows:

public void PopulateList()
{
   listBox.Items.Clear();
   using (System.IO.StreamReader sr = new System.IO.StreamReader(@"inventory.txt"))
        {
            while (!sr.EndOfStream)
            {
                for (int i = 0; i < 22; i++)
                {
                    string strListItem = sr.ReadLine();
                    if (!String.IsNullOrEmpty(strListItem) && 
                       (categoryComboBox.SelectedItem!=null &&     
                       (strListItem.Contains(categoryComboBox.SelectedItem.ToString())))
                    listBox.Items.Add(strListItem);
                }
            }
        }
 }

Now you can call the method in the constructor after InitializeComponent(); and in the categoryComboBox_SelectionChanged if needed.

Regarding filtering items based on selectedItem in the combobox: You have to check whether the item contains/startwith/ends with( as per your need) the current items before adding them to the list box.

Upvotes: 2

Related Questions