How to delete the empty rows in datagridview

With the help of the following example you can remove the all empty rows in your datagridview control.

[VB.net]

  1.  Dim blank as boolean =true
  2.  For Each _row As DataGridViewRow In DataGridView1.Rows
  3.             blank = True
  4.             For i As Integer = 0 To _row.Cells.Count - 1
  5.                 If _row.Cells(i).Value IsNot Nothing AndAlso _row.Cells(i).Value <> "" Then
  6.                     blank = False
  7.                     Exit For
  8.                 End If
  9.             Next
  10.             If blank Then
  11.                 If Not _row.IsNewRow Then
  12.                     DataGridView1.Rows.Remove(_row)
  13.                 End If
  14.             End If
  15.         Next

[C#]

  1. bool blank = true;
  2. foreach (DataGridViewRow _row in DataGridView1.Rows) {
  3.  blank = true;
  4.  for (int i = 0; i <= _row.Cells.Count - 1; i++) {
  5.   if (_row.Cells(i).Value != null && !string.IsNullOrEmpty(_row.Cells(i).Value)) {
  6.    blank = false;
  7.    break;
  8.   }
  9.  }
  10.  if (blank) {
  11.   if (!_row.IsNewRow) {
  12.    DataGridView1.Rows.Remove(_row);
  13.   }
  14.  }
  15. }

The above code will not delete the last row which is created automatically.
However this is not good practice to delete the empty rows after set the datasource to the DataGridView. You can ignore the empty records from database before set the datasource property of the DataGridview control.

Published by

Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.

  • Tarak Bhavsar

    the Vb Code doesn’t work. I tried for the last uncommitted row