【问题标题】:Loading text file into listbox. lines of code need to be Split将文本文件加载到列表框中。代码行需要拆分
【发布时间】:2019-05-13 04:49:05
【问题描述】:

我正在尝试使用 openfiledialog 加载文本文件。 字符串字符串布尔 姓名,高中一年,不及格? 文本文件中的代码

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);

【问题讨论】:

  • 好吧,您并没有显示所有代码,例如students 没有显示,只是使用。无论如何,请使用var parts = list[i].Split('|'); x.name = parts[0]; // and so on,因为 split 给出了一个数组。
  • 另外,我建议你使用foreach(var line in File.ReadLines(file path)) 更好,因为它会按需读取一行。
  • 学生名单

标签: c#


【解决方案1】:

我想这就是你想要的。

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);
}

【讨论】:

  • 这让一切都成为了名字。我需要一些可以拆分的东西,列表框将在哪里获取一个带有名称、年份和失败的对象?
猜你喜欢
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2021-05-09
  • 1970-01-01
相关资源
最近更新 更多