用文本文件中的项目填充列表框 - 库存应用程序
Filling listbox with items from text file - inventory application
所以我尝试使用文本文件中的项目填充列表框,然后我需要能够使用组合框对列表框项目进行排序,例如,如果我在组合框中选择汉堡,则只有汉堡应该是在列表框中。
到目前为止我有这个代码:
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);
}
}
}
}
}
问题是,它会填充列表框,但如果我单击组合框上的任何内容,它只会添加所有获得的项目,最终我得到两倍的项目。
因为您是在组合框的每个选择更改事件中向列表框添加项目,如果不需要在每个选择更改事件中添加项目,那么您可以将代码移至构造函数。如果您真的想刷新每个选择更改中的项目,则意味着使用 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 过滤项目:
在将项目添加到列表框之前,您必须检查项目 contains/startwith/ends 是否具有(根据您的需要)当前项目。
所以我尝试使用文本文件中的项目填充列表框,然后我需要能够使用组合框对列表框项目进行排序,例如,如果我在组合框中选择汉堡,则只有汉堡应该是在列表框中。
到目前为止我有这个代码:
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);
}
}
}
}
}
问题是,它会填充列表框,但如果我单击组合框上的任何内容,它只会添加所有获得的项目,最终我得到两倍的项目。
因为您是在组合框的每个选择更改事件中向列表框添加项目,如果不需要在每个选择更改事件中添加项目,那么您可以将代码移至构造函数。如果您真的想刷新每个选择更改中的项目,则意味着使用 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 过滤项目: 在将项目添加到列表框之前,您必须检查项目 contains/startwith/ends 是否具有(根据您的需要)当前项目。