Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dataGridView "remove empty rows" - button

Sum up:

  • Windows 10

  • Visual Studio 2015

  • C#, Win Forms

  • dataGridView

-> trying to remove empty rows on button click event

(I have no idea where the issue is caused so I generously added code from the other buttons)


I'm using some button to add line(s):
private void someButton_Click(object sender, EventArgs e)
{
    dataGridView1.Rows.Add(1);
    dataGridView1.Select();
    dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0];
}

And another button to remove the last line of the dataGridView:

private void anotherButton_Click(object sender, EventArgs e)
{
    if (dataGridView1.Rows.Count > 0)
    {
        dataGridView1.Rows.Remove(dataGridView1.Rows[dataGridView1.Rows.Count - 1]);
    }
}

Since (at the moment) users will be able to freely edit cells in the dataGridView some rows may end up empty. In order to deal with that I tried to add a third button removing empty rows:

private void thirdButton_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Cells[0].Value == null)
        {
            dataGridView1.Rows.RemoveAt(row.Index);
        }
    }
}


When I press the "thirdButton" some empty rows are removed BUT funnily enough not all of them. I played around for a bit and noticed I had to press the button multiple times to erase all the empty rows. The dataGridView acts like the following:

4 empty rows exist + button press
-> 2 empty rows left

2 empty rows + button press
-> 1 empty row left

1 last empty row + button press
-> 0 empty rows (yay)

(Same with e.g. 11 -> 5 -> 2 -> 1 -> 0)

So it seems my button is halving the number of empty rows and I'd like to know why! Any ideas?

like image 337
Avigrail Avatar asked Jan 07 '23 02:01

Avigrail


1 Answers

You can't modify the collection like that in a ForEach. Try iterating over the collection in reverse, which preserves the index order:

for (int i = dataGridView1.Rows.Count - 1; i > -1; i--)
  {
     DataGridViewRow row = dataGridView1.Rows[i];
     if (!row.IsNewRow && row.Cells[0].Value == null)
       {
          dataGridView1.Rows.RemoveAt(i);
       }
  }
like image 184
LarsTech Avatar answered Jan 08 '23 16:01

LarsTech