views:

587

answers:

1

Hi: I am a programmer teaching myself C#. I have a project that reads rows from an SQL database and displays them in a datagridview. That part works great. I want to show a subset of these records by deleting every non selected row in the grid. This is the code:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (!row.Selected)
    {
         if (!row.IsNewRow)
         {
              dataGridView1.Rows.Remove(row);
            //dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
         }
     }    
}

It either deletes from the bottom up to the selected area and leaves the unselected rows above, or deletes selected as well as unselected rows.

Could anyone point me in the right direction?

Thank You

A: 

The rows are being altered as others are being removed, so some elements are getting skipped incorrectly.

You could use 2 loops: the 1st to invert the selected items, and the 2nd to delete selected items (which would be the previously unselected items prior to inversion).

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            // invert row selections
            if (!row.Selected)
            {
                if (!row.IsNewRow)
                {
                    row.Selected = true;
                }
            }
            else
            {
                row.Selected = false;
            }
        }

        // remove selected rows
        foreach (DataGridViewRow row in dataGridView1.SelectedRows)
        {
            dataGridView1.Rows.Remove(row);
        }
Ahmad Mageed