reveN
reveN

Reputation: 642

Display a List of DataRows in DataGrid

I am trying to display a List of DataRows in a DataGrid like this:

List<DataRow> grid = new List<DataRow>();

for (int i = 0; i <= dt.Rows.Count; i++)
{
    grid.Add(dt.Rows[i]);
}
dataGrid1.ItemsSource = grid;

dt is a DataTable from where I get my data. The problem is, when I run the code the datagrid is empty.

This didn't work, too:

datagrid1.DataContext = grid;

Edit: (xaml)

<DataGrid Name="dataGrid1" />

Upvotes: 2

Views: 2059

Answers (2)

atomkiwi
atomkiwi

Reputation: 1

Please use a foreach loop it is much more easier and you cant do mistakes.

foreach (var row in dt.Rows)
{
    grid.Add(row);
}

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39956

You don't need a List of DataRows. You could simply:

dataGrid1.ItemsSource = dt.DefaultView;

Or:

dataGrid1.DataContext = dt.DefaultView;

And:

<DataGrid Name="dataGrid1" ItemsSource="{Binding}">

Update: If you still want a List of DataRows:

dataGrid1.ItemsSource = dt.AsEnumerable()
                          .Where(grid.Contains)
                          .AsDataView();

Also you should change this:

for (int i = 0; i <= dt.Rows.Count; i++)

To this:

for (int i = 0; i < dt.Rows.Count; i++)

Upvotes: 4

Related Questions