0

I have a DataGridView with a CheckBox first column.

I use the following Linq to get all the checked rows.

DataGridViewRow[] drs = dgvMain.Rows.Cast<DataGridViewRow>().Where(x =>(!Convert.IsDBNull(x.Cells[0].Value) && Convert.ToBoolean(x.Cells[0].Value))).ToArray();

But somehow the result ALWAYS missing the last checked row!!!

BUT, if I select another roll (not checking it), before I run the line, the last row showed up!!!

Could somebody please be so kind and tell me where did I do wrong!?

Much appreciated!!!

PiggyChu001
  • 440
  • 6
  • 20

2 Answers2

0

You are using this condition:

!Convert.IsDBNull(x.Cells[0].Value) && Convert.ToBoolean(x.Cells[0].Value)

Using && this condition must succeed both left and right.

now my Question is:

Convert.ToBoolean(x.Cells[0].Value) 
 => not a boolean? where clause return as false.
 => what is the purpose? this code doesn't have a reason anymore. You are just 
 converting it to boolean

I suggest you can try only this:

DataGridViewRow[] drs = dgvMain.Rows.Cast<DataGridViewRow>().Where(x =>(!Convert.IsDBNull(x.Cells[0].Value)))
Vijunav Vastivch
  • 4,153
  • 1
  • 16
  • 30
  • The reason I added the second condition is that I "ONLY" want the rows that are "checked"! Without it, it will return "ALL" the rows that ever been "modified"! – PiggyChu001 Feb 11 '19 at 07:08
0

It turned out that the DataGridView is still in Edit Mode when I ran the code, which means the check is not "final"!

That's why the Linq was unable to find it!

So I added

dgvMain.EndEdit();

before the Linq query and the problem is solved!!!

PiggyChu001
  • 440
  • 6
  • 20