Reading a CSV file in a WPF application (C #)

I recently made a console application in C # that could read a .csv file and write it to the console neatly, however now I want to do this in WPF to make it even more neat.

The previous console application is as follows:

class Program
{
    static void Main(string[] args)
    {
        string[] tokens;
        char[] separators = { ';' };
        string str = "";

        FileStream fs = new FileStream(@"D:\Dokumenter\Skole\6. semester\GUI\Exercises\Exercise2\02 deltagerliste.csv", 
                                       FileMode.Open);
        StreamReader sr = new StreamReader(fs, Encoding.Default);

        while ((str = sr.ReadLine()) != null)
        {
            tokens = str.Split(separators, StringSplitOptions.RemoveEmptyEntries);

            Console.WriteLine(String.Format("{0,-20}", tokens[0]) +
                              String.Format("{0,-15}", tokens[1]) +
                              String.Format("{0,-15}", tokens[2]) +
                              String.Format("{0,-15}", tokens[3]));
        }

        Console.ReadLine();            
    }
}

It works great, but I have to admit that it's hard for me to figure out where to start with a WPF application.

So far, I have created the following XAML code with four headers for the .csv file (since it has four columns), and I guess I need to find a way to put the corresponding rows in the corresponding columns.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Deltagerliste" Height="350" Width="525" WindowStartupLocation="CenterScreen" WindowState="Maximized"
    Background="DeepPink"
    >
<ListView HorizontalAlignment="Left" Height="320" VerticalAlignment="Top" Width="517">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="First name"/>
            <GridViewColumn Header="Last name"/>
            <GridViewColumn Header="ID"/>
            <GridViewColumn Header="Email"/>
        </GridView>
    </ListView.View>
</ListView>

My main and initial problem is how I read in a ListView file. I'm new to C # and XAML, and although I know well how to open and read a file in C #, the syntax in XAML is a bit confusing to me.

+4
1

: , .

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

, CSV:

public IEnumerable<Person> ReadCSV(string fileName)
{
    // We change file extension here to make sure it 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]);
    });
}

. , x: Name - , .cs :

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

, ItemSource , Person:

public MainWindow()
{
    InitializeComponent();

    // We can access ListViewPeople here because that the Name of our list
    // using the x:Name property in the designer.
    ListViewPeople.ItemsSource = ReadCSV("example");
}

CSV

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

Program result

+13

Source: https://habr.com/ru/post/1527202/


All Articles