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)
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);
}
}
}
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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With