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]

 Dim blank as boolean =true
 For Each _row As DataGridViewRow In DataGridView1.Rows
            blank = True
            For i As Integer = 0 To _row.Cells.Count - 1
                If _row.Cells(i).Value IsNot Nothing AndAlso _row.Cells(i).Value <> "" Then
                    blank = False
                    Exit For
                End If
            Next
            If blank Then
                If Not _row.IsNewRow Then
                    DataGridView1.Rows.Remove(_row)
                End If
            End If
        Next

[C#]

bool blank = true;
foreach (DataGridViewRow _row in DataGridView1.Rows) {
	blank = true;
	for (int i = 0; i <= _row.Cells.Count - 1; i++) {
		if (_row.Cells(i).Value != null && !string.IsNullOrEmpty(_row.Cells(i).Value)) {
			blank = false;
			break; 
		}
	}
	if (blank) {
		if (!_row.IsNewRow) {
			DataGridView1.Rows.Remove(_row);
		}
	}
}

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.

2 thoughts on “How to delete the empty rows in datagridview”

    1. That would be because of the following line:

      If Not _row.IsNewRow Then

      This means that it will not remove new rows.

Comments are closed.