简体   繁体   English

如何使用从文本文件中读取的项目填充列表框

[英]How do you populate a ListBox with items read from a text file

So I tried reading the file and I confirmed it worked and then tried adding the contents to a listbox and it did not work.所以我尝试读取该文件并确认它有效,然后尝试将内容添加到列表框但它不起作用。 The way I do it is first read the file, split the file line by line and put the contents into a string array, then use a for loop to add the contents to a listbox.我这样做的方法是首先读取文件,逐行拆分文件并将内容放入字符串数组,然后使用 for 循环将内容添加到列表框。 At first my problem was the listbox not having the contents added, then something changed and now it looks like the file isn't being read properly.起初我的问题是列表框没有添加内容,然后发生了一些变化,现在看起来文件没有被正确读取。 I don't know if it affects anything but I did edit the file in Visual Studio so I wouldn't think that affect anything, but I'm mentioning it just in case.我不知道它是否会影响任何东西,但我确实在 Visual Studio 中编辑了文件,所以我认为这不会影响任何东西,但我提到它以防万一。 I am also using holdLine more than once since I am reading more than one file.我也不止一次使用 holdLine,因为我正在阅读多个文件。

Here is where I am reading the file这是我正在阅读文件的地方


using (StreamReader inOFile = new StreamReader("..\\..\\options.txt"))
{               
    while (!inOFile.EndOfStream)
    {
        holdLine = inOFile.ReadLine();
        OptionsArr = holdLine.Split('\n');  
    }

The file in question has these lines有问题的文件有这些行

  • Employee ID员工ID
  • Name名称
  • Department部门
  • Employment Status就业状况
  • Salary薪水

The code where I try to add the contents of the string array to the listbox我尝试将字符串数组的内容添加到列表框的代码

OptionsListBox.Items.Clear();

OptionsListBox.BeginUpdate();
           
//one way I tried            
string listOptions = string.Join(" ", Program.OptionsArr);
OptionsListBox.Items.Add(listOptions.ToString());
              
//different way i tried
for (int i = 0; i < Program.OptionsArr.Length; i++)
{                 
    OptionsListBox.Items.Add(Program.OptionsArr[i]);
}
                  

//another failed attempt
OptionsListBox.Items.AddRange(Program.OptionsArr);

OptionsListBox.EndUpdate();

Here is some code that demonstrates the problem.这是一些演示问题的代码。 I added some Console.WriteLine() to print out what is in the variables during and after the loop.我添加了一些 Console.WriteLine() 来打印出循环期间和之后变量中的内容。 (here is a fiddle ) (这是一个小提琴

using System;
using System.IO;
                    
public class Program
{
    const string _textFile = "This is the first line in the file\n"
                           + "This is the second line in the file\n"
                           + "This is the third line in the file\n";
    public static void Main()
    {
        var utf8 = System.Text.Encoding.UTF8.GetBytes(_textFile);
        var memoryStream = new MemoryStream(utf8);
        memoryStream.Position = 0;
        
        string wholeLine;
        string[] optionsArray;

        using (var inOFile = new StreamReader(memoryStream))
        {           
            var count = 0;
            while (!inOFile.EndOfStream)
            {
                wholeLine = inOFile.ReadLine();
                optionsArray = wholeLine.Split('\n');
                
                Console.WriteLine("Reading Line {0}", ++count);
                Console.WriteLine("\tWhole: '{0}'", wholeLine);
                Console.WriteLine("\tSplit: '{0}'", string.Join("', '", optionsArray));
                Console.WriteLine()
            }
            Console.WriteLine("Final Options Array: {0}", string.Join(" | ", optionsArray));
        }
    }
}

The output of this program is:本程序的output为:

Reading Line 1
    Whole: 'This is the first line in the file'
    Split: 'This is the first line in the file'

Reading Line 2
    Whole: 'This is the second line in the file'
    Split: 'This is the second line in the file'

Reading Line 3
    Whole: 'This is the third line in the file'
    Split: 'This is the third line in the file'

Final Options Array: This is the third line in the file

Notice how optionsArray only contains one item in it?请注意 optionsArray 是如何只包含其中一项的? And it's exact copy of wholeLine?它是 wholeLine 的精确副本吗? That's because the ReadLine() function removes all the line breaks in the data.那是因为 ReadLine() function 删除了数据中的所有换行符。 .Split('\n') won't be able to split anything. .Split('\n') 将无法拆分任何内容。

If I change the split character to a space, then I get this:如果我将拆分字符更改为空格,则会得到:

Reading Line 1
    Whole: 'This is the first line in the file'
    Split: 'This', 'is', 'the', 'first', 'line', 'in', 'the', 'file'

Reading Line 2
    Whole: 'This is the second line in the file'
    Split: 'This', 'is', 'the', 'second', 'line', 'in', 'the', 'file'

Reading Line 3
    Whole: 'This is the third line in the file'
    Split: 'This', 'is', 'the', 'third', 'line', 'in', 'the', 'file'

Final Options Array: This | is | the | third | line | in | the | file

In this case, each line is split into separate words because they are separated by a space ' '.在这种情况下,每一行都被分成单独的单词,因为它们由空格“”分隔。 But even if I change the splitting, optionsArray only contains the last line in the file.但即使我更改拆分,optionsArray 也只包含文件中的最后一行。 Your while loop is written to read the entire file, but since you never do anything to collect the results of the split operating, the rest of your code won't do anything.您的 while 循环被编写为读取整个文件,但由于您从未执行任何操作来收集拆分操作的结果,因此代码的 rest 不会执行任何操作。

Try something like:尝试类似的东西:

// Employee is a class with employee fields (EmployeeID, name...)
IList<Employee> employees = readEmployeesFromFile();
OptionsListBox.DataSource = employees;
OptionsListBox.DisplayMember = "Name";
OptionsListBox.ValueMember = "EmployeeID";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM