How to install DataSource DataGrid in WPF?

I need to set a table from a database as a GridGrid data source in WPF. In Windows Forms, the property is called a DataSource , but in WPF there is no such property, so how can I do this?

+6
wpf binding wpf-controls wpfdatagrid
source share
4 answers

You can use the ItemsSource property:

 <ListView ItemsSource="{Binding YourData}"> <ListView.View> <GridView> <!-- The columns here --> </GridView> </ListView.View> </ListView> 

If you prefer to use code binding instead of binding, just provide the ListView name and set the ItemsSource property in the code:

 listView1.ItemsSource = YourData; 

You can also use the ItemsSource property with other list controls ( DataGrid , ListBox , ComboBox , etc.), as it is defined in the base class ItemsControl .


EDIT: if the data source is a DataTable , you cannot assign it directly to the ItemsSource , because it does not implement IEnumerable , but you can do it through a binding:

 listView1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = YourData }); 
+11
source share

This is a simple example:

XAML part :

 <DataGrid Name="dataGrid1" Width="866" Height="auto" HorizontalAlignment="Left" VerticalAlignment="Top" /> 

Part C # :

... [code to read and populate the table] ...

 da.Fill(myDataTable); dataGrid1.ItemsSource = myDataTable.DefaultView; 

Now your DataGrid will be populated with your DataTable

+7
source share

GridView is a view, not a standalone control, as far as I know, you would normally use it as a ListView . In WPF, a property for a data set is called ItemsSource , you probably want to either use a ListView or a DataGrid to display your data this way.

+1
source share

You can use below both methods of binding datatable to datagrid in WPF.

  datagrid.ItemSource = mydt.DefaultView(); datagrid.DataContext = mydt.DefaultView(); 
0
source share

All Articles