Deleting rows from a DataGridView control.

Hi:

I'm trying to figure out the best way to delete rows from my dataGridView control.
The dataGridView contains 2 colums: 1 - CheckBox; 2 - String

I would like to be able to delete the rows based on whether the checkbox is selected or not.

My code looks like this:

                // Loop through and remove the rows where the value is checked
                foreach (DataGridViewRow dgvExistingRow in this.dataGridViewFileNames.Rows)
                {
                    if (dgvExistingRow.Cells["FileCheckBox"].Value.Equals(true))
                    {
                        this.dataGridViewFileNames.Rows.Remove(dgvExistingRow);
                    }
                }

This isn't quite working right. If all the rows are to be removed (they are all checked), then only N-1 rows are removed,
where N is the number of rows in the row collection.

I know this should be relatively straightforward, but I'm just not seeing it.

Thanks in advance,
JohnB
LVL 1
jxbmaSoftware ConsultantAsked:
Who is Participating?
 
Anurag ThakurConnect With a Mentor Technical ManagerCommented:
Have a look at the following link
it explains the functionality as you require
http://www.dotnetjohn.com/articles.aspx?articleid=51
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
You have to do a cycle from the last row to the first in order to delete.
0
 
OBonioCommented:
You can't modify a collection whilst iterating through it.  ie,  you are not allowed to remove row from datagrid while doing a foreach on the rows collection.

You need to remove them outside of the foreach loop.  To do this, create an ArrayList which you add the row to in the foreach loop then iterate the ArrayList after the foreach, removing each row.

That should do the job.
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
If you need help with the code just say it!
I can show you a code snippet.
0
 
Anurag ThakurTechnical ManagerCommented:
Hi, my comment ID:22719426 indicates a complete coding example as to how to implement his/her required functionality
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.