Paulo Praca
Paulo Praca

Reputation: 39

Fill a DataGrid with LINQ expression

I can't fill a datagrid with this code:

var y = valores.Where(c => c % 2 == 0);                 
dataGridView1.DataSource = y.ToList();

But this works:

var x = from valor in valores
        where (valor % 2 == 0)
        select new
        {
            valor
        };

dataGridView1.DataSource = x.ToList();

Upvotes: 2

Views: 370

Answers (2)

Miodrag
Miodrag

Reputation: 76

As you may see from the result of your queries:

enter image description here

you are getting two different lists. The first one returns the integers value type, the second one is returning valor which is anonymous type list.

enter image description here

In order to fix the first query you should edit your code from:

var y = valores.Where(c => c % 2 == 0);

to

var y = valores.Where(c => c % 2 == 0).Select(c => new { valor = c });

Upvotes: 1

DotNet Developer
DotNet Developer

Reputation: 3018

I can't fill a datagrid

Apparently you mean that your dataGridView1 is not displaying the list.

I reproduced your problem and did an experiment with some types. Looks like the reason is when the list contains objects which has no properties then DataGridView does not get bound to the list. In your first snippet, for example, the Linq expression is returning a list of integers, which is System.Int32. And if you take a look at the definition of this value type with object browser then you can see that it does not declare any public property.

For example following code "does not work" either

var x = from valor in valores
where (valor % 2 == 0)
select new
{    
};
dataGridView1.DataSource = x.ToList();

That is, I am creating object of anonymous type with no properties.

Like System.Int32 a list of System.Double or System.Decimal "does not work" either.

Unlike System.Int32 a list of System.DateTimes works because DateTime has properties.

So my conclusion is if a type does not contain any property then a list of instances of this type will not be bound to the DataGridView.

Upvotes: 1

Related Questions