简体   繁体   中英

Datagridview to array missing one row

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!!!

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

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!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM