' EJERCICIO DE CONEXION A BD DE ACCESS
' Antes de ejecutarlo por primera vez, hay que crear
' una nueva base de datos, llamada pruebasDB.mdb
' que contenga 3 tablas:
' - Prueba1: tabla que es modificada desde el programa
' - Prueba2: registros que el programa copia a Prueba1
' - Prueba3: tabla de reserva con todos los registros originales
'
' Las 3 tablas han de tener la misma estructura:
' - Nombre: campo de texto, max. 40 caracteres
' - Teléfono: campo de texto, max. 9 caracteres
'
' La tabla Prueba1 puede estar vacía, pero la tabla Prueba2 ha de
' tener registros.
'
Imports System
Imports System.Collections
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports Microsoft.VisualBasic
'
Imports System.Data
Imports System.Data.OleDb
'
Public Class sqlaccessForm
    Inherits System.Web.UI.Page

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

    'El Diseñador de Web Forms requiere esta llamada.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents btDrop As System.Web.UI.WebControls.Button
    Protected WithEvents Form1 As System.Web.UI.HtmlControls.HtmlForm
    Protected WithEvents brCrear As System.Web.UI.WebControls.Button
    Protected WithEvents btInsert As System.Web.UI.WebControls.Button
    Protected WithEvents btSelect1 As System.Web.UI.WebControls.Button
    Protected WithEvents btSelect2 As System.Web.UI.WebControls.Button
    Protected WithEvents btUpdate As System.Web.UI.WebControls.Button
    Protected WithEvents btDelete As System.Web.UI.WebControls.Button
    Protected WithEvents lbMostrar As System.Web.UI.WebControls.Label
    Protected WithEvents btClose As System.Web.UI.WebControls.Button
    Protected WithEvents btCopiar As System.Web.UI.WebControls.Button
    Protected WithEvents btCrear As System.Web.UI.WebControls.Button
    Protected WithEvents lbMostrar1 As System.Web.UI.WebControls.Label
    Protected WithEvents lbMostrar3 As System.Web.UI.WebControls.Label
    Protected WithEvents lbMostrar2 As System.Web.UI.WebControls.Label
    Protected WithEvents txNom As System.Web.UI.WebControls.TextBox
    Protected WithEvents txTel As System.Web.UI.WebControls.TextBox
    Protected WithEvents btInsert2 As System.Web.UI.WebControls.Button
    Protected WithEvents txId As System.Web.UI.WebControls.TextBox
    Protected WithEvents btDelete2 As System.Web.UI.WebControls.Button
    Protected WithEvents btBuscar1 As System.Web.UI.WebControls.Button
    Protected WithEvents btBuscar2 As System.Web.UI.WebControls.Button
    Protected WithEvents txSel1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents txSel2 As System.Web.UI.WebControls.TextBox

    'NOTA: el Diseñador de Web Forms necesita la siguiente declaración del marcador de posición.
    'No se debe eliminar o mover.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: el Diseñador de Web Forms requiere esta llamada de método
        'No la modifique con el editor de código.
        InitializeComponent()
    End Sub

#End Region

#Region " Declaración de Variables "
    ' Objeto conexión de tipo OleDb
    Protected con As OleDbConnection = New OleDbConnection
    ' Para construir la cadena de conexión a la BD
    ' Server.MapPath refiere a la carpeta desde la que arranca la aplicación
    Protected ruta As String = Server.MapPath("../datos/pruebasDB.mdb")
    Protected conectar As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
    ' Objeto de comando, permite ejecutar las sentencias SQL
    Protected com As OleDbCommand = New OleDbCommand
    ' Las clases pueden ser abstractas ("abstract") o selladas ("sealed", precintadas):
    ' - una clase abstracta requiere una clase derivada para proporcionar una implementación.
    ' - una clase sellada no admite una clase derivada.
    ' DataReader es una clase precintada o sellada, no se puede heredar de ella
    Protected col As OleDbDataReader
    ' Variables para las columnas de la tabla
    Protected nom, tel As String ' valores de cadena
    Protected ide As Integer ' valor autonumérico (ver más adelante)
    Protected i As Integer ' número de registrosmodificados
    Protected ejercicio As String ' texto para mostrar en la etiqueta lbMostrar3
    Protected a1, a2, a3, a4 As String ' para almacenar variables de texto (cuadros de texto)
#End Region

#Region " Carga de la página "
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' SmartNavigation indica si los desplazamientos inteligentes están habilitados. No es conveniente
        ' establecer esta propiedad en el código. Es mejor esstablecer el atributo 
        ' SmartNavigation como true en la directiva @ Page del archivo .aspx. Cuando se 
        ' solicita la página, la clase generada dinámicamente establece esta propiedad.
        ' Los desplazamientos inteligentes mejoran la experiencia del usuario con la página por: 
        ' - eliminar el parpadeo originado por el desplazamiento.
        ' - mantener la posición de desplazamiento al ir de una página a otra.
        ' - mantener el foco del elemento entre desplazamientos.
        ' - conservar sólo el estado de la última página en el historial del explorador.
        'Me.SmartNavigation = True
        '
        ' Texto para mostrar en la etiqueta lbMostrar3
        'ejercicio = "<div align=center><ul><li>Borrar la tabla existente:<br>" & _
        '"(<b>DROP TABLE Tabla;</b>)</li>" & _
        '"<li>Crear la tabla ""Prueba1"":<br>" & _
        '"(<b>CREATE TABLE Tabla;</b>)</li>" & _
        '"<li>Insertar registros nuevos:<br>" & _
        '"(<b>INSERT INTO Tabla (Campo1, Campo2) VALUES ('Valor1', 'Valor2');</b>)</li>" & _
        '"<li>Registros sin ordenar:<br>" & _
        '"(<b>SELECT * FROM Tabla;</b>)</li>" & _
        '"<li>Registros ordenados por Nombre:<br>" & _
        '"(<b>SELECT * FROM Tabla ORDER BY Nombre;</b>)</li>" & _
        '"<li>Modificar un registro:<br>" & _
        '"(<b>UPDATE Tabla SET Campo1='Valor1', Campo2='Valor2' WHERE Campo='Valor';</b>)</li>" & _
        '"<li>Borrar un registro:<br>" & _
        '"(<b>DELETE FROM Tabla WHERE Campo='Valor';</b>)</li>" & _
        '"<li>Copiar registros desde otra tabla:<br>" & _
        '"(<b>INSERT INTO Tabla SELECT Campo1, Campo2 FROM Tabla2;</b>)</li></ul></div>"
        If Not Page.IsPostBack Then
            'Me.lbMostrar3.Text = ejercicio
            '
            ' Vaciar las cajas de texto
            Me.txNom.Text = ""
            Me.txTel.Text = ""
            Me.txId.Text = ""
            Me.txSel1.Text = ""
            Me.txSel2.Text = ""
        End If
    End Sub
#End Region

#Region " Procedimiento que ejecuta la instrucción SQL y muestra los datos "

    ' Se dispara al pulsar cualquiera de los botones
    Sub comandoSQL(ByVal sender As Object, ByVal e As System.EventArgs) Handles btDrop.Click, btCrear.Click, btInsert.Click, btSelect1.Click, btSelect2.Click, btUpdate.Click, btDelete.Click, btDelete2.Click, btInsert2.Click
        Try
            ' Cadena de conexión a la BD
            con.ConnectionString = conectar & ruta
            ' Abrir la conexión
            con.Open()
            ' Asignar el comando a la conexión creada
            com.Connection = con            '
            ' Los objetos de comando tienen distintos métodos de ejecución:
            ' - visualizar los datos: ExecuteReader() ejecuta una sentencia SQL y
            ' devuelve un objeto OleDbDataReader con los datos (se captura su valor de retorno)
            ' - modificar los datos: ExecuteNonQuery() ejecuta una sentencia SQL
            ' que no devuelve datos(DELETE, UPDATE, INSERT...) (no se captura su valor de retorno)
            ' - devolver un valor único (una única columna) después de ejecutar
            ' una sentencia SELECT: ExecuteScalar(). Ejemplo: buscar la media o un valor máximo
            ' Se asigna a la propiedad Text del comando la cadena SQL y se ejecuta
            ' Después se muestran los datos en pantalla añadiendo texto a las etiquetas 
            ' formateando el HTML de salida.
            '
            ' Hacemos una selección dependiendo del texto del botón pulsado:
            ' Sender es el objeto pasado como parámetro (el botón pulsado), Click es el evento detectado
            Select Case sender.Text
                ' ------------------
                ' botón DROP
            Case "Drop"
                    com.CommandText = "DROP TABLE Prueba1;"
                    com.ExecuteNonQuery()
                    'Me.lbMostrar.Text = "<b><font size=+1>BORRAR LA TABLA Prueba1</font></b>"
                    Me.lbMostrar.Text = ""
                    Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>DROP TABLE Prueba1;</font></b><br>"
                    ' Vaciar las cajas de texto
                    Me.txNom.Text = ""
                    Me.txTel.Text = ""
                    Me.txId.Text = ""
                    Me.txSel1.Text = ""
                    Me.txSel2.Text = ""
                    ' ----------------------
                    ' botón CREATE
                Case "Create"
                    com.CommandText = "CREATE TABLE Prueba1 " & _
           "(Id INTEGER IDENTITY PRIMARY KEY, Nombre VARCHAR(40), Teléfono CHAR(9));"
                    com.ExecuteNonQuery()
                    'Me.lbMostrar.Text = "<b><font size=+1>CREAR LA TABLA Prueba1</font></b><br><br>"
                    Me.lbMostrar.Text = ""
                    Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>CREATE TABLE Prueba1<br>" & _
                    "(Id INTEGER IDENTITY PRIMARY KEY, <br>Nombre VARCHAR(40), <br>Teléfono CHAR(9));" & _
                    "</font></b><br>"
                    ' Vaciar las cajas de texto
                    Me.txNom.Text = ""
                    Me.txTel.Text = ""
                    Me.txId.Text = ""
                    Me.txSel1.Text = ""
                    Me.txSel2.Text = ""
                    ' ---------------------
                    ' botones INSERT
                Case "Insert"
                    ' hay 2 botones con texto idéntico "Insert", para diferenciarlos
                    ' recurrimos a su ID que sí es diferente: "btInsert" y "btInsert2"
                    ' asignamos el valor del ID a la variable de cadena a4
                    a4 = CType(sender, Button).ID
                    ' si el ID es "btInsert"
                    If a4 = "btInsert" Then
                        Me.lbMostrar.Text = a4
                        ' i devuelve el número de filas afectadas por el comando
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('AEK Group INC', '923652547');"
                        i = com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Orion Capital Corp.', '900125458');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('IBM', '956985447');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('ACE Hardware Corp.', '945896325');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Baxter International Inc.', '936521452');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Lockheed Martin Corp.', '903056898');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Bay Networks Inc.', '985654125');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('MCI Communications Corp.', '900326587');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('BDO Seidman LLP', '978563214');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Caterpillar Inc.', '932655096');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Data General Corp.', '955561023');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Gateway Inc.', '993201145');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Hewlett-Packard Co.', '975556912');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('ICF Kaiser International Inc.', '990023654');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('ADI Systems Inc.', '922569687');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Ikon Office Solutions Inc.', '914525890');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('J.P. Morgan and Co. Inc.', '922258961');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Kansas City Southern Industries Inc.', '926352145');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Dayton Hudson Corp.', '987654789');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Eastman Kodak Co.', '933655896');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Case Corp.', '900125458');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Eaton Corp.', '923659654');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Medtronic Inc.', '900125458');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Mellon Bank Corp.', '900125458');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Edison International', '944456902');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Fifth Third BanCorp', '920126032');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Ohio Casualty Corp.', '900125458');"
                        i += com.ExecuteNonQuery()
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('Paine Webber Group Inc.', '999521477');"
                        i += com.ExecuteNonQuery()
                        'Me.lbMostrar.Text = "<b><font size=+1>INSERTAR REGISTROS NUEVOS</font></b><br><br>"
                        Me.lbMostrar.Text = ""
                        Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>INSERT INTO Prueba1 (Nombre, Teléfono) <br>" & _
                        "VALUES ('Nombre', 'Teléfono');" & _
                        "</font></b><br>"
                        Me.lbMostrar2.Text += "Registros insertados: <b><font color=blue>" & i & "</font></b><br>"
                        com.CommandText = "SELECT COUNT(*) FROM Prueba1;"
                        i = com.ExecuteScalar
                        Me.lbMostrar2.Text += "Registros totales: <b><font color=blue>" & i & "</font></b><br>"
                        '
                        ' si el ID es "btInsert2"
                    ElseIf a4 = "btInsert2" Then
                        a1 = CType(txNom, TextBox).Text
                        a2 = CType(txTel, TextBox).Text
                        com.CommandText = "INSERT INTO Prueba1 (Nombre, Teléfono) VALUES ('" & a1 & "', '" & a2 & "');"
                        i = com.ExecuteNonQuery()
                        'Me.lbMostrar.Text = "<b><font size=+1>INSERTAR REGISTRO NUEVO</font></b><br><br>"
                        Me.lbMostrar.Text = ""
                        Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>INSERT INTO Prueba1 (Nombre, Teléfono) <br>VALUES ('" & a1 & "', '" & a2 & "');" & "</font></b><br>"
                        Me.lbMostrar2.Text += "Registros insertados: <b><font color=blue>" & i & "</font></b><br>"
                        com.CommandText = "SELECT COUNT(*) FROM Prueba1;"
                        i = com.ExecuteScalar
                        Me.lbMostrar2.Text += "Registros totales: <b><font color=blue>" & i & "</font></b><br>"
                        'Me.txNom.Text = ""
                        'Me.txTel.Text = ""
                    End If
                    ' ---------------------
                    ' botón SELECT
                Case "Select"
                    a4 = CType(sender, Button).ID
                    ' según el ID del botón
                    If a4 = "btSelect1" Or a4 = "btSelect2" Then
                        If a4 = "btSelect1" Then
                            ' texto del comando con la instrucción SQL
                            com.CommandText = "SELECT * FROM Prueba1;"
                            ' El DataReader:
                            ' - no puede trabajar en modo desconectado
                            ' - es un objeto de sólo lectura
                            ' - su finalidad es la de acceder lo más rápido posible a los datos
                            ' - sólo permite movimiento hacia adelante a través de los registros
                            ' - se usan bucles para recorrer el DataReader hasta el final
                            col = com.ExecuteReader()
                            'Me.lbMostrar.Text = "<b><font size=+1>REGISTROS SIN ORDENAR</font></b><br><br>"
                            Me.lbMostrar.Text = ""
                            Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>SELECT * FROM Prueba1;</font></b><br>"
                            '
                        ElseIf a4 = "btSelect2" Then
                            ' texto del comando con la instrucción SQL
                            com.CommandText = "SELECT * FROM Prueba1 ORDER BY Nombre;"
                            col = com.ExecuteReader()
                            'Me.lbMostrar.Text = "<b><font size=+1>REGISTROS ORDENADOS POR NOMBRE</font></b><br><br>"
                            Me.lbMostrar.Text = ""
                            Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>SELECT * FROM Prueba1 ORDER BY Nombre;</font></b><br>"
                        End If
                        '
                        Me.lbMostrar.Text += "<table align=center cellspacing=1>" & _
                                  "<tr><td width=40 bgcolor=lavender><b><font face=Verdana size=2>" & _
                                  col.GetName(0).ToUpper() & _
                                  "</font></b></td><td width=260 align=center bgcolor=lavender>" & _
                                  "<b><font face=Verdana size=2>" & col.GetName(1).ToUpper() & _
                                  "</b></font></td><td width=100 align=center bgcolor=lavender>" & _
                                  "<b><font face=Verdana size=2>" & _
                                  col.GetName(2).ToUpper() & "</font></b></td></tr></table><hr color=blue width=400>"
                        ' recorrer el DataReader hacia adelante
                        While (col.Read)
                            ' Se muestran 3 formas de obtener datos de un OleDbDataReader:
                            ' - recuperación por índice, devuelve datos de la columna
                            ' con el índice declarado (variables ide y nom), se usan
                            ' 2 propiedades diferentes: Item(i) y GetValue(i)
                            ' - recuperación por nombre, devuelve datos de la columna
                            ' con el nombre declarado (variable tel)
                            ide = CInt(col.Item(0))
                            nom = CStr(col.GetValue(1))
                            tel = CStr(col("Teléfono"))
                            ' Mostrar los datos en pantalla formateando HTML
                            Me.lbMostrar.Text += "<table align=center cellspacing=1>" & _
                        "<tr><td width=40 bgcolor=Gainsboro><font face=Verdana size=2>" & ide.ToString & _
                        "</font></td><td width=260 bgcolor=Gainsboro>" & _
                        "<font face=Verdana size=2>" & nom & _
                        "</font></td><td width=100 align=center bgcolor=Gainsboro>" & _
                        "<font face=Verdana size=2>" & _
                         tel & "</font></td></tr></table>"
                        End While
                        Me.lbMostrar.Text += "<br>"
                        ' el DataReader debe ser cerrado explícitamente al terminar de leer
                        col.Close()
                        ' comando para contar los registros
                        com.CommandText = "SELECT COUNT(*) FROM Prueba1;"
                        i = com.ExecuteScalar
                        Me.lbMostrar2.Text += "Registros mostrados: <b><font color=blue>" & i & "</font></b><br><br>"
                    End If
                    '
                    If a4 = "btBuscar1" Or a4 = "btBuscar2" Then
                        '
                        If a4 = "btBuscar1" Then
                            a1 = CType(txSel1, TextBox).Text
                            ' texto del comando con la instrucción SQL
                            com.CommandText = "SELECT * FROM Prueba1 WHERE Nombre LIKE '" & a1 & "%';"
                            col = com.ExecuteReader()
                            'Me.lbMostrar.Text = "<b><font size=+1>REGISTROS ORDENADOS POR NOMBRE</font></b><br><br>"
                            Me.lbMostrar.Text = ""
                            Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>SELECT * FROM Prueba1 <br>" & _
                            "WHERE Nombre LIKE '" & a1 & "%';</font></b><br>"
                            Me.lbMostrar.Text += "<table align=center cellspacing=1>" & _
                            "<tr><td width=40 bgcolor=lavender><b><font face=Verdana size=2>" & _
                            col.GetName(0).ToUpper() & _
                            "</font></b></td><td width=260 align=center bgcolor=lavender>" & _
                            "<b><font face=Verdana size=2>" & col.GetName(1).ToUpper() & _
                            "</b></font></td><td width=100 align=center bgcolor=lavender>" & _
                            "<b><font face=Verdana size=2>" & _
                            col.GetName(2).ToUpper() & "</font></b></td></tr></table><hr color=blue width=400>"
                            ' recorrer el DataReader hacia adelante
                            While (col.Read)
                                ide = CInt(col.Item(0))
                                nom = CStr(col.GetValue(1))
                                tel = CStr(col("Teléfono"))
                                ' Mostrar los datos en pantalla formateando HTML
                                Me.lbMostrar.Text += "<table align=center cellspacing=1>" & _
                            "<tr><td width=40 bgcolor=Gainsboro><font face=Verdana size=2>" & ide.ToString & _
                            "</font></td><td width=260 bgcolor=Gainsboro>" & _
                            "<font face=Verdana size=2>" & nom & _
                            "</font></td><td width=100 align=center bgcolor=Gainsboro>" & _
                            "<font face=Verdana size=2>" & _
                             tel & "</font></td></tr></table>"
                            End While
                            ' el DataReader debe ser cerrado explícitamente al terminar de leer
                            col.Close()
                            ' comando para contar los registros
                            com.CommandText = "SELECT COUNT(*) FROM Prueba1 WHERE Nombre LIKE '" & a1 & "%';"
                            i = com.ExecuteScalar
                            Me.lbMostrar2.Text += "Registros mostrados: <b><font color=blue>" & i & "</font></b><br><br>"
                            'Me.txSel1.Text = ""
                            '
                        ElseIf a4 = "btBuscar2" Then
                            a1 = CType(txSel2, TextBox).Text
                            ' texto del comando con la instrucción SQL
                            com.CommandText = "SELECT * FROM Prueba1 WHERE Nombre LIKE '%" & a1 & "%';"
                            col = com.ExecuteReader()
                            'Me.lbMostrar.Text = "<b><font size=+1>REGISTROS ORDENADOS POR NOMBRE</font></b><br><br>"
                            Me.lbMostrar.Text = ""
                            Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>SELECT * FROM Prueba1 <br>" & _
                            "WHERE Nombre LIKE '%" & a1 & "%';</font></b><br>"
                            Me.lbMostrar.Text += "<table align=center cellspacing=1>" & _
                            "<tr><td width=40 bgcolor=lavender><b><font face=Verdana size=2>" & _
                            col.GetName(0).ToUpper() & _
                            "</font></b></td><td width=260 align=center bgcolor=lavender>" & _
                            "<b><font face=Verdana size=2>" & col.GetName(1).ToUpper() & _
                            "</b></font></td><td width=100 align=center bgcolor=lavender>" & _
                            "<b><font face=Verdana size=2>" & _
                            col.GetName(2).ToUpper() & "</font></b></td></tr></table><hr color=blue width=400>"
                            ' recorrer el DataReader hacia adelante
                            While (col.Read)
                                ide = CInt(col.Item(0))
                                nom = CStr(col.GetValue(1))
                                tel = CStr(col("Teléfono"))
                                ' Mostrar los datos en pantalla formateando HTML
                                Me.lbMostrar.Text += "<table align=center cellspacing=1>" & _
                            "<tr><td width=40 bgcolor=Gainsboro><font face=Verdana size=2>" & ide.ToString & _
                            "</font></td><td width=260 bgcolor=Gainsboro>" & _
                            "<font face=Verdana size=2>" & nom & _
                            "</font></td><td width=100 align=center bgcolor=Gainsboro>" & _
                            "<font face=Verdana size=2>" & _
                             tel & "</font></td></tr></table>"
                            End While
                            ' el DataReader debe ser cerrado explícitamente al terminar de leer
                            col.Close()
                            ' comando para contar los registros
                            com.CommandText = "SELECT COUNT(*) FROM Prueba1 WHERE Nombre LIKE '%" & a1 & "%';"
                            i = com.ExecuteScalar
                            Me.lbMostrar2.Text += "Registros mostrados: <b><font color=blue>" & i & "</font></b><br><br>"
                            'Me.txSel2.Text = ""
                        End If
                        '
                        Me.lbMostrar.Text += "<br>"
                    End If
                    ' -----------------------
                    ' botón UPDATE 
                Case "Update"
                    com.CommandText = "UPDATE Prueba1 SET " & _
                "Nombre='Paragon Health Network Inc.', Teléfono='977589658' " & _
                "WHERE Nombre='J.P. Morgan and Co. Inc.';"
                    i = com.ExecuteNonQuery()
                    'Me.lbMostrar.Text = "<b><font size=+1>MODIFICAR UN REGISTRO</font></b><br><br>"
                    Me.lbMostrar.Text = ""
                    Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>UPDATE Prueba1<br>" & _
                    "SET Nombre='Paragon Health Network Inc.', Teléfono='977589658' <br>" & _
                    "WHERE Nombre='J.P. Morgan and Co. Inc.';</font></b><br>"
                    Me.lbMostrar2.Text += "Registros modificados: <b><font color=blue>" & i & "</font></b><br>"
                    com.CommandText = "SELECT COUNT(*) FROM Prueba1;"
                    i = com.ExecuteScalar
                    Me.lbMostrar2.Text += "Registros totales: <b><font color=blue>" & i & "</font></b><br>"
                    ' -----------------------
                    ' botón DELETE 
                Case "Delete"
                    a4 = CType(sender, Button).ID
                    ' según el ID del botón
                    If a4 = "btDelete" Then
                        com.CommandText = "DELETE FROM Prueba1 WHERE Nombre='Eastman Kodak Co.';"
                        i = com.ExecuteNonQuery()
                        'Me.lbMostrar.Text = "<b><font size=+1>ELIMINAR UN REGISTRO</font></b><br><br>"
                        Me.lbMostrar.Text = ""
                        Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>DELETE FROM Prueba1<br>" & _
                        "WHERE Nombre='Eastman Kodak Co.';</font></b><br>"
                        Me.lbMostrar2.Text += "Registros borrados: <b><font color=blue>" & i & "</font></b><br>"
                        com.CommandText = "SELECT COUNT(*) FROM Prueba1;"
                        i = com.ExecuteScalar
                        Me.lbMostrar2.Text += "Registros totales: <b><font color=blue>" & i & "</font></b><br>"
                    ElseIf a4 = "btDelete2" Then
                        a3 = CType(txId, TextBox).Text
                        com.CommandText = "DELETE FROM Prueba1 WHERE Id=" & a3 & ";"
                        i = com.ExecuteNonQuery()
                        'Me.lbMostrar.Text = "<b><font size=+1>ELIMINAR UN REGISTRO</font></b><br><br>"
                        Me.lbMostrar.Text = ""
                        Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>DELETE FROM Prueba1 " & _
                        "WHERE Id=" & a3 & ";</font></b><br>"
                        Me.lbMostrar2.Text += "Registros borrados: <b><font color=blue>" & i & "</font></b><br>"
                        com.CommandText = "SELECT COUNT(*) FROM Prueba1;"
                        i = com.ExecuteScalar
                        Me.lbMostrar2.Text += "Registros totales: <b><font color=blue>" & i & "</font></b><br>"
                        'Me.txId.Text = ""
                    End If
                    ' ----------------------
                    ' botón COPIAR 
                Case "Copiar"
                    com.CommandText = "INSERT INTO Prueba1 SELECT Nombre, Teléfono FROM Prueba2;"
                    i = com.ExecuteNonQuery()
                    'Me.lbMostrar.Text = "<b><font size=+1>COPIAR REGISTROS NUEVOS</font></b><br><br>"
                    Me.lbMostrar.Text = ""
                    Me.lbMostrar2.Text = "Instrucción SQL: <b><font color=blue>INSERT INTO Prueba1<br>SELECT Nombre, Teléfono FROM Prueba2;" & _
                    "</font></b><br>"
                    Me.lbMostrar2.Text += "Registros copiados: <b><font color=blue>" & i & "</font></b><br>"
                    com.CommandText = "SELECT COUNT(*) FROM Prueba1;"
                    i = com.ExecuteScalar
                    Me.lbMostrar2.Text += "Registros totales: <b><font color=blue>" & i & "</font></b><br>"
            End Select
            ' Cerrar la conexión
            con.Close()
        Catch pollo As Exception
            'Me.lbMostrar3.Text = ejercicio
            Me.lbMostrar.Text = ""
            Me.lbMostrar2.Text = "<b><font color=red>ERROR: " & pollo.Message & "</font></b><br>"
            ' Vaciar las cajas de texto
            Me.txNom.Text = ""
            Me.txTel.Text = ""
            Me.txId.Text = ""
            Me.txSel1.Text = ""
            Me.txSel2.Text = ""
        End Try
    End Sub

#End Region

End Class