C# Load CSV into DataGrid

只谈情不闲聊 提交于 2019-12-07 19:10:33

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/5182656/c-sharp-load-csv-into-datagrid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!