Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the DataSource of a DataGrid in WPF?

I need to set a table from a database to be the DataSource of a GridGrid in WPF. In Windows Forms the property is called DataSource but in WPF no such property exists, so how can i do it?

like image 437
Miguel Avatar asked Mar 22 '11 22:03

Miguel


2 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-behind rather than a binding, just give a name to the ListView and set the ItemsSource property in code:

listView1.ItemsSource = YourData;

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


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

listView1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = YourData });
like image 110
Thomas Levesque Avatar answered Sep 22 '22 22:09

Thomas Levesque


This is simple an example:

XAML part :

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

C# part :

... [code to read and fill your table ] ...

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

And now your DataGrid will be filled with your DataTable

like image 30
Menard Laval Avatar answered Sep 25 '22 22:09

Menard Laval