sábado, 14 de septiembre de 2013

Visual Basic 6.0 y base de datos Access

Muy Buenas a todos y todas!!!

Seguimos trabajando en Visual Basic 6.0 y ahora le toca el turno a las bases de datos.
Para ello he utilizado las bases de datos Access, el complemento ADODB, un DataGrid, un Common Dialog Control y un PictureBox; Todos ellos los están en el apartado "Complementos".

El ejemplo es sencillo con unos pocos campos para el nombre, Apellidos y el nombre de la imagen que aparerá en un PictureBox.

La imagen se puede seleccionar en cualquier carpeta y al guardar el registro se copiara automáticamente a la carpeta \picture del path principal en el que tenemos copiada la carpeta principal del programa.

Para que la opción de copiar funcione correctamente, hay que seleccionar en el apartado /Proyecto/Referencias la referencia a "Microsoft Scripting Runtime". Con eso funcionara perfectamente. (En el ejemplo para descargar la referencia ya esta activada)


Proyectos\Referencias

Referencia Microsoft Scripting Runtime

Espero que este ejemplo le sirva a alguien para algún proyecto además siempre se puede mejorar ;-)



VERSION 5.00

Begin VB.Form Form1 
   BorderStyle     =   1  'Fixed Single
   Caption         =   "Base de datos Access con DataGrid "
   ClientHeight    =   5085
   ClientLeft      =   45
   ClientTop       =   375
   ClientWidth     =   8490
   LinkTopic       =   "Form1"
   MaxButton       =   0   'False
   MinButton       =   0   'False
   ScaleHeight     =   5085
   ScaleWidth      =   8490
   StartUpPosition =   3  'Windows Default
   Begin MSComDlg.CommonDialog CDialog 
      Left            =   8400
      Top             =   2760
      _ExtentX        =   847
      _ExtentY        =   847
      _Version        =   393216
   End
   Begin MSAdodcLib.Adodc Adodc1 
      Height          =   495
      Left            =   8520
      Top             =   2520
      Width           =   1200
      _ExtentX        =   2117
      _ExtentY        =   873
      ConnectMode     =   0
      CursorLocation  =   3
      IsolationLevel  =   -1
      ConnectionTimeout=   15
      CommandTimeout  =   30
      CursorType      =   3
      LockType        =   3
      CommandType     =   8
      CursorOptions   =   0
      CacheSize       =   50
      MaxRecords      =   0
      BOFAction       =   0
      EOFAction       =   0
      ConnectStringType=   1
      Appearance      =   1
      BackColor       =   -2147483643
      ForeColor       =   -2147483640
      Orientation     =   0
      Enabled         =   -1
      Connect         =   ""
      OLEDBString     =   ""
      OLEDBFile       =   ""
      DataSourceName  =   ""
      OtherAttributes =   ""
      UserName        =   ""
      Password        =   ""
      RecordSource    =   ""
      Caption         =   "Adodc1"
      BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
         Name            =   "MS Sans Serif"
         Size            =   8.25
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      _Version        =   393216
   End
   Begin VB.CommandButton cmdDelete 
      Caption         =   "&Eliminar"
      Height          =   300
      Left            =   2880
      TabIndex        =   12
      Top             =   2880
      Width           =   975
   End
   Begin VB.CommandButton cmdGuardar 
      Caption         =   "&Guardar"
      Height          =   300
      Left            =   1560
      TabIndex        =   11
      Top             =   2880
      Width           =   975
   End
   Begin VB.CommandButton cmdClose 
      Caption         =   "&Cerrar"
      Height          =   300
      Left            =   4200
      TabIndex        =   10
      Top             =   2880
      Width           =   975
   End
   Begin VB.CommandButton Cmdnuevo 
      Caption         =   "&Nuevo"
      Height          =   300
      Left            =   240
      TabIndex        =   9
      Top             =   2880
      Width           =   975
   End
   Begin VB.CommandButton Cmdcargar 
      Caption         =   "&Cargar imagen"
      Height          =   300
      Left            =   6240
      TabIndex        =   8
      Top             =   2880
      Width           =   1215
   End
   Begin VB.PictureBox Picture1 
      Appearance      =   0  'Flat
      BackColor       =   &H80000005&
      ForeColor       =   &H80000008&
      Height          =   2535
      Left            =   5280
      ScaleHeight     =   2505
      ScaleWidth      =   2985
      TabIndex        =   7
      Top             =   240
      Width           =   3015
   End
   Begin VB.TextBox Text1 
      BeginProperty Font 
         Name            =   "MS Sans Serif"
         Size            =   9.75
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Height          =   375
      Index           =   2
      Left            =   2040
      TabIndex        =   6
      Top             =   2160
      Width           =   3015
   End
   Begin VB.TextBox Text1 
      BeginProperty Font 
         Name            =   "MS Sans Serif"
         Size            =   9.75
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Height          =   375
      Index           =   1
      Left            =   2040
      TabIndex        =   5
      Top             =   1320
      Width           =   3015
   End
   Begin VB.TextBox Text1 
      BeginProperty Font 
         Name            =   "MS Sans Serif"
         Size            =   9.75
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Height          =   375
      Index           =   0
      Left            =   2040
      TabIndex        =   4
      Top             =   360
      Width           =   3015
   End
   Begin MSDataGridLib.DataGrid DataGrid1 
      Height          =   1455
      Left            =   360
      TabIndex        =   0
      Top             =   3480
      Width           =   7935
      _ExtentX        =   13996
      _ExtentY        =   2566
      _Version        =   393216
      HeadLines       =   1
      RowHeight       =   15
      BeginProperty HeadFont {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
         Name            =   "MS Sans Serif"
         Size            =   8.25
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
         Name            =   "MS Sans Serif"
         Size            =   8.25
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      ColumnCount     =   2
      BeginProperty Column00 
         DataField       =   ""
         Caption         =   ""
         BeginProperty DataFormat {6D835690-900B-11D0-9484-00A0C91110ED} 
            Type            =   0
            Format          =   ""
            HaveTrueFalseNull=   0
            FirstDayOfWeek  =   0
            FirstWeekOfYear =   0
            LCID            =   3082
            SubFormatType   =   0
         EndProperty
      EndProperty
      BeginProperty Column01 
         DataField       =   ""
         Caption         =   ""
         BeginProperty DataFormat {6D835690-900B-11D0-9484-00A0C91110ED} 
            Type            =   0
            Format          =   ""
            HaveTrueFalseNull=   0
            FirstDayOfWeek  =   0
            FirstWeekOfYear =   0
            LCID            =   3082
            SubFormatType   =   0
         EndProperty
      EndProperty
      SplitCount      =   1
      BeginProperty Split0 
         BeginProperty Column00 
         EndProperty
         BeginProperty Column01 
         EndProperty
      EndProperty
   End
   Begin VB.Label Label1 
      Caption         =   "Nombre Foto:"
      BeginProperty Font 
         Name            =   "MS Sans Serif"
         Size            =   12
         Charset         =   0
         Weight          =   700
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Height          =   375
      Index           =   2
      Left            =   240
      TabIndex        =   3
      Top             =   2160
      Width           =   1815
   End
   Begin VB.Label Label1 
      Caption         =   "Apellidos:"
      BeginProperty Font 
         Name            =   "MS Sans Serif"
         Size            =   12
         Charset         =   0
         Weight          =   700
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Height          =   375
      Index           =   1
      Left            =   720
      TabIndex        =   2
      Top             =   1320
      Width           =   1215
   End
   Begin VB.Label Label1 
      Caption         =   "Nombre:"
      BeginProperty Font 
         Name            =   "MS Sans Serif"
         Size            =   12
         Charset         =   0
         Weight          =   700
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Height          =   375
      Index           =   0
      Left            =   960
      TabIndex        =   1
      Top             =   360
      Width           =   1095
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Dim A As New Scripting.FileSystemObject
Dim Cn As New ADODB.Connection
Dim Rs As New ADODB.Recordset
Dim X As String
Dim Cuenta As Integer

Private Sub cmdClose_Click()
End
End Sub

                                '----BOTON GUARDAR----
Private Sub cmdGuardar_Click()

If Text1(0).Text = "" Or Text1(1).Text = "" Or Text1(2).Text = "" Then
MsgBox "Por favor Rellene todos los campos"
Call clear
Else
Call Asignar_Datos
Rs.Update
Call Visualizar_Datos
Cmdnuevo.Enabled = True
cmdDelete.Enabled = True
End If
A.CopyFile CDialog.FileName, App.Path & "\picture\" & CDialog.FileTitle
Call Carga_Imagenes
End Sub
                                '----BOTON PARA CARGAR IMAGENES-----
Private Sub Cmdcargar_Click()

CDialog.ShowOpen
Picture1.Picture = LoadPicture(CDialog.FileName)
Text1(2).Text = CDialog.FileTitle
If Text1(2).Text = "" Then
    MsgBox "seleccione una imagen"
Else
    Text1(2).Text = CDialog.FileTitle
End If
End Sub

                                '-----BOTON ELIMINAR-----
Private Sub cmdDelete_Click()
On Error Resume Next
If Rs.RecordCount = 1 Then
MsgBox "No se puede eliminar el último registro, Por favor modifiquelo y pulse Guardar"
Else
 With DataGrid1
        If MsgBox("Se va a eliminar el registro : ¿Está seguro? ", _
                    vbExclamation + vbYesNo, "Eliminar") = vbYes Then
            
            
            Rs.Delete
                        
            ' Actualiza el recordset
            Rs.Update
            DataGrid1.Refresh
        End If
    End With
             ' muestra los datos en los textbox
    Call Visualizar_Datos
    Call Carga_Imagenes
   
        
        ' si elrecordset llegó al final se posiciona en el último
        If Rs.EOF Then
             Rs.MoveFirst
                Call Visualizar_Datos
                Call Carga_Imagenes
            'MsgBox "  Ultimo registro ", vbInformation
       End If
        
If Text1(2).Text = "" Then
Text1(2).Text = "Nopicture.jpg"
Call Carga_Imagenes
End If
End If
If Err Then
MsgBox "No se puede borrar registro"
End If
End Sub
                                '-----BOTON NUEVO-----
Private Sub Cmdnuevo_Click()
Call clear
Cmdnuevo.Enabled = False
cmdDelete.Enabled = False
Rs.AddNew
Text1(2).Text = "Nopicture.jpg"
Call Carga_Imagenes
Text1(0).SetFocus


End Sub

Private Sub Form_Load()

Cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\bd1.mdb" & ";Persist Security Info=False"

Rs.Source = "Agenda"
Rs.CursorType = adOpenKeyset
Rs.LockType = adLockOptimistic
Rs.CursorLocation = adUseClient
Rs.Open "select * from Agenda", Cn, 3, 3  ' adOpenDynamic, adLockOptimistic


Dim Rs2 As New ADODB.Recordset
Set Rs2 = New ADODB.Recordset
Call Visualizar_Datos

If Text1(2).Text = "" Then
Text1(2).Text = "Nopicture.jpg"
End If
Call Carga_Imagenes

Call Cargar_data(DataGrid1)
With DataGrid1
        .AllowUpdate = False
        .Width = 7800
        .Columns(0).Width = 2300
        .Columns(1).Width = 3600
        .Columns(2).Width = 1560
End With
End Sub
Private Sub DataGrid1_HeadClick(ByVal ColIndex As Integer)
With Rs
If (.Sort = .Fields(ColIndex).[Name] & " Asc") Then
.Sort = .Fields(ColIndex).[Name] & " Desc"
Else
.Sort = .Fields(ColIndex).[Name] & " Asc"
End If
End With
End Sub

'Abre el formulario para Editar el registro seleccionado
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Sub Editar()

    Dim i As Integer
    
    If DataGrid1.Row = -1 Then Exit Sub
    Call Visualizar_Datos
    Call Carga_Imagenes
        DataGrid1.Refresh
        
End Sub

Private Sub datagrid1_DblClick()
    Call Editar
End Sub
' Sub que carga los datos del recordset y los asigna a los textbox
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Sub Visualizar_Datos()
 On Error Resume Next
  Text1(0).Text = Rs.Fields("Nombre")
  Text1(1).Text = Rs.Fields("Apellidos")
  If Text1(2).Text = "" Then Text1(2).Text = "nopicture.jpg"
  Text1(2).Text = Rs.Fields("imagen")
End Sub
' Sub que asigna los datos al recordset
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Sub Asignar_Datos()
If Rs.EOF Then
Rs.MoveLast
End If
  Rs.Fields("Nombre") = Text1(0).Text
  Rs.Fields("Apellidos") = Text1(1).Text
  Rs.Fields("imagen") = Text1(2).Text
End Sub

' Limpia las cajas de texto
Private Sub clear()
  Text1(0).Text = "Nombre"
  Text1(1).Text = "Apellidos"
  Text1(2).Text = "Nopicture.jpg"
End Sub
  
Private Sub Carga_Imagenes()
On Error Resume Next
X = App.Path
Picture1.Picture = LoadPicture(X & "\picture\" & Text1(2).Text)
If Err Then
MsgBox "Se ha producido un error al cargar la Imagen. Esta la imagen en la carpeta?"
If Text1(2).Text = "" Then
Text1(2).Text = "Nopicture.jpg"

End If
End If

End Sub

Private Sub Cargar_data(Dg As DataGrid)
  Dg.MarqueeStyle = dbgHighlightRow
    Set Dg.DataSource = Rs
    Dg.Refresh
End Sub


Otros artículos sobre Visual Basic 6.0 que te pueden interesar:

Nos vemos en el próximo artículo, saludos!!!

No hay comentarios :

Publicar un comentario