How to delete empty rows in a Datagridview using C#?
To remove blank rows in the DataGridView, you can follow these steps:
- Iterate through all rows in the DataGridView.
- Iterate through all the rows in dataGridView1.
- Check if the values of all cells are empty in each row.
- Check if a row is empty by looping through the columns of a DataGridView.
- Delete the line if it is a blank line.
- if the row is empty, then remove it from the dataGridView1.
A full code example:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
bool isEmptyRow = true;
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null && !string.IsNullOrWhiteSpace(dataGridView1.Rows[i].Cells[j].Value.ToString()))
{
isEmptyRow = false;
break;
}
}
if (isEmptyRow)
{
dataGridView1.Rows.RemoveAt(i);
}
}
Note: After deleting a row, the row indexes will change, so it is necessary to decrement the value of i in order to correctly traverse all rows.