I'm creating a UWP app and trying to fill my DataGrid with a DataTable that contains data from my database, but with no success. I have already searched for solutions but just can't get rid of the error.
XAML code:
<StackPanel>
<Button Content="Fill DataGrid" Click="Button_Click"/>
<controls:DataGrid x:Name="dataGrid"
Margin="30"
AutoGenerateColumns="True">
</controls:DataGrid>
</StackPanel>
C# code:
private static DataTable GetDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("FirstName", typeof(string));
dt.Columns.Add("LastName", typeof(string));
dt.Columns.Add("Address", typeof(string));
dt.Columns.Add("City", typeof(string));
for (int i = 0; i < 10; i++)
dt.Rows.Add(i, "text", "text", "text", "text");
return dt;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DataTable dt = GetDataTable();
dataGrid.ItemsSource = dt.DefaultView;
}
and this error 20 times (the table has 10 entries)
Error: BindingExpression path error: 'Item' property not found on 'System.Data.DataRowView'. BindingExpression: Path='Item' DataItem='System.Data.DataRowView'; target element is 'Windows.UI.Xaml.Controls.TextBlock' (Name='null'); target property is 'Text' (type 'String')
When i swap ItemSource with DataContext:
dataGrid.DataContext = dt.DefaultView;
I don't get any error but I also don't change the dataGrid in any way.
I have tried to do the same in windows forms with DataGridView and I have succeeded:
private void button_Click(object sender, EventArgs e)
{
DataTable dt = GetDataTableFromDatabase();
dataGridView1.DataSource = dt;
}
I get this so its not a problem with the database or the DataTable.
I have managed to achieve a workaround by creating a List with the entities from the DataTable and adding them as the source to the dataGrid, but the problem is that I have a lot of different DataGrids and it would be a lot easier if i could somehow solve the problem in a way similar to the example in windows forms with the dataGridView.
Any help is appreciated.