首页 > 解决方案 > 将文本文件加载到列表框中。代码行需要拆分

问题描述

我试图使用 openfiledialog 加载文本文件。string string bool 姓名,高中一年,失败?文本文件中的代码

Chris | Junior | False
Jake Peters | Freshman | True
Jasmine Baker | Senior | False

所以我使用一个数组来获取代码。然后创建一个 foreach 循环以添加到字符串列表

然后使用 for 循环将行拆分为“|”

然后创建一个新对象并使用对象的变量保存数据。

最后添加到列表框

不需要转换。你可以忽略布尔值。我想更了解这个概念

我的意思是我尝试过的方法。根本没有加载。

string[] b = File.ReadAllLines(filePath);

List<string> ...
foreach(var a in b)
{
   list.Add(a);
}

for (int i =0; i<students.Count; i++)
{
list[i].Split('|');

//Human object...

Human x = new Human();

x.name =
listbox.add(x);
failinglistbox.Items.Add(x);

标签: c#

解决方案


我想这就是你想要的。

string[] students = File.ReadAllLines(filePath);

for (int i = 0; i < students.Length; i++)
{
    string[] cells = students[i].Split('|');

    //Human object...

    Human x = new Human();

    x.name =cells[0].Trim();

////////edited////////////
        x.year =cells[1].Trim();
        x.failing =cells[2].Trim();

    listbox.add(x);
    failinglistbox.Items.Add(x);
}

推荐阅读