Shantanu Gupta
Shantanu Gupta

Reputation: 21198

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?

Upvotes: 8

Views: 12278

Answers (1)

JohnB
JohnB

Reputation: 18982

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:

How to bind DataGrid to generic list in WPF:

Especially (a great feature in WPF):

Upvotes: 7

Related Questions