简体   繁体   English

读取从文本文件到列表框C#的所有行

[英]Read all lines from text file to listbox C#

It says I need an String after ReadAllLines(...) Can someone help me setup that. 它说我在ReadAllLines(...)之后需要一个String ReadAllLines(...)有人可以帮助我进行设置。

I don't understand how I'm going to get the text file to ListBox . 我不明白如何将文本文件添加到ListBox

private void futureButton4_Click(object sender, EventArgs e)
{
    ofd.Filter = "TXT|* .txt";

    if (ofd.ShowDialog() == DialogResult.OK)
    {
        string[] lines = System.IO.File.ReadAllLines(DialogResult);
        listbox.Items.Add(lines);
    }
}

If you want to add a collection of strings in one pass, use AddRange() instead of Add() . 如果要一次性添加字符串集合,请使用AddRange()而不是Add() Also, you'll need to reference the FileName property to get the full path of the selected file. 另外,您将需要引用FileName属性以获取所选文件的完整路径。

string[] lines = System.IO.File.ReadAllLines(ofd.FileName);

listbox.Items.AddRange(lines);

The call to Add() just ends up calling ToString() on the collection, so all you'll see is the class type, in this case String[] Array . Add()的调用最终只是在集合上调用ToString() ,因此您所看到的只是类类型,在本例中为String[] Array

When you use AddRange() , it calls ToString() on each item in the collection. 当您使用AddRange() ,它将对集合中的每个项目调用ToString() In the case of a collection of strings, you just see each string. 如果是字符串集合,则只需查看每个字符串即可。 If you were using a custom class you created, you'd have to either override ToString() so something sensible were displayed, or you could use a bit of LINQ in the call to AddRange() , to select the property you wanted displayed. 如果使用的是创建的自定义类,则必须重写ToString()以便显示某些内容,或者可以在对AddRange()的调用中使用一些LINQ来选择要显示的属性。

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

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