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.
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);
}
}
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);
}
}
}
Try something like this:
listboxObject.DataSource = File.ReadAllLines("PathToYourFileHere");
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.