C#将CSV加载到DataGrid [英] C# Load CSV into DataGrid
问题描述
所以我有一个CSV文件:
Header1,Header2,Header3,Header4
$ p WPF项目中的$ p>
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 usingItemSource
... 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'sDefaultView
property and setAutoGenerateColums
totrue
这篇关于C#将CSV加载到DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!