C#将CSV加载到DataGrid [英] C# Load CSV into DataGrid

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

问题描述

所以我有一个CSV文件:

  Header1,Header2,Header3,Header4 
Data11,Data12,Data13 ,Data14
Data21,Data22,Data23,Data24
Data31,Data32,Data33,Data34
Data41,Data42,Data43,Data44


DataGrid 。对于我的一生,我无法将其导入。我之前想做的是添加所有列( Header1 Header2 Header3 Header4 )然后添加行……但是似乎没有任何添加行的方法。所以我尝试使用 ItemSource ...但没有运气。



所以...我如何导入CSV文件放入系统 Windows 控件 DataGrid



更新



因此,我尝试了以下操作:

  DataTable表= CSVReader.ReadCSVFile(fileName,true); 
dataGrid.ItemsSource = table.DefaultView;

似乎可行...有点:$ b​​ $ b



更新2



因此,在打开 AutoGenerateColumns 之后,一切运行正常。

解决方案

看看此库
它使您可以将任何CSV转换为DataTable类型的对象,并将其绑定到DataGrid,如下所示:

  DataTable table = CSVReader.ReadCSVFile(fileName,true); 
myGridView.ItemSource = table.DefaultView;
myGridView.AutoGenerateColumns = true;

如果您已经将CSV解析为表,则只需绑定 ItemSource 到表的 DefaultView 属性,并将 AutoGenerateColums 设置为 true


So I have a CSV file:

    Header1,Header2,Header3,Header4
    Data11,Data12,Data13,Data14
    Data21,Data22,Data23,Data24
    Data31,Data32,Data33,Data34
    Data41,Data42,Data43,Data44

and a DataGrid in an WPF project. I cannot, for the life of me, get it to import. What I was trying to do before was add all the columns (Header1, Header2, Header3, Header4) then add the rows... but there didn't seem to be any way to add rows. So I tried using ItemSource... but no luck.

So... how do I import a CSV file into a System.Windows.Controls.DataGrid

UPDATE

So I tried this:

    DataTable table = CSVReader.ReadCSVFile(fileName, true);
    dataGrid.ItemsSource = table.DefaultView;

And it seems to work... somewhat:

UPDATE 2

So after turning on AutoGenerateColumns, everything worked perfectly.

解决方案

Take a look at this library. It lets you convert any CSV into an object of type DataTable and bind that to the DataGrid like this:

DataTable table = CSVReader.ReadCSVFile(fileName, true);
myGridView.ItemSource = table.DefaultView;
myGridView.AutoGenerateColumns = true;

If you already have parsed your CSV into a table, just bind the ItemSource to the table's DefaultView property and set AutoGenerateColums to true

这篇关于C#将CSV加载到DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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