'AGENDA TELEFONICA 2 --- Miliuco 07/09/2003
'Ejercicio de acceso a datos:
'- base de datos de Microsoft Access
'- usando DataBinding (enlace  de datos a controles del formulario)

Imports System.Data
Imports System.Data.OleDb

Public Class Inicio
    Inherits System.Windows.Forms.Form

    'Variables declaradas a nivel de clase para poder usarlas desde
    'cualquier procedimiento o función
    Private conn As OleDbConnection = New OleDbConnection 'conexión de tipo OleDb
    Private adaptador As OleDbDataAdapter 'DataAdapter: adaptador de datos
    Private datos As DataSet 'DataSet: conjunto de datos desconectados
    Private enlaceBase As BindingManagerBase 'administrador de los objetos de enlace a datos
    Private comando As OleDbCommandBuilder 'constructor de comandos para el DataAdapter
    Private ruta As String 'almacena la ruta a la base de datos
    Private abierto As Boolean = False 'para saber si ya está abierta la base de datos
    Private cambios As Boolean = False 'para saber si hay cambios pendientes de guardar

#Region " Código generado por el Diseñador de Windows Forms "

    Public Sub New()
        MyBase.New()

        'El Diseñador de Windows Forms requiere esta llamada.
        InitializeComponent()

        'Agregar cualquier inicialización después de la llamada a InitializeComponent()

    End Sub

    'Form reemplaza a Dispose para limpiar la lista de componentes.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Requerido por el Diseñador de Windows Forms
    Private components As System.ComponentModel.IContainer

    'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
    'Puede modificarse utilizando el Diseñador de Windows Forms. 
    'No lo modifique con el editor de código.
    Friend WithEvents lbNombre As System.Windows.Forms.Label
    Friend WithEvents lbTel1 As System.Windows.Forms.Label
    Friend WithEvents lbTel2 As System.Windows.Forms.Label
    Friend WithEvents txNombre As System.Windows.Forms.TextBox
    Friend WithEvents txTel1 As System.Windows.Forms.TextBox
    Friend WithEvents txTel2 As System.Windows.Forms.TextBox
    Friend WithEvents btAvanzar As System.Windows.Forms.Button
    Friend WithEvents btRetroceder As System.Windows.Forms.Button
    Friend WithEvents btPrimero As System.Windows.Forms.Button
    Friend WithEvents btUltimo As System.Windows.Forms.Button
    Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
    Friend WithEvents btInsertar As System.Windows.Forms.Button
    Friend WithEvents btActualizar As System.Windows.Forms.Button
    Friend WithEvents btSalir As System.Windows.Forms.Button
    Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox
    Friend WithEvents lbRegistro As System.Windows.Forms.Label
    Friend WithEvents btCargar As System.Windows.Forms.Button
    Friend WithEvents lbPrimera As System.Windows.Forms.Label
    Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip
    Friend WithEvents Icono As System.Windows.Forms.PictureBox
    Friend WithEvents lbSegunda As System.Windows.Forms.Label
    Friend WithEvents dlgFile As System.Windows.Forms.OpenFileDialog
    Friend WithEvents GroupBox3 As System.Windows.Forms.GroupBox
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    Friend WithEvents btBorrar As System.Windows.Forms.Button
    Friend WithEvents btLimpiar As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Inicio))
        Me.lbNombre = New System.Windows.Forms.Label
        Me.lbTel1 = New System.Windows.Forms.Label
        Me.lbTel2 = New System.Windows.Forms.Label
        Me.lbPrimera = New System.Windows.Forms.Label
        Me.txNombre = New System.Windows.Forms.TextBox
        Me.txTel1 = New System.Windows.Forms.TextBox
        Me.txTel2 = New System.Windows.Forms.TextBox
        Me.btCargar = New System.Windows.Forms.Button
        Me.btAvanzar = New System.Windows.Forms.Button
        Me.btRetroceder = New System.Windows.Forms.Button
        Me.btPrimero = New System.Windows.Forms.Button
        Me.btUltimo = New System.Windows.Forms.Button
        Me.GroupBox1 = New System.Windows.Forms.GroupBox
        Me.lbRegistro = New System.Windows.Forms.Label
        Me.btInsertar = New System.Windows.Forms.Button
        Me.btActualizar = New System.Windows.Forms.Button
        Me.btSalir = New System.Windows.Forms.Button
        Me.GroupBox2 = New System.Windows.Forms.GroupBox
        Me.btLimpiar = New System.Windows.Forms.Button
        Me.btBorrar = New System.Windows.Forms.Button
        Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
        Me.Icono = New System.Windows.Forms.PictureBox
        Me.lbSegunda = New System.Windows.Forms.Label
        Me.dlgFile = New System.Windows.Forms.OpenFileDialog
        Me.GroupBox3 = New System.Windows.Forms.GroupBox
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.GroupBox1.SuspendLayout()
        Me.GroupBox2.SuspendLayout()
        Me.GroupBox3.SuspendLayout()
        Me.SuspendLayout()
        '
        'lbNombre
        '
        Me.lbNombre.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.lbNombre.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lbNombre.Location = New System.Drawing.Point(16, 16)
        Me.lbNombre.Name = "lbNombre"
        Me.lbNombre.Size = New System.Drawing.Size(72, 24)
        Me.lbNombre.TabIndex = 3
        Me.lbNombre.Text = "Nombre"
        Me.lbNombre.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbTel1
        '
        Me.lbTel1.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.lbTel1.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lbTel1.Location = New System.Drawing.Point(16, 48)
        Me.lbTel1.Name = "lbTel1"
        Me.lbTel1.Size = New System.Drawing.Size(80, 24)
        Me.lbTel1.TabIndex = 4
        Me.lbTel1.Text = "Teléfono 1"
        Me.lbTel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbTel2
        '
        Me.lbTel2.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lbTel2.Location = New System.Drawing.Point(216, 48)
        Me.lbTel2.Name = "lbTel2"
        Me.lbTel2.Size = New System.Drawing.Size(80, 24)
        Me.lbTel2.TabIndex = 5
        Me.lbTel2.Text = "Teléfono 2"
        Me.lbTel2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'lbPrimera
        '
        Me.lbPrimera.BackColor = System.Drawing.SystemColors.Control
        Me.lbPrimera.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.lbPrimera.Font = New System.Drawing.Font("Arial", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lbPrimera.ForeColor = System.Drawing.Color.Blue
        Me.lbPrimera.Location = New System.Drawing.Point(24, 240)
        Me.lbPrimera.Name = "lbPrimera"
        Me.lbPrimera.Size = New System.Drawing.Size(432, 96)
        Me.lbPrimera.TabIndex = 11
        Me.lbPrimera.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'txNombre
        '
        Me.txNombre.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
        Me.txNombre.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txNombre.Location = New System.Drawing.Point(96, 16)
        Me.txNombre.Name = "txNombre"
        Me.txNombre.Size = New System.Drawing.Size(304, 23)
        Me.txNombre.TabIndex = 0
        Me.txNombre.Text = ""
        '
        'txTel1
        '
        Me.txTel1.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txTel1.Location = New System.Drawing.Point(96, 48)
        Me.txTel1.Name = "txTel1"
        Me.txTel1.Size = New System.Drawing.Size(96, 23)
        Me.txTel1.TabIndex = 1
        Me.txTel1.Text = ""
        '
        'txTel2
        '
        Me.txTel2.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txTel2.Location = New System.Drawing.Point(304, 48)
        Me.txTel2.Name = "txTel2"
        Me.txTel2.Size = New System.Drawing.Size(96, 23)
        Me.txTel2.TabIndex = 2
        Me.txTel2.Text = ""
        '
        'btCargar
        '
        Me.btCargar.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btCargar.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btCargar.Location = New System.Drawing.Point(24, 24)
        Me.btCargar.Name = "btCargar"
        Me.btCargar.Size = New System.Drawing.Size(96, 24)
        Me.btCargar.TabIndex = 0
        Me.btCargar.TabStop = False
        Me.btCargar.Text = "Cargar datos"
        '
        'btAvanzar
        '
        Me.btAvanzar.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btAvanzar.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btAvanzar.Location = New System.Drawing.Point(352, 24)
        Me.btAvanzar.Name = "btAvanzar"
        Me.btAvanzar.Size = New System.Drawing.Size(40, 24)
        Me.btAvanzar.TabIndex = 4
        Me.btAvanzar.TabStop = False
        Me.btAvanzar.Text = ">"
        Me.ToolTip1.SetToolTip(Me.btAvanzar, "Avanzar")
        '
        'btRetroceder
        '
        Me.btRetroceder.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btRetroceder.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btRetroceder.Location = New System.Drawing.Point(176, 24)
        Me.btRetroceder.Name = "btRetroceder"
        Me.btRetroceder.Size = New System.Drawing.Size(40, 24)
        Me.btRetroceder.TabIndex = 2
        Me.btRetroceder.TabStop = False
        Me.btRetroceder.Text = "<"
        Me.ToolTip1.SetToolTip(Me.btRetroceder, "Retroceder")
        '
        'btPrimero
        '
        Me.btPrimero.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btPrimero.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btPrimero.Location = New System.Drawing.Point(136, 24)
        Me.btPrimero.Name = "btPrimero"
        Me.btPrimero.Size = New System.Drawing.Size(40, 24)
        Me.btPrimero.TabIndex = 1
        Me.btPrimero.TabStop = False
        Me.btPrimero.Text = "<<"
        Me.ToolTip1.SetToolTip(Me.btPrimero, "Primer registro")
        '
        'btUltimo
        '
        Me.btUltimo.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btUltimo.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btUltimo.Location = New System.Drawing.Point(392, 24)
        Me.btUltimo.Name = "btUltimo"
        Me.btUltimo.Size = New System.Drawing.Size(40, 24)
        Me.btUltimo.TabIndex = 5
        Me.btUltimo.TabStop = False
        Me.btUltimo.Text = ">>"
        Me.ToolTip1.SetToolTip(Me.btUltimo, "Ultimo registro")
        '
        'GroupBox1
        '
        Me.GroupBox1.Controls.Add(Me.btAvanzar)
        Me.GroupBox1.Controls.Add(Me.btRetroceder)
        Me.GroupBox1.Controls.Add(Me.btPrimero)
        Me.GroupBox1.Controls.Add(Me.btUltimo)
        Me.GroupBox1.Controls.Add(Me.lbRegistro)
        Me.GroupBox1.Controls.Add(Me.btCargar)
        Me.GroupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.GroupBox1.Location = New System.Drawing.Point(8, 80)
        Me.GroupBox1.Name = "GroupBox1"
        Me.GroupBox1.Size = New System.Drawing.Size(456, 64)
        Me.GroupBox1.TabIndex = 6
        Me.GroupBox1.TabStop = False
        Me.GroupBox1.Text = "Navegación por registros"
        '
        'lbRegistro
        '
        Me.lbRegistro.BackColor = System.Drawing.Color.Navy
        Me.lbRegistro.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.lbRegistro.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.lbRegistro.Font = New System.Drawing.Font("Arial", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lbRegistro.ForeColor = System.Drawing.Color.White
        Me.lbRegistro.Location = New System.Drawing.Point(208, 24)
        Me.lbRegistro.Name = "lbRegistro"
        Me.lbRegistro.Size = New System.Drawing.Size(152, 24)
        Me.lbRegistro.TabIndex = 3
        Me.lbRegistro.Text = "Sin registros"
        Me.lbRegistro.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'btInsertar
        '
        Me.btInsertar.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btInsertar.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btInsertar.Location = New System.Drawing.Point(144, 24)
        Me.btInsertar.Name = "btInsertar"
        Me.btInsertar.Size = New System.Drawing.Size(72, 24)
        Me.btInsertar.TabIndex = 1
        Me.btInsertar.TabStop = False
        Me.btInsertar.Text = "Insertar"
        '
        'btActualizar
        '
        Me.btActualizar.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btActualizar.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btActualizar.Location = New System.Drawing.Point(288, 24)
        Me.btActualizar.Name = "btActualizar"
        Me.btActualizar.Size = New System.Drawing.Size(80, 24)
        Me.btActualizar.TabIndex = 3
        Me.btActualizar.TabStop = False
        Me.btActualizar.Text = "Actualizar"
        '
        'btSalir
        '
        Me.btSalir.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btSalir.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btSalir.Location = New System.Drawing.Point(376, 24)
        Me.btSalir.Name = "btSalir"
        Me.btSalir.Size = New System.Drawing.Size(57, 24)
        Me.btSalir.TabIndex = 9
        Me.btSalir.TabStop = False
        Me.btSalir.Text = "Salir"
        '
        'GroupBox2
        '
        Me.GroupBox2.Controls.Add(Me.btLimpiar)
        Me.GroupBox2.Controls.Add(Me.btBorrar)
        Me.GroupBox2.Controls.Add(Me.btActualizar)
        Me.GroupBox2.Controls.Add(Me.btInsertar)
        Me.GroupBox2.Controls.Add(Me.btSalir)
        Me.GroupBox2.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.GroupBox2.Location = New System.Drawing.Point(11, 152)
        Me.GroupBox2.Name = "GroupBox2"
        Me.GroupBox2.Size = New System.Drawing.Size(448, 64)
        Me.GroupBox2.TabIndex = 7
        Me.GroupBox2.TabStop = False
        Me.GroupBox2.Text = "Edición de registros"
        '
        'btLimpiar
        '
        Me.btLimpiar.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btLimpiar.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btLimpiar.Location = New System.Drawing.Point(16, 24)
        Me.btLimpiar.Name = "btLimpiar"
        Me.btLimpiar.Size = New System.Drawing.Size(120, 24)
        Me.btLimpiar.TabIndex = 0
        Me.btLimpiar.TabStop = False
        Me.btLimpiar.Text = "Nuevo registro"
        '
        'btBorrar
        '
        Me.btBorrar.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btBorrar.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btBorrar.Location = New System.Drawing.Point(224, 24)
        Me.btBorrar.Name = "btBorrar"
        Me.btBorrar.Size = New System.Drawing.Size(56, 24)
        Me.btBorrar.TabIndex = 2
        Me.btBorrar.TabStop = False
        Me.btBorrar.Text = "Borrar"
        '
        'ToolTip1
        '
        Me.ToolTip1.AutomaticDelay = 1000
        '
        'Icono
        '
        Me.Icono.BackColor = System.Drawing.Color.Transparent
        Me.Icono.Cursor = System.Windows.Forms.Cursors.Help
        Me.Icono.Image = CType(resources.GetObject("Icono.Image"), System.Drawing.Image)
        Me.Icono.Location = New System.Drawing.Point(408, 16)
        Me.Icono.Name = "Icono"
        Me.Icono.Size = New System.Drawing.Size(48, 48)
        Me.Icono.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize
        Me.Icono.TabIndex = 17
        Me.Icono.TabStop = False
        '
        'lbSegunda
        '
        Me.lbSegunda.BackColor = System.Drawing.SystemColors.Control
        Me.lbSegunda.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.lbSegunda.Font = New System.Drawing.Font("Arial", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lbSegunda.ForeColor = System.Drawing.Color.Blue
        Me.lbSegunda.Location = New System.Drawing.Point(8, 136)
        Me.lbSegunda.Name = "lbSegunda"
        Me.lbSegunda.Size = New System.Drawing.Size(440, 32)
        Me.lbSegunda.TabIndex = 1
        Me.lbSegunda.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'GroupBox3
        '
        Me.GroupBox3.Controls.Add(Me.Panel1)
        Me.GroupBox3.Controls.Add(Me.lbSegunda)
        Me.GroupBox3.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.GroupBox3.Location = New System.Drawing.Point(8, 224)
        Me.GroupBox3.Name = "GroupBox3"
        Me.GroupBox3.Size = New System.Drawing.Size(456, 176)
        Me.GroupBox3.TabIndex = 10
        Me.GroupBox3.TabStop = False
        Me.GroupBox3.Text = "Avisos y ruta a la base de datos"
        '
        'Panel1
        '
        Me.Panel1.BackColor = System.Drawing.SystemColors.Control
        Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Panel1.Location = New System.Drawing.Point(16, 120)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(424, 5)
        Me.Panel1.TabIndex = 0
        '
        'Inicio
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(470, 408)
        Me.Controls.Add(Me.Icono)
        Me.Controls.Add(Me.txTel2)
        Me.Controls.Add(Me.txTel1)
        Me.Controls.Add(Me.txNombre)
        Me.Controls.Add(Me.lbPrimera)
        Me.Controls.Add(Me.lbTel2)
        Me.Controls.Add(Me.lbTel1)
        Me.Controls.Add(Me.lbNombre)
        Me.Controls.Add(Me.GroupBox1)
        Me.Controls.Add(Me.GroupBox2)
        Me.Controls.Add(Me.GroupBox3)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.Name = "Inicio"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Acceso a datos desconectados"
        Me.GroupBox1.ResumeLayout(False)
        Me.GroupBox2.ResumeLayout(False)
        Me.GroupBox3.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region

    'Al cargar el formulario
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Crear tooltip de 2 líneas en el control Icono
        Me.ToolTip1.SetToolTip(Icono, "Emilio Pérez Egido  (Miliuco)" & ControlChars.CrLf _
        & Space(2) & "8 de Septiembre de 2003")
        'Texto inicial de las etiquetas
        lbPrimera.Text = "Pulsa en ""Cargar datos"" para conectarte a la base de datos." & _
                vbCrLf & "Elige la base de datos en el cuadro de diálogo."
        lbSegunda.Text = "Desconectado. Conjunto de datos vacío."
        'Altura inicial del separador Panel1
        Panel1.Height = 5
    End Sub

    Private Sub btCargar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btCargar.Click
        'Si la base de datos está abierta, simplemente informar
        If abierto = True Then
            Dim aviso As String = "La base de datos ya está cargada en el DataSet"
            lbPrimera.Text = aviso.ToUpper
        End If

        'Si la base de datos NO está abierta
        If abierto = False Then
            Try

                'Cuadro de diálogo para elegir la base de datos
                dlgFile = New OpenFileDialog
                dlgFile.Filter = "Base de datos Agenda (*.mdb)|*.mdb"
                dlgFile.Title = "Selecciona la base de datos Agenda"

                'Si el diálogo devuelve OK
                If dlgFile.ShowDialog() = DialogResult.OK Then
                    'Nombre del archivo elegido, con su ruta completa,
                    'equivale a la base de datos
                    ruta = dlgFile.FileName

                    'Cadena de conexión típica de base de datos de Microsoft Access
                    conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
                    & ruta & ";User Id=admin;Password=;"

                    'DataAdapter: objeto que hace de puente entre la base de datos
                    'y el DataSet o conjunto de datos
                    adaptador = New OleDbDataAdapter("SELECT * FROM Agendatb ORDER BY Nombre", conn)
                    'DataAdapter puede contener sentencias SQL y objetos Command
                    comando = New OleDbCommandBuilder(adaptador)
                    'DataSet: contiene una copia de la base de datos, en esquema XML,
                    'independiente del proveedor, con sus elementos tablas y relaciones.
                    'Es el verdadero almacén de datos desconectados: actuamos sobre
                    'el DataSet desconectado y el DataAdapter se conecta para volcar
                    'los datos entre base de datos y DataSet, en ambos sentidos
                    datos = New DataSet

                    'Abrir la conexión, el DataAdapter llena el DataSet,
                    'cerrar la conexión
                    conn.Open()
                    adaptador.Fill(datos, "Agendatb")
                    conn.Close()

                    'Para enlazar controles del formulario con el DataSet usamos
                    'DataBinding; al objeto Binding le pasamos la propiedad del
                    'control que se debe enlazar, el DataSet y la tabla-columna.
                    'Después, el objeto Binding se añade a la colección de enlaces
                    'de datos (DataBinding) del control elegido, con el método Add()
                    Dim enlace As Binding

                    enlace = New Binding("Text", datos, "Agendatb.Nombre")
                    txNombre.DataBindings.Add(enlace)
                    enlace = Nothing

                    enlace = New Binding("Text", datos, "Agendatb.Teléfono1")
                    txTel1.DataBindings.Add(enlace)
                    enlace = Nothing

                    enlace = New Binding("Text", datos, "Agendatb.Teléfono2")
                    txTel2.DataBindings.Add(enlace)
                    enlace = Nothing

                    'Al objeto BindingManagerBase le pasamos el DataSet y la tabla,
                    'desde el contexto de enlace del formulario (BindingContext)
                    Me.enlaceBase = Me.BindingContext(datos, "Agendatb")

                    lbPrimera.Text = "Base de datos cargada en el conjunto de datos," & _
                    vbCrLf & "usando DataBinding: Enlace de datos a controles." & _
                    vbCrLf & "Para insertar un registro nuevo, pulsa ""Limpiar campos""," & _
                    vbCrLf & "escribe los datos y pulsa ""Insertar"""
                    lbSegunda.Text = "Archivo de datos: " & ruta

                    'Procedimiento descrito más abajo
                    Call verCuenta()
                    'Para saber que la base de datos ya está cargada
                    abierto = True
                End If

            Catch pollo As Exception
                lbPrimera.Text = pollo.Message.ToUpper
            End Try
        End If

    End Sub

    'Mostrar el registro actual y el total de registros de la tabla del DataSet
    Private Sub verCuenta()
        lbRegistro.Text = "Registro " & Me.enlaceBase.Position + 1 & " de " _
        & Me.enlaceBase.Count
    End Sub

    'Gracias al enlace automático entre controles y datos (DataBinding)
    'es muy sencillo navegar entre los registros y se necesita muy poco
    'código para ello, el objeto enlaceBase (BindingManagerBase) se encarga
    'de actualizar de manera automática el control con los datos de la fila
    'de la tabla en que estamos posicionados
    Private Sub btAvanzar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btAvanzar.Click
        'Si la base de datos está abierta
        If abierto = True Then
            Try
                'Si ya estamos en el último registro
                If Me.enlaceBase.Position = Me.enlaceBase.Count - 1 Then
                    Dim aviso1 As String = "Ya estás en el último registro de la tabla"
                    lbPrimera.Text = aviso1.ToUpper
                Else
                    lbPrimera.Text = "Base de datos cargada en el conjunto de datos." & _
    vbCrLf & "Usando DataBinding: Enlace de datos a controles."
                    'avanzar un registro
                    Me.enlaceBase.Position += 1
                    verCuenta()
                End If
            Catch pollo As Exception
                lbPrimera.Text = pollo.Message.ToUpper
            End Try
            'Si la base de datos NO está abierta
        Else
            Dim aviso As String = "Primero has de cargar la base de datos"
            lbPrimera.Text = aviso.ToUpper
        End If

    End Sub

    Private Sub btRetroceder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btRetroceder.Click
        'Si la base de datos está abierta
        If abierto = True Then
            Try
                'Si ya estamos en el primer registro
                If Me.enlaceBase.Position = 0 Then
                    Dim aviso2 As String = "Ya estás en el primer registro de la tabla"
                    lbPrimera.Text = aviso2.ToUpper
                Else
                    lbPrimera.Text = "Base de datos cargada en el conjunto de datos." & _
    vbCrLf & "Usando DataBinding: Enlace de datos a controles."
                    'retroceder un registro
                    Me.enlaceBase.Position -= 1
                    verCuenta()
                End If
            Catch pollo As Exception
                lbPrimera.Text = pollo.Message.ToUpper
            End Try
            'Si la base de datos NO está abierta
        Else
            Dim aviso As String = "Primero has de cargar la base de datos"
            lbPrimera.Text = aviso.ToUpper
        End If
    End Sub

    Private Sub btPrimero_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btPrimero.Click
        'Si la base de datos está abierta
        If abierto = True Then
            Try
                'Si ya estamos en el primer registro
                If Me.enlaceBase.Position = 0 Then
                    Dim aviso2 As String = "Ya estás en el primer registro de la tabla"
                    lbPrimera.Text = aviso2.ToUpper
                Else
                    lbPrimera.Text = "Base de datos cargada en el conjunto de datos." & _
        vbCrLf & "Usando DataBinding: Enlace de datos a controles."
                    'ir al primer registro
                    Me.enlaceBase.Position = 0
                    verCuenta()
                End If
            Catch pollo As Exception
                lbPrimera.Text = pollo.Message.ToUpper
            End Try
            'Si la base de datos NO está abierta
        Else
            Dim aviso As String = "Primero has de cargar la base de datos"
            lbPrimera.Text = aviso.ToUpper
        End If
    End Sub

    Private Sub btUltimo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btUltimo.Click
        'Si la base de datos está abierta
        If abierto = True Then
            Try
                'Si ya estamos en el último registro
                If Me.enlaceBase.Position = Me.enlaceBase.Count - 1 Then
                    Dim aviso1 As String = "Ya estás en el último registro de la tabla"
                    lbPrimera.Text = aviso1.ToUpper
                Else
                    : lbPrimera.Text = "Base de datos cargada en el conjunto de datos." & _
                       vbCrLf & "Usando DataBinding: Enlace de datos a controles."
                    'ir al último registro
                    Me.enlaceBase.Position = Me.enlaceBase.Count - 1
                    verCuenta()
                End If
            Catch pollo As Exception
                lbPrimera.Text = pollo.Message.ToUpper
            End Try
            'Si la base de datos NO está abierta
        Else
            Dim aviso As String = "Primero has de cargar la base de datos"
            lbPrimera.Text = aviso.ToUpper
        End If
    End Sub

    'Para borrar un registro
    Private Sub btBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btBorrar.Click
        'Si la base de datos está abierta
        If abierto = True Then
            Try
                'Borrar el registro que se corresponde con la posición actual
                Me.enlaceBase.RemoveAt(Me.enlaceBase.Position)
                lbPrimera.Text = "Se ha eliminado un registro." & vbCrLf _
                & "Pulsa actualizar si deseas guardar los cambios."
                cambios = True
            Catch pollo As Exception
                lbPrimera.Text = pollo.Message.ToUpper
            End Try
            'Si la base de datos NO está abierta
        Else
            Dim aviso As String = "Primero has de cargar la base de datos"
            lbPrimera.Text = aviso.ToUpper
        End If
    End Sub

    'Para vaciar los campos de texto
    Private Sub btLimpiar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btLimpiar.Click
        'Si la base de datos está abierta
        If abierto = True Then
            txNombre.Text = ""
            txTel1.Text = ""
            txTel2.Text = ""
            txNombre.Focus()
            'Si la base de datos NO está abierta
        Else
            Dim aviso As String = "Primero has de cargar la base de datos"
            lbPrimera.Text = aviso.ToUpper
        End If
    End Sub

    'Para añadir un registro
    Private Sub btInsertar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btInsertar.Click
        'Si la base de datos está abierta
        If abierto = True Then
            ''crear una nueva fila en la tabla
            Dim fila As DataRow
            fila = Me.datos.Tables("Agendatb").NewRow()
            Try
                'rellenar los campos de la fila nueva
                fila("Nombre") = txNombre.Text
                fila("Teléfono1") = txTel1.Text
                fila("Teléfono2") = txTel2.Text
                lbPrimera.Text = "Se ha insertado un registro nuevo." & vbCrLf _
                & "Pulsa actualizar si deseas guardar los cambios."
                'añadir la nueva fila a la tabla
                Me.datos.Tables("Agendatb").Rows.Add(fila)
                cambios = True
            Catch pollo As Exception
                lbPrimera.Text = pollo.Message.ToUpper
            End Try
            'Si la base de datos NO está abierta
        Else
            Dim aviso As String = "Primero has de cargar la base de datos"
            lbPrimera.Text = aviso.ToUpper
        End If
    End Sub

    'Para actualizar el adaptador de datos (DataAdapter) con los cambios hechos en el DataSet
    Private Sub btActualizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btActualizar.Click
        'Si la base de datos está abierta
        If abierto = True Then
            'Si ha habido cambios en el DataSet desde la última actualización
            If (cambios = True) Then
                Try
                    conn.Open()
                    'Actualizar DataAdapter, se pueden pasar parámetros:
                    ' - (datos as dataset, "tabla" as string)
                    ' - (datos.tables("tabla") as dataset) --> usado aquí
                    Me.adaptador.Update(Me.datos.Tables("Agendatb"))
                    'Vaciar el DataSet: conserva los datos de tablas y registros y si no
                    'se limpia acumula las operaciones sucesivas de modificación de filas
                    Me.datos.Clear()
                    'Volver a llenar el DataSet desde el DataAdapter ya modificado
                    Me.adaptador.Fill(datos, "Agendatb")
                    conn.Close()
                    'Actualizar la etiqueta lbRegistro
                    Call verCuenta()
                    'Indicador de cambios pendientes a false
                    cambios = False
                    Dim aviso As String = "Base de datos actualizada con los cambios realizados"
                    lbPrimera.Text = aviso.ToUpper
                Catch pollo As Exception
                    lbPrimera.Text = pollo.Message.ToUpper
                End Try
            Else
                '    'Si NO ha habido cambios en el DataSet desde la última actualización
                Dim aviso2 As String = "No hay cambios pendientes de actualizar"
                lbPrimera.Text = aviso2.ToUpper
            End If
            'Si la base de datos NO está abierta
        Else
            Dim aviso3 As String = "Primero has de cargar la base de datos"
            lbPrimera.Text = aviso3.ToUpper
        End If
    End Sub

    Private Sub btSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btSalir.Click
        'Si la base de datos NO está abierta
        If abierto = False Then
            'Cerrar el formulario
            Me.Close()
        End If
        If abierto = True Then
            'si NO ha habido cambios en el DataSet desde la última actualización
            If cambios = False Then
                'Cerrar el formulario
                Me.Close()
            End If
            'Si la base de datos está abierta y si además
            'ha habido cambios en el DataSet desde la última actualización 
            If cambios = True Then
                If MessageBox.Show("Hay cambios pendientes de guardar." & vbCrLf _
                & "Pulsa en ""Cancelar"" para volver al programa." & _
                vbCrLf & "Pulsa en ""Aceptar"" para salir sin guardar", _
                "Cambios sin guardar", MessageBoxButtons.OKCancel, _
                MessageBoxIcon.Exclamation) = DialogResult.OK Then
                    Me.Close()
                End If
            End If
        End If
    End Sub

End Class