Avigrail
Avigrail

Reputation: 321

dataGridView "remove empty rows" - button

Sum up:

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

Upvotes: 4

Views: 11284

Answers (2)

LarsTech
LarsTech

Reputation: 81675

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

Upvotes: 8

MaKiPL
MaKiPL

Reputation: 1200

There are two things that came up to my mind. First one is:

  1. You should check for null and "". To simplify this just check if the row length is equal to 0. Sometimes the user may leave a whitespace that wouldn't be detected as null nor length == 0, so try to remove whitespace at every entry programatically before checking
  2. The second issue may be the index order. When you remove rows, the index raises and leaves one row behind. One solution is delete the rows from the end.

Upvotes: 1

Related Questions