Loading text file into listbox

 ̄綄美尐妖づ 提交于 2019-11-30 09:23:42

问题


What I am wanting to achieve is loading a text file into a listbox. It seems simple enough but I need to recognise in the text file when there is a new line, and each new line needs to be a new item in the listbox.

If this is possible, a reply would be much appreciated.


回答1:


This will work

List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(f))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
        lines.Add(line);
    }
}



回答2:


  OpenFileDialog f = new OpenFileDialog();
    if (f.ShowDialog() ==DialogResult.OK)
    {
        listBox1.Items.Clear();

        List<string> lines = new List<string>();
        using (StreamReader r = new StreamReader(f.OpenFile()))
        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                listBox1.Items.Add(line);

            }
        }
    }



回答3:


Try something like this:

listboxObject.DataSource = File.ReadAllLines("PathToYourFileHere");



回答4:


You can read all text (file.ReadAllText or Alllines), I don't have a compiler here.

Then add them to the list box, it is advised to trim the lines to get rid of whitespace at the beginning and end of each line.



来源:https://stackoverflow.com/questions/9531375/loading-text-file-into-listbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!