Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

c# - CSV/Text in DataGrid Wpf

I cannot seem to figure out how to add my CSV File in a DataGrid. Can someone explain me what my approach should be?

Lets say i have a CSV file with the following content in my csv file:

ID;Name;Age;Gender
01;Jason;23;Male
02;Lela;29;Female

Really need some help here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Forget DataTable-based stuff. It's horrendous. It is not strongly typed and it forces you to all sorts of "magic-string" based hacks.

Instead, create a proper strongly-typed Data Model:

public class Person
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }

    public Gender Gender { get; set; }
}

public enum Gender
{
    Male,
    Female
}

Then create a Service that can load Data from the File:

public static class PersonService
{
    public static List<Person> ReadFile(string filepath)
    {
        var lines = File.ReadAllLines(filepath);

        var data = from l in lines.Skip(1)
                   let split = l.Split(';')
                   select new Person
                   {
                       Id = int.Parse(split[0]),
                       Name = split[1],
                       Age = int.Parse(split[2]),
                       Gender = (Gender)Enum.Parse(typeof(Gender), split[3])
                   };

        return data.ToList();
    }
}

And then use that to populate the UI:

public partial class Window2 : Window
{
    public Window2()
    {
        InitializeComponent();

        DataContext = PersonService.ReadFile(@"c:file.csv");
    }
}

XAML:

<Window x:Class="WpfApplication14.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window2" Height="300" Width="300">
    <DataGrid AutoGenerateColumns="True"
              ItemsSource="{Binding}"/>
</Window>

Result:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...