How to delete empty rows in a Datagridview using C#?

To remove blank rows in the DataGridView, you can follow these steps:

  1. Iterate through all rows in the DataGridView.
  2. Iterate through all the rows in dataGridView1.
  3. Check if the values of all cells are empty in each row.
  4. Check if a row is empty by looping through the columns of a DataGridView.
  5. Delete the line if it is a blank line.
  6. 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.

广告
Closing in 10 seconds
bannerAds