I'm trying to read a csv into my data grid. All I need to do is get the csv and put it in a data grid. This is the C# that I have (found here):
public ICollection CreateDataSource()
{
string CSVDataBase = @"C:\Users\Laura\source\repos\Inveni\Inveni\inventory.csv";
//Create new DataTables and Rows
DataTable dt = new DataTable();
DataRow dr;
//Create Column Headers
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Type", typeof(string)));
dt.Columns.Add(new DataColumn("Brand", typeof(string)));
dt.Columns.Add(new DataColumn("Line", 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);
//Type =
dr[1] = Line.Split(',').ElementAt(1);
//Brand=
dr[2] = Line.Split(',').ElementAt(2);
//Line=
dr[3] = Line.Split(',').ElementAt(3);
//Add the row we created
dt.Rows.Add(dr);
}
//Return Dataview
DataView dv = new DataView(dt);
return dv;
}
And then:
dgvInventory.ItemsSource = CreateDataSource();
And in my XAML:
<DataGrid x:Name="dgvInventory" ItemsSource="{Binding}" Grid.Column="1" Margin="0" Grid.Row="1" BorderBrush="{x:Null}" Background="#FF0B123F" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding}" Header="ID"/>
<DataGridTextColumn Binding="{Binding}" Header="Type"/>
<DataGridTextColumn Binding="{Binding}" Header="Brand"/>
<DataGridTextColumn Binding="{Binding}" Header="Line"/>
</DataGrid.Columns>
</DataGrid>
The output from this is every single cell showing "System.Data.DataRowView" instead of actual data. System.Data.DataRowView Issue
How can I make my data grid show correct data?
The column bindings must use the respective property paths:
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}" Header="ID"/>
<DataGridTextColumn Binding="{Binding Type}" Header="Type"/>
<DataGridTextColumn Binding="{Binding Brand}" Header="Brand"/>
<DataGridTextColumn Binding="{Binding Line}" Header="Line"/>
</DataGrid.Columns>
or simpler, you don't explicitly declare the Columns at all and don't set AutoGenerateColumns="False"
.
Also note that ItemsSource="{Binding}"
is pointless when you assign the ItemsSource property in code behind.
And you don't need much more than the following to create the source collection:
private IEnumerable CreateDataSource()
{
var CSVDataBase = ...
return File.ReadLines(CSVDataBase).Select(
line =>
{
var items = line.Split(',');
return new
{
ID = int.Parse(items[0]),
Type = items[1],
Brand = items[2],
Line = items[3]
};
});
}