views:

37

answers:

2

I am brand spanking new to LINQ and am trying to use it in my current hobby project. I have a datagridview where the first cell of each row is a datagridviewcheckbox, and the 4th cell is a string.

If the checkbox is checked, I need to add the 4th cell's value to a list.

At first I tried:

var selectedID = from c in multiContactLookup.SelectedCells.Cast<DataGridViewCell>() 
                              select multiContactLookup.Rows[c.RowIndex].Cells[4].Value;

That didn't work because the checked cells are programatically unselected so c is never a value.

Then I tried:

var sel2 = from r in multiContactLookup.Rows.Cast<DataGridViewRow>()
                       where r.Cells[0].Value is true select r.Cells[4].Value;

but somehow my syntax is wrong.

Using LINQ, how can I select the rows where the first cell is checked then select the value of the first cell? Do I have to split this into two collections?

Thank you!

+4  A: 

I think this should work:

IEnumerable<string> values = multiContactLookup.Rows.Cast<DataGridViewRow>()
    .Where(row => (bool)row.Cells[0].Value)
    .Select(row => (string)row.Cells[3].Value);
Lee
A: 

Maybe not the answer you have been looking for, but...

DataGridView (as most win-forms controls) is not the best source to start with LINQ. Most collections do not implement the correct IEnumerable<T> interface. That's the reason why you need the Cast() workaround.

In general, try to move your applications behavior away from controls and into the data. Maybe your grid is connected to a DataTable. In this case register the DataTable's events for changed data and work with the values of the DataRow, instead of the DataGridViewRow and its cells.

Greets Flo

Florian Reischl