2017-04-27 50 views
0

所以我想用一個文本文件中的項來填充列表框,然後我需要能夠使用組合框對列表框項進行排序,例如,如果我選擇漢堡在組合框上只有漢堡包應該在列表框中。從文本文件中填充列表框 - 庫存應用程序

到目前爲止,我有這樣的代碼:

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); 
       } 
      } 
     } 
    } 
} 

問題是,它將填充列表框,但如果我點擊下拉框任何東西它只是增加了對收益的所有項目和我結束了兩倍之多項目。

+2

添加之前,在方法開始之前清除所有項目。 'listBox.Items.Clear()' – Nino

+0

感謝像魅力 –

回答

2

因爲您正在將項目添加到組合框的每個選擇更改事件中,如果沒有必要在每個選擇更改事件中添加項目,則可以將代碼移動到構造函數中。如果您確實想刷新每次選擇更改的項目,請在評論中建議使用listBox.Items.Clear()作爲Nino。總之你可以做的最好的事情如下:

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); 
       } 
      } 
     } 
} 

現在你可以在構造函數InitializeComponent()之後調用該方法;如果需要的話在categoryComboBox_SelectionChanged

關於基於組合框中的selectedItem過濾項目: 在將項目添加到列表框之前,您必須檢查項目是否包含/ startwith/ends(根據您的需要)當前項目。

+0

工作,但他說,他需要排序,即項目過濾。 。 。 –

+0

@ZainUlAbidin:謝謝,我已更新帖子請看看 –