Reading a .csv file into WPF application (C#)

后端 未结 1 1706
孤街浪徒
孤街浪徒 2021-01-05 20:03

I\'ve just recently made a C# console application that could read a .csv file and write it to the console in a neat manner, however now I want to make it in WPF to make it e

相关标签:
1条回答
  • 2021-01-05 20:30

    First: Create a class that will hold the data per row.

    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;
        }
    }
    

    Then create a function that will return a list of Persons from the CSV file:

    public IEnumerable<Person> 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<Person> 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]);
        });
    }
    

    Then configure your listview columns with the appropriate binding. Note that the x:Name property is the name you will use to access this listview in the .cs file of the form:

    <ListView x:Name="ListViewPeople">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="First name" Width="100" DisplayMemberBinding="{Binding Path=FirstName}"/>
                <GridViewColumn Header="Last name" Width="150" DisplayMemberBinding="{Binding Path=LastName}"/>
                <GridViewColumn Header="ID" Width="40" DisplayMemberBinding="{Binding Path=ID}"/>
                <GridViewColumn Header="Email" Width="200" DisplayMemberBinding="{Binding Path=Email}"/>
            </GridView>
        </ListView.View>
    </ListView>
    

    Lastly you bind the ItemsSource of the listview to the method returning the Person list:

    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");
    }
    

    CSV File

    Henk;van Dam;1;henk.van.dam@gmail.com
    Alex;the Great;2;alex.the_great@live.nl
    

    End result

    Program result

    0 讨论(0)
提交回复
热议问题