Damian
Damian

Reputation: 39

How add specified items to listbox from file?

Let's say I have some text file and I want to load lines from line to line in the listbox, omitting the first and last line in this file. Can it be done ??

enter image description here

private void metroButton18_Click(object sender, EventArgs e)
    {
        OpenFileDialog f = new OpenFileDialog();
        if (f.ShowDialog() == DialogResult.OK)
        {
            listBox3.Items.Clear();

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

Thank You for Your help.

Upvotes: 0

Views: 211

Answers (3)

Berkay Yaylacı
Berkay Yaylacı

Reputation: 4513

What about this ?

OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog() == DialogResult.OK) {
    listBox1.Items.Clear();
    List<string> lines = new List<string>();
    using (StreamReader sr = new StreamReader(f.OpenFile())) {
          string line;
          while ((line = sr.ReadLine()) != null) {
                lines.Add(line); // add lines to list first
          }
    }
    string[] resultArray = lines.Skip(1).Reverse().Skip(1).Reverse().ToArray();
//skip first one , reverse so last one is the first now, skip again and reverse again to get actual list
    listBox1.Items.AddRange(resultArray);
}

Hope helps,

Upvotes: 1

Abbas
Abbas

Reputation: 14432

Use the File.ReadAllLines Method and skip the first and last index in the loop:

var path = @"C:\temp\MyTest.txt";
var allLines = File.ReadAllLines(path);

for(var i = 1; i < allLines.Length - 1; i++)
{
    listBox3.Items.Add(allLines[i]);
}

Using the OpenFileDialog to open the file:

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

    var allLines = File.ReadAllLines(f.FileName);
    for(var i = 1; i < allLines.Length - 1; i++)
    {
        listBox3.Items.Add(allLines[i]);
    }
}

Upvotes: 3

Michał Turczyn
Michał Turczyn

Reputation: 37500

Read first line outside the loop:

line = sr.ReadLine();
while ((line = sr.ReadLine()) != null)
{
    listBox3.Items.Add(line);
}

After finishing reading from file, just remove last item:

listBox3.Items.RemoveAt(listBox3.Items.Count);

Upvotes: 1

Related Questions