我似乎无法弄清如何将我的CSV文件添加到DataGrid中。有人能告诉我应该采取什么方法吗?
假设我有一个CSV文件,其中包含以下内容:
ID;Name;Age;Gender
01;Jason;23;Male
02;Lela;29;Female
我这里确实需要一些帮助
不要使用基于 DataTable
的东西,它很糟糕。它不是强类型的,而且它会迫使你采用各种“魔术字符串”式的黑科技。
相反地,创建一个正确的、强类型的数据模型:
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
}
接下来创建一个服务,可以从文件中加载数据:
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();
}
}
然后使用它来填充用户界面:
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>
结果:
//Location of CSV File
string CSVDataBase = @"C:\CSVDatabase.csv";
//Create Collection for DataGrid Source
ICollection CreateDataSource()
{
//Create new DataTables and Rows
DataTable dt = new DataTable();
DataRow dr;
//Create Column Headers
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Age", typeof(string)));
dt.Columns.Add(new DataColumn("Gender", typeof(string)));
//For each line in the File
foreach (string Line in File.ReadLines(CSVDataBase))
{
//Split lines at delimiter ';''
//Create new Row
dr = dt.NewRow();
//ID=
dr[0] = Line.Split(';').ElementAt(0);
//Name =
dr[1] = Line.Split(';').ElementAt(1);
//Age=
dr[2] = Line.Split(';').ElementAt(2);
//Gender=
dr[3] = Line.Split(';').ElementAt(3);
//Add the row we created
dt.Rows.Add(dr);
}
//Return Dataview
DataView dv = new DataView(dt);
return dv;
}
public void loadDataGridView()
{
//Load everything in datagrid
myDataGrid.ItemsSource = CreateDataSource();
}