开发者

LINQ Select certain cell in DataGridView depending on other cell in row

开发者 https://www.devze.com 2023-01-08 06:44 出处:网络
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.

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 did开发者_StackOverflow社区n'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!


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);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消