简体   繁体   中英

C# WPF How do I display the contents of a .txt file into a list box?

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"

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM