C# 单击组合框以显示.txt文件中的特定行
我正在使用.txt文件创建购物车,但在开始计算之前,我需要在表单上显示信息 我有两个单独的.txt文件。txt文件包含可在程序中搜索的不同部分的类别(即服装、游戏、配件、杂项等)。我使用for循环将每个类别的名称循环到组合框中。另一个.txt文件包含产品的实际名称、价格、说明以及产品所属的类别 我试图做的是从组合框中选择特定类别,并在页面上显示该特定类别的产品。因为我要显示多个项目,所以我必须使用一个数组,所以我首先要做的是声明新的数组C# 单击组合框以显示.txt文件中的特定行,c#,combobox,text-files,C#,Combobox,Text Files,我正在使用.txt文件创建购物车,但在开始计算之前,我需要在表单上显示信息 我有两个单独的.txt文件。txt文件包含可在程序中搜索的不同部分的类别(即服装、游戏、配件、杂项等)。我使用for循环将每个类别的名称循环到组合框中。另一个.txt文件包含产品的实际名称、价格、说明以及产品所属的类别 我试图做的是从组合框中选择特定类别,并在页面上显示该特定类别的产品。因为我要显示多个项目,所以我必须使用一个数组,所以我首先要做的是声明新的数组 public partial class Form2 :
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文件中的信息填充组合框
试一试
{
StreamReader categories=新的StreamReader(“categories.txt”);
int指数=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);
}
for(int i=0;i
下面这个文件实际上显示了另一个.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);
}
试试看
{
StreamReader产品=新的StreamReader(“products.txt”);
int指数=0;
while(products.Peek()!=-1)
{
名称[索引]=products.ReadLine();
description[index]=products.ReadLine();
价格[指数]=products.ReadLine();
类别[索引]=products.ReadLine();
索引++;
}
//当您单击组合框的组时,组中的项目不会被选中!
//if(类别[索引]==cBSearch.SelectedIndex)
对于(int i=0;i
我想我错过了什么。由于有两个独立的.txt文件,因此从一个.txt文件到另一个.txt文件选择信息变得更加困难。我需要添加什么,以便只显示特定类别的产品 1.您没有将第二个文件的
类别
项与从组合框中选择的项进行比较
试试这个:
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.我强烈建议您在这里使用数据库
而不是文件
,因为今后使用文件管理您的数据
会很复杂。我尝试了您的方法,但表单中没有显示任何内容。我认为还需要做更多的工作才能让它发挥作用
此外,我不会切换到数据库,因为它只会使我自己的事情复杂化。我只知道C#的基本原理 我强烈建议你在这里使用数据库而不是文件。我同意Sudhakar的观点。从数据库或XML中研究如何实现这一点。