How to delete the empty rows in datagridview

From the below code samples 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 of the DataGridview control.

facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>