OMGKurtNilsen
OMGKurtNilsen

Reputation: 5098

Linq from List<T> to DataGridView

I have a List and a dataGridView1 and I'm trying to do this:

var result = from s in sessions
             where s.ID > 0
             select s;
dataGridView1.DataSource = result;

It compiles fine, nothing shows in the DataGridView and no exceptions.

If I however set dataGridView1.DataSource = sessions; it shows everything.

Upvotes: 0

Views: 2675

Answers (3)

Saeed Amiri
Saeed Amiri

Reputation: 22565

Do:

var result = from s in sessions
             where s.ID > 0
             select s;
dataGridView1.DataSource = result.ToList();

In fact because of linq deferred execution, your linq query doesn't execute until you fetch some data.

If you add ToList and you see nothing, it means that there is no result and nothing goes wrong, just check your result.ToList() in watch window in debug mode, if there isn't any result it's OK, but if you see some result may be you should refresh your dataGridView or rebind it.

Upvotes: 2

Lzh
Lzh

Reputation: 3635

I just tried a scenario in which using dataGridView1.DataSource = result.ToList(); works but using result directly doesn't work. It seems that a DataGridView isn't designed to directly bind to an IEnumerable (the result of a Linq statement).

Upvotes: 0

Kev Ritchie
Kev Ritchie

Reputation: 1647

I think this may do the trick:

dataGridView1.DataSource = result.AsDataView();

Upvotes: 2

Related Questions