我有一个DataGridView,它受VB.net Windows窗体应用程序中的数据源绑定。当我将数据导入DataGrid时,我希望任何空白或空字段都用红色着色,直到用户输入数据。我已经完成了这个,但我有一个小问题。当用户向DataGrid添加一个新的空行并且没有填充任何数据时,加载时新形成的行将完全用红色着色,而我想在加载时删除这个新生成的行。这就是我这样做的方式,但我没有成功。非常感谢您提供的任何帮助或建议。
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 empty = True AndAlso e.RowIndex = lastRow Then
'If row is empty and it’s the last row then prevent the row from being added to ‘the datagridview
DataGridView1.AllowUserToAddRows = False
Else If empty = True AndAlso e.RowIndex <> lastRow Then
'the row is empty and not the last row then paint the cell red
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Red
End If
End If
End If
End Sub