Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting ‘Created a Boolean flag if empty Dim empty as Boolean = True Dim cellString = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value If cellString Is Nothing OrElse IsDBNull(cellString) OrElse cellString.ToString = String.Empty OrElse String.IsNullOrWhiteSpace(cellString) = True Then empty = True Else empty = False End If End If ‘create variable assigned the rowindex of the last row of the DataGridView Dim lastRow As String = DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(0).Value If (e.ColumnIndex = 0 OrElse e.ColumnIndex = 1 OrElse e.ColumnIndex = 2) Then If empty = False Then ‘If row is not empty then allow the newly generated row on load DataGridView1.AllowUserToAddRows = true Else ‘If row is empty and it’s the last row then prevent the row from being added to ‘the datagridview If empty = True AndAlso e.RowIndex = lastRow Then DataGridView1.AllowUserToAddRows = False ‘If the row is empty and not the last row then paint the cell red Else If empty = True AndAlso e.RowIndex <> lastRow Then DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Red End If End If End If End Sub
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)