从多个文本文件中读取,数组显示在列表框和标签上



嗨,我有一个程序:

1-用户应首先从ComboBox中选择一个项目。

选择后,将在后台打开一个文本文件,并将其内容添加到ListBox中。

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    switch (comboBox2.SelectedIndex)
    {
        case 0:
            listBox3.Items.Clear();
            FileInfo file0 = new FileInfo("C:\hardwaremaintenance.txt");
            StreamReader stRead0 =file0.OpenText();
            while (!stRead0.EndOfStream)
            {                
                listBox3.Items.Add(stRead0.ReadLine());
            }
            break;
        case 1:
            listBox3.Items.Clear();
            FileInfo file1 = new FileInfo("C:\NetworkManagement.txt");
            StreamReader stRead1 =file1.OpenText();
            while (!stRead1.EndOfStream)
            {                
                listBox3.Items.Add(stRead1.ReadLine());
            }
            break;
        case 2:
            listBox3.Items.Clear();
            FileInfo file2 = new FileInfo("C:\Software.txt");
            StreamReader stRead2 =file2.OpenText();
            while (!stRead2.EndOfStream)
            {                
                listBox3.Items.Add(stRead2.ReadLine());
            }
            break;
        case 3:
            listBox3.Items.Clear();
            FileInfo file3 = new FileInfo("C:\SyriatelApplications.txt");
            StreamReader stRead3 =file3.OpenText();
            while (!stRead3.EndOfStream)
            {                
                listBox3.Items.Add(stRead3.ReadLine());
            }
            break;
        case 4:
            listBox3.Items.Clear();
            FileInfo file4 = new FileInfo("C:\NewHardwareRequest.txt");
            StreamReader stRead4 =file4.OpenText();
            while (!stRead4.EndOfStream)
            {                
                listBox3.Items.Add(stRead4.ReadLine());
            }
            break;
    }
}

2-用户从列表框中(最近)添加的项目中选择一个项目(来自步骤1),执行此操作后,它再次打开一个新的文本文件,其中填充了这种格式的文本,其中"|"是分隔符号

private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
    int itemsCount = listBox3.Items.Count;
    string[] items = new string[itemsCount];
    for (int i = 0; i < itemsCount; i++)
        items[i] = listBox3.Items[i].ToString();

我的大脑突然卡在了这里。

下一步应该取ListBox中的每个项,并将其与最后打开的文件中的行连接,其中所选项==任何行中的第一个单词。

我不知道怎么做的是:

  1. 何时以及如何打开新文件,读取每一行并将每一项放置在数组中(将行彼此分隔)
  2. 如何将ListBox中的选定元素与第二个文件中任意行中的第一个单词进行比较

如果它们匹配,我想使用行中的剩余信息来填充标签和文本框。

程序的接口如下

如果我把你弄糊涂了,我真的很抱歉,但我在编程方面没有那么丰富的经验

一些入门技巧:

  • 不要将控件(listBox3)用作数据存储。相反,在类中添加一个string[] items
  • 当您有像switch()中那样的重新安排代码时,请使用Refactor|Extract方法
  • 使用System.IO.File.ReadAllLines(fileName)可以更好、更容易地读取文本文件
  • 如果要在另一个文件中查找单词(str=listbox3.SelectedItem),请使用lines[i].Contains(str)

最新更新