Bujolg
Bujolg

Reputation: 33

How do I add all items from txt to a listbox?

So basically I need a button that will add all text from txt file, that already exists in the folder of bin/debug. I was trying to come up with something but it didn't go that well

const string sPath = "save.txt";

        System.IO.StreamReader ReadFile = new System.IO.StreamReader(sPath);
        if (File.Exists(sPath))
        {
            string str = File.ReadAllText(sPath);
            foreach (char item in sPath)             
            { 
                ListBoxOutput.Items.Add(str);

            }             
        }

        ReadFile.Close();

        MessageBox.Show("Information loaded");

Upd: Thanks for the help, I ended up with this:

 const string sPath = "save.txt";

        System.IO.StreamReader ReadFile = new System.IO.StreamReader(sPath);
        if (File.Exists(sPath))
        {
            string[] lines = File.ReadAllLines(sPath);

            foreach (string item in lines)
            {
                ListBoxOutput.Items.Add(item);

            }
        }

        ReadFile.Close();

        MessageBox.Show("Information loaded!");

Upvotes: 1

Views: 81

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

Instead of adding items one by one to the ListBox, just assign the string array returned by File.ReadAllLines to the ListBox' DataSource property.

ListBoxOutput.DataSource = File.ReadAllLines(sPath);

Note: There is no point in opening the StreamReader, since you are not using it. The entire code:

const string sPath = "save.txt";

if (File.Exists(sPath)) {
    ListBoxOutput.DataSource = File.ReadAllLines(sPath);
    MessageBox.Show("Information loaded");
}  else {
    MessageBox.Show("File doesn't exist.");
}

See also: File.ReadAllLines Method

Upvotes: 0

HiiiiD
HiiiiD

Reputation: 46

Try changing

string str = File.ReadAllText(sPath);
    foreach (char item in sPath)             
    { 
        ListBoxOutput.Items.Add(str);
    }  

To this

IEnumerable<string> str = File.ReadLines(sPath);
foreach (string item in str)             
{ 
    ListBoxOutput.Items.Add(item);
}  

I think that's what you need. By the way if you have a small file you can use

File.ReadAllLines(sPath)

Hope this helps.

Upvotes: 2

Roman Kalinchuk
Roman Kalinchuk

Reputation: 728

change

string str = File.ReadAllText(sPath);
foreach (char item in sPath)             
{ 
    ListBoxOutput.Items.Add(str);// there you add all your file content N times where N - count of characters in save file path
}  

to

string[] str = File.ReadAllLines(sPath);
foreach (string item in str)             
{ 
    ListBoxOutput.Items.Add(item);
}  

it is not to clear what you are trying to achieve, but hope this helps

Upvotes: 2

Related Questions