Read csv file into wpf C# code example
Example 1: Read csv file into wpf C#
public MainWindow()
{
InitializeComponent();
// We can access ListViewPeople here because that's the Name of our list
// using the x:Name property in the designer.
ListViewPeople.ItemsSource = ReadCSV("example");
}
Example 2: Read csv file into wpf C#
public IEnumerable ReadCSV(string fileName)
{
// We change file extension here to make sure it's a .csv file.
// TODO: Error checking.
string[] lines = File.ReadAllLines(System.IO.Path.ChangeExtension(fileName, ".csv"));
// lines.Select allows me to project each line as a Person.
// This will give me an IEnumerable back.
return lines.Select(line =>
{
string[] data = line.Split(';');
// We return a person with the data in order.
return new Person(data[0], data[1], Convert.ToInt32(data[2]), data[3]);
});
}
Example 3: Read csv file into wpf C#
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
public string Email { get; set; }
public Person(string firstName, string lastName, int id, string email)
{
FirstName = firstName;
LastName = lastName;
ID = id;
Email = email;
}
}