在DataGrid中的WPF CSV /文本 [英] CSV/Text in DataGrid Wpf

查看:143
本文介绍了在DataGrid中的WPF CSV /文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚如何添加我的CSV在DataGrid文件。 ?
谁能给我解释一下我的方法应该是什么

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

可以说我有一个CSV在我的CSV文件中的以下内容的文件:

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

推荐答案

忘记数据表为基础的东西。这是可怕的。它不是强类型,它迫使你对各种神奇字符串基于黑客

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



,然后用它来填充UI:

And then use that to populate the UI:

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

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



XAML:

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:

这篇关于在DataGrid中的WPF CSV /文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆