这是我的最终解决方案。它对我有用,我希望它在概念上是正确的。我使用了代表和Leave + LostFocus事件。
'**********
'* Controllo righe da eliminare
'**********
Private Sub dgvSpSettings_RowLeave(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSpSettings.RowLeave
Me.dgvSpSettings.CommitEdit(0)
Dim row As DataGridViewRow = Me.dgvSpSettings.Rows(e.RowIndex)
For Each cell In row.Cells
cell.Style.BackColor = Color.White
Next
If Not row.IsNewRow() Then 'Esclude l'ultima riga dal controllo sulle righe vuote
If String.IsNullOrEmpty(row.Cells(0).Value) OrElse String.IsNullOrEmpty(row.Cells(1).Value) Then
_rowBlank = row
End If
End If
End Sub
Private Delegate Sub setCurrentCellDelegate()
Private Sub setCurrentCell()
For Each cell In _rowBlank.Cells
cell.Style.BackColor = Color.LightSalmon
Next
Me.dgvSpSettings.CurrentCell = _rowBlank.Cells(0)
Me.dgvSpSettings.BeginEdit(True)
_rowBlank = Nothing
End Sub
Private Delegate Sub removeRowDelegate()
Private Sub removeRow()
Me.dgvSpSettings.Rows.Remove(_rowBlank)
_rowBlank = Nothing
_rowBlankDeleting = False
End Sub
'**********
'* Controllo righe da eliminare
'**********
Private Sub dgvSpSettings_Leave(sender As Object, e As System.EventArgs) Handles dgvSpSettings.Leave
If _rowBlank IsNot Nothing AndAlso _rowBlankDeleting = False Then
If MsgBox("Alcuni campi della riga non sono stati valorizzati. Eliminare la riga?", vbYesNo + vbInformation, "Eliminare") = MsgBoxResult.Yes Then
_rowBlankDeleting = True
Me.dgvSpSettings.BeginInvoke(New removeRowDelegate(AddressOf removeRow))
Else
Me.dgvSpSettings.BeginInvoke(New setCurrentCellDelegate(AddressOf setCurrentCell))
End If
End If
End Sub
'**********
'* Controllo righe da eliminare
'**********
Private Sub dgvSpSettings_LostFocus(sender As Object, e As System.EventArgs) Handles dgvSpSettings.LostFocus
If _rowBlank IsNot Nothing AndAlso _rowBlank IsNot Me.dgvSpSettings.CurrentRow AndAlso _rowBlankDeleting = False Then
If MsgBox("Alcuni campi della riga non sono stati valorizzati. Eliminare la riga?", vbYesNo + vbInformation, "Eliminare") = MsgBoxResult.Yes Then
_rowBlankDeleting = True
Me.dgvSpSettings.BeginInvoke(New removeRowDelegate(AddressOf removeRow))
Else
Me.dgvSpSettings.BeginInvoke(New setCurrentCellDelegate(AddressOf setCurrentCell))
End If
End If
End Sub