使用文本文件中的项目填充列表框 - 库存应用程序

时间:2017-04-27 07:13:30

标签: c# wpf combobox listbox inventory-management

所以我试图使用文本文件中的项目填充列表框然后我需要能够使用组合框对列表框项目进行排序,例如,如果我在组合框中选择汉堡,则只有汉堡应该在列表框。

到目前为止,我有这段代码:

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

问题是,它会填充列表框,但如果我点击组合框中的任何内容,它只会添加所有项目的增益,最终我会得到两倍的项目。

1 个答案:

答案 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 /结束(根据您的需要)当前项目。

相关问题