Reputation: 19
Say I have a txt
file with this content:
Tom, 11
Jason, 12
Gary, 13
Ted, 14
The WPF is just a list box.
What would I need to do for the list box, to show the names inside the txt
file when I start the program.
This is a very simple question, but I cant figure it out. I don't know where the txt file needs to be saved and I don't know how to call it in the ".cs"
Upvotes: 1
Views: 2093
Reputation: 453
Text file can be anywhere as you can specify path to it while opening. You can put it inside solution folder to make path shorter. Then in main method you write something like
var MyList = new List<string>();
using (var streamReader = File.OpenText(pathToYourTextFile))
{
var s = string.Empty;
while ((s = streamReader.ReadLine()) != null)
MyList.Add(s);
}
myListbox.ItemsSource = MyList;
Upvotes: 2
Reputation: 700
This is code which read next line to list,then read how to add this to listbox
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines.Add(line);
}
}
This is example how to binding list to listbox:
eventList.ItemsSource = lines;
Upvotes: 2