DataGrid Wpf 中的 CSV/文本 [英] CSV/Text in DataGrid Wpf
本文介绍了DataGrid Wpf 中的 CSV/文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎不知道如何在 DataGrid 中添加我的 CSV 文件.有人可以解释一下我的方法应该是什么吗?
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
这里真的需要一些帮助
推荐答案
忘记基于 DataTable
的东西.太可怕了.它不是强类型的,它迫使你使用各种基于魔法字符串"的技巧.
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:
<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>
结果:
这篇关于DataGrid Wpf 中的 CSV/文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文