【发布时间】:2017-05-03 15:30:07
【问题描述】:
如果之前有人问过这个问题,我深表歉意,但我已经很接近解决这个问题了,基本上,当我单击组合框时,它为我提供了 4 个选项来过滤列表框(全部、披萨、汉堡、杂物) Pizza、Burger 和 Sundry 是类别名称中的词。如何使我的列表框仅显示在组合框中选择的内容。
class InventoryItem
{
public string CategoryName { get; set; }
public string FoodName { get; set; }
public double Cost { get; set; }
public double Quantity { get; set; }
public override string ToString()
{
return $"{CategoryName} - {FoodName}. Cost: {Cost:0.00}, Quantity: {Quantity}";
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void inventoryButton_Click(object sender, RoutedEventArgs e )
{
InventoryWindow wnd = new InventoryWindow();
//Var filepath allows the code to access the Invenotry.txt from the bin without direclty using a streamreader in the code
var filePath = "inventory.txt";
if (File.Exists(filePath))
{
// ReadAllLines method can read all the lines from the inventory.text file and then returns them in an array, in this case the InventoryItem
var fileContents = File.ReadAllLines(filePath);
foreach (var inventoryLine in fileContents)
{
// This makes sure our line has some content with a true or false boolean value, hence continue simply allows the code to continue past the if statment
if (string.IsNullOrWhiteSpace(inventoryLine)) continue;
//We can now Split a line of text in the inventory txt into segments with a comma thanks to the inventoryLine.Split
var inventoryLineSeg = inventoryLine.Split(',');
var inventoryItem = new InventoryItem();
// if the code was succesful in trying to parse the text file these will hold the value of cost and quantity
double cost;
double quantity;
// Assign each part of the line to a property of the InventoryItem
inventoryItem.CategoryName = inventoryLineSeg[0];
if (inventoryLineSeg.Length > 1)
{
inventoryItem.FoodName = inventoryLineSeg[1];
}
if (inventoryLineSeg.Length > 2 & double.TryParse(inventoryLineSeg[2], out cost))
{
inventoryItem.Cost = cost;
}
if (inventoryLineSeg.Length > 3 & double.TryParse(inventoryLineSeg[3], out quantity))
{
inventoryItem.Quantity = quantity;
}
//Now able to add all the InventoryItem to our ListBox
wnd.ListBox.Items.Add(inventoryItem);
}
wnd.ShowDialog();
}
}
private void foodMenuButton_Click(object sender, RoutedEventArgs e)
{
FoodMenuWindow wnd = new FoodMenuWindow();
wnd.ShowDialog();
}
private void newOrderButton_Click(object sender, RoutedEventArgs e)
{
OrderWindow wnd = new OrderWindow();
wnd.ShowDialog();
}
private void completedOrdersButton_Click(object sender, RoutedEventArgs e)
{
CompletedOrdersWindow wnd = new CompletedOrdersWindow();
wnd.ShowDialog();
}
private void quitButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
【问题讨论】:
-
快速搜索
string.Split()函数,它的重载简单修复 -
你最后的 foreach 有问题......你正在迭代
DLL中的项目(其中每个项目是x),但在循环中你不断添加相同的line。您应该添加x。