单击ComboBox以显示.txt文件中的特定行

时间:2013-11-30 05:29:05

标签: c# combobox text-files

我正在使用.txt文件创建购物车,但在开始计算之前,我需要在表单上显示信息。

我有2个单独的.txt文件。一个.txt文件具有您可以在程序中搜索的不同部分的类别(即服装,游戏,附件,杂项等)。我使用for循环将每个类别的名称循环到组合框中。另一个.txt文件包含产品的实际名称及其价格,描述和所属产品的类别。

我要做的是从组合框中选择特定类别,并在页面上显示该特定类别的产品。由于我正在显示多个项目,所以我必须使用数组,因此我首先要做的是声明新数组。

public partial class Form2 : Form
{
    //Name, description and price are the fields for the products
    //Category is the field for the combo box on the home page
    string[] name = new string[100];
    string[] description = new string[100];
    string[] price = new string[100];
    string[] category = new string[100];

下面的代码使用.txt文件中的信息填充ComboBox。

试             {                 StreamReader categories = new StreamReader(“categories.txt”);                 int index = 0;                 while(categories.Peek()!= -1)                 {                     category [index] = categories.ReadLine();                     索引++;                 }

            for (int i = 0; i < index - 1; i++)
            {
                cBSearch.Items.Add(category[i]);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

下面的这个实际上显示了来自另一个.txt文件的信息。但是,它不是根据类别显示信息,而是显示.txt文件中的所有信息。

try
        {
            StreamReader products = new StreamReader("products.txt");
            int index = 0;
            while (products.Peek() != -1)
            {
                name[index] = products.ReadLine();
                description[index] = products.ReadLine();
                price[index] = products.ReadLine();
                category[index] = products.ReadLine();
                index++;
            }
            //When you click the group for the combo box, the items from the group are not selected man! 
            //if (category[index] == cBSearch.SelectedIndex) 
            for (int i = 0; i < index; i++)
            {
                lblProductName.Text += name[i] + "  ";
                lblDescription.Text += description[i];
                lblPrice.Text += price[i];
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

我想我错过了一些东西。由于有两个单独的.txt文件,因此从一个.txt文件到另一个文件中选择信息变得更加困难。我需要添加什么才能显示特定类别的产品?

2 个答案:

答案 0 :(得分:2)

1。您没有将第二个文件的Category项与SelectedItem

中的ComboBox进行比较

试试这个:

        while (products.Peek() != -1)
        {
            category[index] = products.ReadLine();
            if(cBSearch.SelectedItem.ToString().Equals(category[index]))
            {
            name[index] = products.ReadLine();
            description[index] = products.ReadLine();
            price[index] = products.ReadLine();
            }
            index++;
        }

2。我强烈建议您在此处使用Database代替files,因为未来manage data {{1}}会很复杂使用文件。

答案 1 :(得分:0)

我尝试了你的方法,但表格中没有显示任何内容。我认为还有更多工作要做到这一点。

另外,我没有切换到数据库,因为它只会让我自己复杂化。我只知道C#的基础知识。