Class MainWindow 
  Private bd As New CTelefonoBLL()
  Private coTfnos As ColCTelefonos
  Private tfnoAntesDeModificar As String

  Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
    Try
      ' Contextos de datos
      coTfnos = bd.ObtenerFilasTfnos()
      dgTelefonos.DataContext = coTfnos
    Catch ex As System.Exception
      MessageBox.Show(ex.Message)
    End Try
  End Sub

  Private Sub dgTelefonos_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs)
    If e.RemovedItems.Count = 0 Then Return
    Dim obj As CTelefonoBO = TryCast(e.RemovedItems(0), CTelefonoBO)
    ' Cuando se añade un nuevo elemento, obj es Nothing
    If obj IsNot Nothing AndAlso e.AddedItems.Count = 0 AndAlso
       e.RemovedItems.Count <> 0 Then
      bd.BorrarFilaTfnos(obj.Telefono)
    End If
    If obj IsNot Nothing AndAlso tfnoAntesDeModificar IsNot Nothing AndAlso
       e.AddedItems.Count <> 0 AndAlso e.RemovedItems.Count <> 0 Then
      If obj.Telefono <> tfnoAntesDeModificar Then
        If bd.ObtenerFilaTfnos(tfnoAntesDeModificar) IsNot Nothing Then
          bd.BorrarFilaTfnos(tfnoAntesDeModificar)
        End If
      End If
      tfnoAntesDeModificar = Nothing
    End If
  End Sub

  Private Sub dgTelefonos_RowEditEnding(sender As System.Object, e As System.Windows.Controls.DataGridRowEditEndingEventArgs)
    tfnoAntesDeModificar = DirectCast(e.Row.Item, CTelefonoBO).Telefono
  End Sub

  Private Sub Window_Closing(sender As System.Object, e As System.ComponentModel.CancelEventArgs)
    For i As Integer = 0 To coTfnos.Count - 1
      If coTfnos(i).Modificado Then
        ' Insertar
        If bd.ObtenerFilaTfnos(coTfnos(i).Telefono) Is Nothing Then
          bd.InsertarFilaTfnos(coTfnos(i))
        Else
          ' Actualizar
          bd.ActualizarNomDirObs(coTfnos(i))
        End If
      End If
    Next
  End Sub
End Class
