Loading text file into listbox

c# file text listbox

29299 просмотра

4 ответа

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.

Автор: Shannon Rothe Источник Размещён: 12.11.2019 09:26

Ответы (4)


4 плюса

Решение

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);
    }
}
Автор: gaurawerma Размещён: 02.03.2012 10:12

4 плюса

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

            }
        }
    }
Автор: Adumuah Dowuona Размещён: 17.10.2014 07:47

3 плюса

Try something like this:

listboxObject.DataSource = File.ReadAllLines("PathToYourFileHere");
Автор: Mithrandir Размещён: 02.03.2012 10:07

1 плюс

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.

Автор: Michel Keijzers Размещён: 02.03.2012 10:08
Вопросы из категории :
32x32