Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to bind DataGrid to generic list in WPF

I am trying to bind a DataGrid to a generic list in WPF.

The following code results in blank rows for each row of data in my list (i.e. if i have 5 rows, it shows 5 rows, but doesn't shows any data in the cells):

List<DataRow>  DataBindingSource = GuestList.Where(row =>
  (row.Field<long>("FK_GROUP_ID") == Int64.Parse(cmbGroup.SelectedValue.ToString())) &&
  (row.Field<long>("FK_AGE_GROUP_ID") != (int)L_Age_Group.Child))
  .ToList();

gvwAddultDetails.ItemsSource = DataBindingSource;

If I convert my list of objects to a DataTable, it works (shows data). For example:

List<DataRow> DataBindingSource = GuestList.Where(row =>
  (row.Field<long>("FK_GROUP_ID") == Int64.Parse(cmbGroup.SelectedValue.ToString())) &&
  (row.Field<long>("FK_AGE_GROUP_ID") != (int)L_Age_Group.Child))
  .ToList();

gvwAdultDetails.ItemsSource = DataBindingSource.CopyToDataTable().DefaultView;

But if I had a List<DataRow>, how would I convert it to DataTable?

What is the best practice for binding a DataGrid to a `List' in WPF?

like image 802
Shantanu Gupta Avatar asked Dec 03 '10 10:12

Shantanu Gupta


1 Answers

One way to bind DataGrid to generic list in WPF:

MainWindow.xaml.cs

Grid.DataContext = DataBindingSource;

MainWindow.xaml

<DataGrid
  AutoGenerateColumns="True"
  ItemsSource="{Binding}"
  Name="Grid" />

But it probably won't work with DataRow, because in WPF, if you want to bind to something, it needs to be a property.

- OTHER THOUGHTS -

Here's how you can convert a generic list to a DataTable:

  • Generic List to DataTable

How to bind DataGrid to generic list in WPF:

  • Why isn't my WPF Datagrid showing data?

Especially (a great feature in WPF):

  • ObservableCollection<> WPF Example
like image 64
JohnB Avatar answered Sep 28 '22 02:09

JohnB