Você está na página 1de 29

Recordset

Es una estructura de datos usada en programacin cuya


utilidad es la de almacenar informacin desde una tabla
de una base de datos. Se usa con frecuencia para obtener
conexiones con bases de datos y almacenar el resultado
de las posibles consultas que se realicen.
Se utiliza en mltiples lenguajes de programacin como
Visual Basic C++.

BOF

y EOF

OF: End Of FILE. indica cuando llegas al registro final y ya no


hay mas que leer. se activa cuando quieres seguir hacia
adelante
y
no
hay
mas
que
leer.
BOF: Begin Of File, Indica el PRINCIPIO de los registros. se
activa cuando quieres seguir hacia atrs y no hay ms
registros antes del primero

Para

armar el ejemplo se necesitan los siguientes


controles:

Un

contol PictureBox : Picture1


Un control CommonDialog : CommonDialog1
7 Controles CommandButton: Command1(0): " Nuevo ",
Command1(1): " Eliminar ". Command1(2): " Actualizar ".
Command1(3): " Editar ". Command1(4): " Cancelar ".
Command1(5): " Seleccionar Imagen ", y Command1(6) "
Eliminar Imagen "
Cuatro Command llamados CmdNav. CmdNav(0): " Primer
registro ". CmdNav(1): " Anterior registro ". CmdNav(2): "
Siguiente registro ". CmdNav(3): " Ultimo registro ".
3 TextBox llamados txt_Field(0), txt_Field(1) y txt_Field(2)

Dim cn As Connection
Dim rst As Recordset
Private Sub Form_Unload(Cancel As Integer)
On Error Resume Next
If Not rst Is Nothing Then
If rst.State = adStateOpen Then rst.Close
Set rst = Nothing
End If
If Not cn Is Nothing Then
If cn.State = adStateOpen Then cn.Close
Set cn = Nothing
End If
End Sub

Desconectar

Private Sub Form_Load()


Dim Pathbd As String, cadena As String
Dim T As TextBox
Set cn = New Connection
Pathbd = App.Path & "\db1.mdb"
cadena = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Pathbd & _
";Persist Security Info=False"

cn.Open cadena
Set rst = New Recordset
rst.Open "Select * FROM Contacto", cn, adOpenStatic, adLockOptimistic

Load Cadena de Conexin con


Imagen

' Nombre del campo que tiene el ID de imagen


Field_Img = "ID_Imagen"
' Path de la carpeta donde estn las imagenes
Carpeta_IMG = App.Path & "\img\"
' Si no existe la carpeta para guardar las imagen la crea
If Dir(App.Path & "\img", vbDirectory) = "" Then
MkDir App.Path & "\img"
End If

Load con imagen

If

rst.RecordCount > 0 Then


Call cmdNormal
Else
Call cmdSinRegistros
End If

Set txt_Field(0).DataSource = rst


Set txt_Field(1).DataSource = rst
Set txt_Field(2).DataSource = rst

txt_Field(0).DataField = "Nombre"
txt_Field(1).DataField = "Apellido"
txt_Field(2).DataField = "Email"

'Opcional: esto visualiza el Id del registro en un label


Set lblID.DataSource = rst
lblID.DataField = "Id"

Call Setear_TextBox

' carga la imagen en el registro si es que tiene


Call Mostrar_Imagen

End

Sub

Fin Load

App.path,Devuelve

una cadena con


esta la aplicacin (o sea dentro de
proyecto)
MkDir, para crear un directorio.
Datasource,

la
la

ruta donde
carpeta del

sirve para obtiener o establecer el


origen que contiene una lista de valores que se
utilizan para rellenar los elementos del control.
DataField, Devuelve o establece el nombre de un
campo al que estar enlazado un consumidor de
datos.
For Each...Next, Repite un grupo de instrucciones
para cada elemento de la coleccin.

Terminologas

Rst,AddNew,

Utilizado para crear y aadir un


nuevo registro en el objeto de conjunto de
registros designado por registros. Este mtodo
establece los campos con los valores por
defecto, y si no se especifican valores por
defecto, establece los campos en NULL
Rst.Update,
para
guardar
los
cambios
realizados en el registro actual de un objeto de
conjunto de registros ya llamando a la
AadirNuevo mtodo o desde el cambio de
cualquier valor de campo en un registro
existente.

Terminologas

' Habilita y deshabilita los CommandButton

Private Sub Setear_botones()

Dim i As Integer

For i = 0 To Command1.Count - 1
Command1(i).Enabled = Not Command1(i).Enabled
Next

For i = 0 To cmdNav.Count - 1
cmdNav(i).Enabled = Not cmdNav(i).Enabled
Next
End Sub

Funciones
Creadas

Private Sub Setear_TextBox()


'Bloquea y desbloquea los textbox
Dim T As TextBox
For Each T In Me.txt_Field
T.Locked = Not T.Locked
Next
End Sub

Funciones
Creadas

Private Sub Mostrar_Imagen()


With rst
' Si no hay ningn registro activo sale
If .EOF Or .BOF Then
Exit Sub
End If

' Si el registro no tiene una imagen asociada Limpia el


Picture
If .Fields(Field_Img) = "" Or .Fields(Field_Img) = 0 Then
Picture1.Cls
Else
' Lee el archivo de imagen y lo dibuja en el Picture
Call Dibujar_Imagen(Picture1, Carpeta_IMG &
.Fields(Field_Img))
End If
'Me.Caption = "Registro N: " & CStr(.AbsolutePosition)
End With
End Sub

Sub cmdNormal()
DeshabilitarTodosCmd

Command1(0).Enabled =
True

Command1(1).Enabled =
True

Command1(3).Enabled =
True

End Sub
Sub cmdSinRegistros()

DeshabilitarTodosCmd

Command1(0).Enabled =
True

End Sub

Sub cmdEditar()
DeshabilitarTodosCmd
Command1(2).Enabled
True
Command1(4).Enabled
True
Command1(5).Enabled
True
Command1(6).Enabled
True

End Sub

=
=
=
=

Sub CmdNuevo()
DeshabilitarTodosCmd
Command1(2).Enabled = True
Command1(4).Enabled = True
Command1(5).Enabled = True
Command1(6).Enabled = True
End Sub
Sub DeshabilitarTodosCmd()
Command1(0).Enabled = False
Command1(1).Enabled = False
Command1(2).Enabled = False
Command1(3).Enabled = False
Command1(4).Enabled = False
Command1(5).Enabled = False
Command1(6).Enabled = False
End Sub

' Botonos de los button Nav : Primer registro,


siguiente, etc...
Private Sub cmdNav_Click(Index As Integer)
' Si hay registro activo sale
If rst.BOF And rst.EOF Then Exit Sub
Select Case Index
Case 0
rst.MoveFirst
Case 1
rst.MovePrevious
If rst.BOF Then rst.MoveFirst
Case 2
rst.MoveNext
If rst.EOF Then rst.MoveLast
Case 3
rst.MoveLast
End Select
' Carga la imagen en el Picture
Mostrar_Imagen
End Sub

Private Sub Command1_Click(Index As Integer)


Select Case Index
'Agrega un nuevo registro
Case 0
rst.AddNew
Picture1.Cls
'Elimina el registro activo

button

CmdNuevo Funcin que habilita los

Matriz de Comandos

Case 1 Botn Eliminar


If rst.EOF Or rst.BOF Then Exit Sub
If MsgBox("Eliminar Registro", vbQuestion + vbYesNo) =
vbNo Then Exit Sub

CASE 1

Picture1.Cls
'Elimina el archivo de la carpeta de imagenes
If rst(Field_Img) <> "" Then
Call Kill(Carpeta_IMG & rst(Field_Img))
End If
rst.Delete
If rst.RecordCount > 0 Then
cmdNormal
Else
cmdSinRegistros
End If

If rst.EOF Or rst.BOF Then


Exit Sub
End If
rst.MoveNext
If rst.EOF Then
On Error Resume Next
rst.MoveLast
End If
'Carga la imagen del registro activo
Mostrar_Imagen
Exit Sub

CASE 1 Botn Eliminar

CASE 2
' Botn Actualizar los cambios en la base de
datos
Case 2
If Not rst.EOF And Not rst.BOF Then
rst.Update
Guardar_Imagen
cmdNormal Funcin que habilita
los botones
End If

' Cancela la actualizacin o edicin del


registro que se editando o aadiendo
Case 3
cmdEditar
Setear_TextBox
Exit Sub

CASE 3

'Botn Editar el registro activo


Case 4
If rst.EOF And rst.BOF Then Exit Sub
rst.CancelUpdate

CASE 4

If Not rst.BOF And Not rst.EOF Then


If rst(Field_Img) <> "" Then
Call Dibujar_Imagen(Picture1, Carpeta_IMG & rst(Field_Img))
End If
End If
If rst.RecordCount > 0 Then
cmdNormal
Else
cmdSinRegistros Funcin que Limpia los botones
End If

Case 5

Case 5

With CommonDialog1
.DialogTitle = " Seleccionar imagen"
.Filter = "BMP|*.bmp|JPEG|*.jpeg|GIF|*.gif|JPG|*.jpg|Todos|*.*"
.ShowOpen
If .FileName = "" Then
Exit Sub
Else
' Graba el nombre en el campo, el id de imagen _
que es el mismo que el campo Id
rst(Field_Img) = rst!id '

' se dibuja la imagen en el Picture


Call Dibujar_Imagen(Picture1, .FileName)
End If
End With
Exit Sub

Case 6
' Limpia la imagen del Picture y Elimina el id de _
imagen del registro actual de la base

Case 6

If MsgBox("Desea eliminar la imagen ?", vbYesNo + vbQuestion) =


vbYes Then
Picture1.Cls
rst(Field_Img) = ""
Exit Sub
End If
End Select

Setear_TextBox
' Muestra la imagen
Mostrar_Imagen
End Sub

Para

agregar
el modulo de
construir la
imagen
nuevamente.
Este
cdigo
se
lo
utilizar para
el manejo de
imgenes.

Clic en
PROYECTO
/Agregar Modulo

Escoger

existente.
Buscar la ruta
donde lo
tengamos
guardado o
descargado.
Clic en abrir

Y automaticamente se incluira en
nuestro proyecto

Base

de datos.

Archivo
Guardar y
publicar como
base de datos
2000, mdb

Crear

mediante comando Sql Create Table

Você também pode gostar