CSV / DataGrid中的文本Wpf [英] CSV/Text in DataGrid Wpf
本文介绍了CSV / DataGrid中的文本Wpf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎无法弄清楚如何在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: p>
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>
结果:
这篇关于CSV / DataGrid中的文本Wpf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文