Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a DataGridView that is bound by a datasource in VB.net Windows forms application. When I import my data into the DataGrid I want any blank or null fields to be colored in red until the user inputs data. I’ve already accomplished this but I have a slight issue. When the user adds a new blank row to the DataGrid and doesn’t fill in any data, that newly formed row on load up will be completely colored in red, instead I want to delete this newly generated row on load. This is how I’ve gone about doing this, but I haven’t been successful. I greatly appreciate any help or suggestions you may offer.


VB
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
Posted

1 solution

If the user isn't allowed to add a row, then set the DataGridView.AllowUserToAddRows[^] property to False. I believe this will stop the new row from showing up on the screen.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900