How to load Datatable on a Datagrid?

Asked

Viewed 1,363 times

3

I have a DataTable loaded with information in a WPF application.

I’d like to take that DataTable and carry it on a DataGrid.
How can I do this the easy way ?

DataGrid in the XAML:

<Grid>
    <Button Content="Pedidos&#xD;&#xA;" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="91" Click="Button_Click" Height="27"/>
    <DataGrid Name="dataGrid" HorizontalAlignment="Left" Margin="10,42,0,0" VerticalAlignment="Top" Height="268" Width="558"/>
</Grid>
  • I believe that when you assign Datagrid, your datatable as Datasource and then a Bind() on it. This causes your Datatable to be transferred to your Datagrid.

  • Can you send me an example code ?

1 answer

2

There are several ways to "popular" a DataGridView with a DataTable.

Here are two simple ways to do it.

Using a BindingSource:

BindingSource bs = new BindingSource();
bs.DataSource = seuDataTablePopulado;
datagrid.DataSource = bs;

"Playing" the DataTable straight on the grid:

datagrid.DataSource = seuDataTable;

Between these two ways I prefer to use the BindingSource by the options of filters I have later.

  • I decided otherwise: this.meuDataGrid.ItemsSource = this.meuDataTable.DefaultView;. It worked the way I wanted it to. Still, thanks for the help !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.