【问题标题】:How can I filter my listbox items with a combobox?如何使用组合框过滤我的列表框项目?
【发布时间】: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

标签: c# combobox listbox


【解决方案1】:

您需要在分隔符, 上拆分正在读取的line

var array = line.Split(',');

然后您可以访问索引array[2]array[3] 处的数字。

double firstNumber = double.Parse(array[2]);
double secondNumber = double.Parse(array[3]);

【讨论】:

    【解决方案2】:

    您可以通过使用File 类的静态ReadAllLines 方法在不显式使用StreamReader 的情况下执行此操作,该方法从文本文件中读取所有行并将它们返回到数组中。

    然后,对于每一行,您可以使用 string 类的静态 Split 方法,该方法会将行拆分为一个或多个字符(在您的情况下我们将使用逗号)并返回一个数组。

    接下来,我们可以根据分割线的内容生成一个新的InventoryItem。我喜欢每次都测试数组的长度,这样如果有一行缺少逗号,我们就不会遇到异常(换句话说,除非你知道,否则不要尝试访问数组中的索引存在)。

    最后,我们可以将新的InventoryItem 添加到我们的ListBox

    注意:这假设您有一个 InventoryItem 类,例如:

    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}) - Price: ${Cost:0.00}, Qty: {Quantity}";
        }
    }
    

    然后我们可以像这样解析文件并更新我们的ListBox

    // Path to our inventory file
    var filePath = @"f:\public\temp\inventory.txt";
    
    if (File.Exists(filePath))
    {
        var fileContents = File.ReadAllLines(filePath);
    
        foreach (var inventoryLine in fileContents)
        {
            // Ensure our line has some content
            if (string.IsNullOrWhiteSpace(inventoryLine)) continue;
    
            // Split the line on the comma character
            var inventoryLineParts = inventoryLine.Split(',');
            var inventoryItem = new InventoryItem();
    
            // These will hold the values of Cost and Quantity if `double.TryParse` succeeds
            double cost;
            double qty;
    
            // Assign each part of the line to a property of the InventoryItem
            inventoryItem.CategoryName = inventoryLineParts[0].Trim();
            if (inventoryLineParts.Length > 1)
            {
                inventoryItem.FoodName = inventoryLineParts[1].Trim();
            }
            if (inventoryLineParts.Length > 2 && 
                double.TryParse(inventoryLineParts[2], out cost))
            {
                inventoryItem.Cost = cost;
            }
            if (inventoryLineParts.Length > 3 && 
                double.TryParse(inventoryLineParts[3], out qty))
            {
                inventoryItem.Quantity = qty;
            }
    
            // Add this InventoryItem to our ListBox
            wnd.ListBox.Items.Add(inventoryItem);
        }
    }
    

    【讨论】:

    • 谢谢你的代码是我能够阅读和理解的唯一代码,但是仍然存在问题,你的看起来应该可以工作,但不是在列表框中显示每一行文本出于某种原因写 ACW2.MainWindow+InventoryItem ,你知道这是为什么吗?
    • 哦,是的,我想这是因为我们没有任何默认方式来显示InventoryItem 的字符串值。我更新了上面的代码示例以添加对 ToString 方法的覆盖。您可以调整它以显示您想要的方式。
    • 非常感谢!
    • 我还在前两个属性分配中添加了一些Trim() 方法,因为食物名称前面有多余的空格
    • 我想你可能不知道如何解决这个问题,现在我们已经将文本文件中的文本排序到数据结构中,我如何使用组合框将列表框过滤到行从特定的类别名称开始(只有 4 个类别名称,All、Pizza、Burger、Sundry)。您是唯一一个完全解释如何解决这些问题的人,如果您能提供帮助,我们将不胜感激。
    猜你喜欢
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多