Sie sind auf Seite 1von 28

APLICACION WINDOWS FORM EN N-CAPAS UTILIZANDO VB.

NET Y SQL SERVER CON


PROCEDIMIENTOS ALMACENADOS
TUTORIAL DE LA APLICACIÓN
1. Base de Datos
1.1 Creando la Tabla Empleado

1
2 CREATE TABLE [Empleado](
3 [CodEmpleado] [char](10) NOT NULL,
4 [Nombres] [varchar](100) NULL,
5 [ApePaterno] [varchar](50) NULL,
[ApeMaterno] [varchar](50) NULL,
6 [FecNacimiento] [date] NULL,
7 [CodSexo] [char](3) NULL,
8 [Foto] [image] NULL,
9 [CodEstado] [char](3) NULL,
[Terminal] [varchar](15) NULL,
10 [FechaRegi] [date] NULL,
11 [UsuarioRegi] [varchar](15) NULL,
12 [FechaModi] [date] NULL,
13 [UsuarioModi] [varchar](15) NULL,
14 CONSTRAINT [PK_Empleado] PRIMARY KEY CLUSTERED
(
15 [CodEmpleado] ASC
16)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
17ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
18) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
19

1.2 Procedimientos Almacenados para Generar Codigo, Insertar, Actualizar, Eliminar y Listar

--STORED PROCEDURE PARA GENERAR CODIGO DE EMPLEADO


1 CREATE PROCEDURE [dbo].[USP_Empleado_GenerarCodigo]
2 AS
3 BEGIN
4 select
5 'EMP' +
RIGHT('0000000'+CONVERT(VARCHAR(20),ISNULL(MAX(RIGHT(CodEmpleado,7)),0)+1),7)
6 from Empleado
7 END
8
9 GO
10
11 -- STORED PROCEDURE PARA INSERTAR
CREATE PROCEDURE [dbo].[USP_Empleado_Insertar]
12 (
13 @CodEmpleado char(10),
14 @Nombres varchar(100) = NULL,
15 @ApePaterno varchar(50) = NULL,
16 @ApeMaterno varchar(50) = NULL,
@FecNacimiento date = NULL,
17 @CodSexo char(3) = NULL,
18 @Foto image = NULL,
19 @CodEstado char(3) = NULL,
20 @Terminal varchar(15) = NULL,
@UsuarioRegi varchar(15) = NULL)
21
AS
22
23 BEGIN
24
25 INSERT
26 INTO [Empleado]
(
27 [CodEmpleado],
28 [Nombres],
29 [ApePaterno],
30 [ApeMaterno],
[FecNacimiento],
31 [CodSexo],
32 [Foto],
33 [CodEstado],
34 [Terminal],
35 [FechaRegi],
[UsuarioRegi]
36 )
37 VALUES
38 (
39 @CodEmpleado,
40 @Nombres,
@ApePaterno,
41 @ApeMaterno,
42 @FecNacimiento,
43 @CodSexo,
44 @Foto,
@CodEstado,
45 @Terminal,
46 GETDATE(),
47 @UsuarioRegi
48 )
49 END
50
GO
51
52 --STORED PROCEDURE PARA ACTUALIZAR
53 CREATE PROCEDURE [USP_Empleado_Actualizar]
54 (
55 @CodEmpleado char(10),
@Nombres varchar(100) = NULL,
56 @ApePaterno varchar(50) = NULL,
57 @ApeMaterno varchar(50) = NULL,
58 @FecNacimiento date = NULL,
59 @CodSexo char(3) = NULL,
60 @Foto image = NULL,
@CodEstado char(3) = NULL,
61 @Terminal varchar(15) = NULL,
62 @UsuarioModi varchar(15) = NULL)
63 AS
64
65 BEGIN
UPDATE [Empleado]
66
SET
67 [CodEmpleado] = @CodEmpleado,
68 [Nombres] = @Nombres,
69 [ApePaterno] = @ApePaterno,
70 [ApeMaterno] = @ApeMaterno,
[FecNacimiento] = @FecNacimiento,
71 [CodSexo] = @CodSexo,
72 [Foto] = @Foto,
73 [CodEstado] = @CodEstado,
74 [Terminal] = @Terminal,
75 [FechaModi] = GETDATE(),
[UsuarioModi] = @UsuarioModi
76 WHERE
77 [CodEmpleado] = @CodEmpleado
78
79 END
80
81 GO
82
83 --STORED PROCEDURE PARA ELIMINAR
CREATE PROCEDURE [USP_Empleado_Eliminar]
84 (
85 @CodEmpleado char(10)
86 )
87 AS
88
BEGIN
89
90 DELETE FROM Empleado
91 WHERE [CodEmpleado] = @CodEmpleado
92
93 END
94
95 GO
96
97 --PROCEDURE PARA LISTAR REGISTROS POR CRITERIO DE BUSQUEDA
CREATE PROCEDURE [dbo].[USP_Empleado_Listar]
98 @Criterio varchar(150)
99 AS
100begin
101select Empleado=ApePaterno+' '+ApeMaterno+' '+Nombres,* from Empleado
102where (ApePaterno+''+ApeMaterno+''+Nombres) like '%'+@Criterio+'%'
end
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
2. Visual Studio 2008
2.1 Creando una solución en blanco

2.2 Añadiendo la Capa de Entidades


Una tabla es una entidad que en nuestro caso sera la tabla "Empleado". Esta entidad es la que
recorrerá las distintas capas llevando o trayendo información.
Pasos:

 Click derecho en la solución("Tutorial_NCapas") creada previamente y elegir la opcion


agregar nuevo proyecto.
 Seleccionar Librería de Clases y nombrarla "BusinessEntities" para identificar que dentro
de ese proyecto estarán todas nuestras entidades.
2.2.1 Creando la Clase EmpleadoBE

Pasos:

 Click derecho en el proyecto "BusinessEntities" y agregar una nueva clase con el nombre
de "EmpleadoBE"
 Agregar el siguiente codigo dentro de la clase "EmpleadoBE"

1 Public Class EmpleadoBE


'Campos de la entidad
2 Private _CodEmpleado As String
3 Private _Nombres As String
4 Private _ApePaterno As String
5 Private _ApeMaterno As String
Private _FecNacimiento As Date
6 Private _CodSexo As String
7 Private _Foto As Byte()
8 Private _CodEstado As String
9 Private _Terminal As String
10 Private _FechaRegi As Date
Private _UsuarioRegi As String
11 Private _FechaModi As Date
12 Private _UsuarioModi As String
13
14 'Propiedades de la entidad
15 Public Property CodEmpleado() As String
Get
16 Return _CodEmpleado
17 End Get
18 Set(ByVal value As String)
19 _CodEmpleado = value
End Set
20 End Property
21
22 Public Property Nombres() As String
23 Get
24 Return _Nombres
End Get
25 Set(ByVal value As String)
26 _Nombres = value
27 End Set
28 End Property
29
30 Public Property ApePaterno() As String
Get
31 Return _ApePaterno
32 End Get
33 Set(ByVal value As String)
34 _ApePaterno = value
End Set
35 End Property
36
37 Public Property ApeMaterno() As String
38 Get
39 Return _ApeMaterno
40 End Get
Set(ByVal value As String)
41 _ApeMaterno = value
42 End Set
43 End Property
44
45 Public Property FecNacimiento() As Date
46 Get
Return _FecNacimiento
47 End Get
48 Set(ByVal value As Date)
49 _FecNacimiento = value
50 End Set
End Property
51
52 Public Property CodSexo() As String
53 Get
54 Return _CodSexo
55 End Get
56 Set(ByVal value As String)
_CodSexo = value
57 End Set
58 End Property
59
60 Public Property Foto() As Byte()
61 Get
Return _Foto
62 End Get
63 Set(ByVal value As Byte())
64 _Foto = value
65 End Set
66 End Property
67
Public Property CodEstado() As String
68 Get
69 Return _CodEstado
End Get
70 Set(ByVal value As String)
71 _CodEstado = value
72 End Set
73 End Property
74
Public Property Terminal() As String
75 Get
76 Return _Terminal
77 End Get
78 Set(ByVal value As String)
79 _Terminal = value
End Set
80 End Property
81
82 Public Property FechaRegi() As Date
83 Get
84 Return _FechaRegi
End Get
85 Set(ByVal value As Date)
86 _FechaRegi = value
87 End Set
88 End Property
89
90 Public Property UsuarioRegi() As String
Get
91 Return _UsuarioRegi
92 End Get
93 Set(ByVal value As String)
94 _UsuarioRegi = value
95 End Set
End Property
96
97 Public Property FechaModi() As Date
98 Get
99 Return _FechaModi
100 End Get
Set(ByVal value As Date)
101 _FechaModi = value
102 End Set
103 End Property
104
105 Public Property UsuarioModi() As String
106 Get
Return _UsuarioModi
107 End Get
108 Set(ByVal value As String)
109 _UsuarioModi = value
110 End Set
End Property
111End Class
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134

2.3 Añadiendo la Capa de Acceso a Datos


Es la encargada de acceder a los datos. Aqui se reciben las solicitudes de almacenamiento o
recuperación de información desde la capa de negocio
Pasos:

 Click derecho en la solución("Tutorial_NCapas") creada previamente y elegir la opcion


agregar nuevo proyecto.
 Seleccionar Biblioteca de Clases y nombrarla "DataAccess" para identificar que dentro de
ese proyecto estarán todas las clases que van interactuar con la base datos
 Click Derecho en el proyecto("DataAccess") y seleccionar "Agregar Referencia".
 Ubicar la pestaña "Proyectos" y seleccionar como referencia "BusinessEntities" para poder
heredar todas las clases creadas en la Capa de Entidades.
Agregar como Referencia la Capa de Entidades

2.3.1 Creando la Clase Conexion

Pasos:
 Crear una Clase llamada "Conexion" para agregar la cadena de conexion necesaria y poder
tener comunicación con la base de datos (SQL Server).
 La Clase Conexion.vb
 ?
1
2 Imports System.Data
Imports System.Data.SqlClient
3
4 Public Class Conexion
5 Public Function Conexion() As SqlConnection
6 'Cambiar la Base de Datos y el Password de acuerdo a su configuracion
7 Dim cadconex As String = "Server=.;DATABASE=xxx;User ID=sa;Password=xxx"
8 Dim cn As New SqlConnection(cadconex)
Return cn
9 End Function
10End Class
11

2.3.2 Creando la Clase EmpleadoDA

Pasos:

 Click derecho en el proyecto "DataAccess" y agregar una nueva clase con el nombre de
"EmpleadoDA"
 Agregar el siguiente codigo dentro de la clase "EmpleadoDA"

La Clase EmpleadoDA.vb
1 Imports BusinessEntities 'Importamos la capa de entidades, si tienen error es
porque no se agrego la referencia
2 Imports System.Data
3 Imports System.Data.SqlClient
4
5 Public Class EmpleadoDA
6 'Instanciamos el objeto _Conexion de la clase Conexion para obtener la cadena
7 de conexion a la BD
Dim _Conexion As New Conexion
8
9 'Funcion que me ve permitir generar el codigo del empleado
10 Private Function GenerarCorrelativo() As String
11 Dim cmd As New SqlCommand
12 Dim da As New SqlDataAdapter
Dim dt As New DataTable
13 cmd.Connection = _Conexion.Conexion
14 cmd.CommandText = "USP_Empleado_GenerarCodigo"
15 cmd.CommandType = CommandType.StoredProcedure
16 da.SelectCommand = cmd
17 da.Fill(dt)
Return dt.Rows(0).Item(0)
18 End Function
19
20 'Metodo para registrar un nuevo empleado
21 Private Sub Registrar(ByVal EmpleadoBE As EmpleadoBE, ByVal sqlCon As
22 SqlConnection, _
ByVal sqlTrans As SqlTransaction)
23
Try
24 Dim cmd As New SqlCommand
25 cmd.CommandText = "USP_Empleado_Insertar"
26 cmd.Connection = sqlCon
27 cmd.Transaction = sqlTrans
cmd.CommandType = CommandType.StoredProcedure
28
29 'Los parametros que va recibir son las propiedades de la clase
30 Empleado
31 cmd.Parameters.Add("@CodEmpleado", SqlDbType.Char).Value =
32 EmpleadoBE.CodEmpleado
cmd.Parameters.Add("@Nombres", SqlDbType.VarChar).Value =
33 EmpleadoBE.Nombres
34 cmd.Parameters.Add("@ApePaterno", SqlDbType.VarChar).Value =
35 EmpleadoBE.ApePaterno
36 cmd.Parameters.Add("@ApeMaterno", SqlDbType.VarChar).Value =
37 EmpleadoBE.ApeMaterno
cmd.Parameters.Add("@FecNacimiento", SqlDbType.Date).Value =
38 EmpleadoBE.FecNacimiento
39 cmd.Parameters.Add("@CodSexo", SqlDbType.Char).Value =
40 EmpleadoBE.CodSexo
41 cmd.Parameters.Add("@Foto", SqlDbType.Image).Value = EmpleadoBE.Foto
42
cmd.Parameters.Add("@CodEstado", SqlDbType.Char).Value =
43 EmpleadoBE.CodEstado
44 cmd.Parameters.Add("@Terminal", SqlDbType.VarChar).Value =
45 EmpleadoBE.Terminal
46 cmd.Parameters.Add("@UsuarioRegi", SqlDbType.VarChar).Value =
47 EmpleadoBE.UsuarioRegi
48
cmd.ExecuteNonQuery()
49 Catch ex As Exception
50 MsgBox(ex.ToString)
51 End Try
52
53 End Sub
54
55 'Metodo para Modificar un empleado
Private Sub Modificar(ByVal EmpleadoBE As EmpleadoBE, ByVal sqlCon As
56 SqlConnection, _
57 ByVal sqlTrans As SqlTransaction)
58 Try
59 Dim cmd As New SqlCommand
cmd.CommandText = "USP_Empleado_Actualizar"
60 cmd.Connection = sqlCon
61 cmd.Transaction = sqlTrans
62 cmd.CommandType = CommandType.StoredProcedure
63
64 cmd.Parameters.Add("@CodEmpleado", SqlDbType.Char).Value =
65 EmpleadoBE.CodEmpleado
cmd.Parameters.Add("@Nombres", SqlDbType.VarChar).Value =
66 EmpleadoBE.Nombres
67 cmd.Parameters.Add("@ApePaterno", SqlDbType.VarChar).Value =
68 EmpleadoBE.ApePaterno
69 cmd.Parameters.Add("@ApeMaterno", SqlDbType.VarChar).Value =
EmpleadoBE.ApeMaterno
70 cmd.Parameters.Add("@FecNacimiento", SqlDbType.Date).Value =
71 EmpleadoBE.FecNacimiento
72 cmd.Parameters.Add("@CodSexo", SqlDbType.Char).Value =
73 EmpleadoBE.CodSexo
74 cmd.Parameters.Add("@Foto", SqlDbType.Image).Value = EmpleadoBE.Foto
75
cmd.Parameters.Add("@CodEstado", SqlDbType.Char).Value =
76 EmpleadoBE.CodEstado
77 cmd.Parameters.Add("@Terminal", SqlDbType.VarChar).Value =
EmpleadoBE.Terminal
78 cmd.Parameters.Add("@UsuarioModi", SqlDbType.VarChar).Value =
79 EmpleadoBE.UsuarioModi
80
81 cmd.ExecuteNonQuery()
82 Catch ex As Exception
MsgBox(ex.ToString)
83 End Try
84
85 End Sub
86
87 'Metodo para Eliminar un empleado
88 Private Sub Eliminar(ByVal EmpleadoBE As EmpleadoBE, ByVal sqlCon As
89 SqlConnection, _
ByVal sqlTrans As SqlTransaction)
90 Try
91 Dim cmd As New SqlCommand
92 cmd.CommandText = "USP_Empleado_Eliminar"
93 cmd.Connection = sqlCon
cmd.Transaction = sqlTrans
94 cmd.CommandType = CommandType.StoredProcedure
95
96 cmd.Parameters.Add("@CodEmpleado", SqlDbType.Char).Value =
97 EmpleadoBE.CodEmpleado
98
99 cmd.ExecuteNonQuery()
10 Catch ex As Exception
MsgBox(ex.ToString)
0 End Try
10
1 End Sub
10
2 'Funcion Principal que hara toda la logica para grabar la data
10 Public Function GrabarEmpleado(ByVal EmpleadoBE As EmpleadoBE, ByVal flagAccion
3 As String) As Boolean
Dim resultado As Boolean = True
10 Dim cn As New SqlConnection
4 Dim sqlTrans As SqlTransaction
10 Dim correlativo As String
5
10 cn = _Conexion.Conexion
cn.Open()
6 sqlTrans = cn.BeginTransaction
10
7 Try
10 'N:Nuevo M:Modificar E:Eliminar
8
10 If flagAccion = "N" Then
9 correlativo = GenerarCorrelativo()
EmpleadoBE.CodEmpleado = correlativo
11 Registrar(EmpleadoBE, cn, sqlTrans)
0 End If
11
1 If flagAccion = "M" Then
11 Modificar(EmpleadoBE, cn, sqlTrans)
End If
2
11 If flagAccion = "E" Then
3 Eliminar(EmpleadoBE, cn, sqlTrans)
End If
11
4
11 sqlTrans.Commit()
5 resultado = True
11
6 Catch ex As SqlException
11 sqlTrans.Rollback()
resultado = False
7 Catch ex As Exception
11 sqlTrans.Rollback()
8 resultado = False
11 Finally
9 cn.Close()
sqlTrans = Nothing
12 End Try
0
12 Return resultado
1 End Function
12
2
12 'Funcion que me va permitir capturar la lista de registros en la tabla
empleado y que me va retornar
3 'un Datatable
12 Public Function ListarEmpleados(ByVal Criterio As String) As DataTable
4 Dim cmd As New SqlCommand
12 Dim da As New SqlDataAdapter
5 Dim dt As New DataTable
12
cmd.Connection = _Conexion.Conexion
6 cmd.CommandText = "USP_Empleado_Listar"
12 cmd.CommandType = CommandType.StoredProcedure
7
12 cmd.Parameters.Add("@Criterio", SqlDbType.VarChar).Value = Criterio
8 da.SelectCommand = cmd
12 da.Fill(dt)
Return dt
9 End Function
13 End Class
0
13
1
13
2
13
3
13
4
13
5
13
6
13
7
13
8
13
9
14
0
14
1
14
2
14
3
14
4
14
5
14
6
14
7
14
8
14
9
15
0
15
1
15
2
15
3
15
4
15
5
15
6
15
7
15
8
15
9
16
0
16
1
16
2
16
3

2.4 Añadiendo la Capa Lógica


En esta capa es donde residen los programas que se ejecutan, se reciben las peticiones del usuario y
se envían las respuestas tras el proceso.
Pasos:

 Click derecho en la solución("Tutorial_NCapas") creada previamente y elegir la opcion


agregar nuevo proyecto.
 Seleccionar Biblioteca de Clases y nombrarla "BusinessLogic" para identificar que dentro
de ese proyecto estará toda la logica del negocio
 Click Derecho en el proyecto("BusinessLogic") y seleccionar "Agregar Referencia".
 Ubicar la pestaña "Proyectos" y seleccionar como referencia "BusinessEntities" para poder
heredar todas las clases creadas en la Capa de Entidades y "DataAccess" para poder
heredar todas las clases creadas en la Capa de Acceso a Datos

Agregar como Referencia la Capa de Entidades y de Acceso a Datos


2.4.1 Creando la Clase EmpleadoBL
Pasos:

 Click derecho en el proyecto " " y agregar una nueva clase con el nombre de
"EmpleadoBL"
 Agregar el siguiente codigo dentro de la clase "EmpleadoBL"

La Clase EmpleadoBL.vb
?
1
2 Imports BusinessEntities 'Importamos la capa de entidades
3 Imports DataAccess 'Importamos la capa de acceso a datos
4 Public Class EmpleadoBL
5 'Instanciamos el objeto _EmpleadoDA de la Clase EmpleadoDA
6 Dim _EmpleadoDA As New EmpleadoDA
7
Public Function GrabarEmpleado(ByVal EmpleadoBE As EmpleadoBE, _
8 ByVal flagAccion As String) As Boolean
9 Return _EmpleadoDA.GrabarEmpleado(EmpleadoBE, flagAccion)
10 End Function
11
12 Public Function ListarEmpleados(ByVal Criterio As String) As DataTable
Return _EmpleadoDA.ListarEmpleados(Criterio)
13
End Function
14
15
2.5 Añadiendo la Capa de Presentación
Esta capa es la que contiene las interfaces en las que el usuario interactua con el sistema.
Pasos:

 Click derecho en la solución("Tutorial_NCapas") creada previamente y elegir la opcion


agregar nuevo proyecto.
 Seleccionar Windows Forms Application y nombrarla "Presentacion" para identificar que
dentro de ese proyecto estarán todos los formularios.
 Click Derecho en el proyecto("Presentacion") y seleccionar "Agregar Referencia".
 Ubicar la pestaña "Proyectos" y seleccionar como referencia "BusinessEntities" para poder
heredar todas las clases creadas en la Capa de Entidades y "Business Logic" para poder
heredar todas las clases creadas en la Capa Lógica

Agregar como Referencia la Capa de Entidades y la Capa Lógica


2.5.1 Creando el Formulario FrmTutorial
Pasos:

 Click derecho en el proyecto "Presentacion" y agregar una nuevo formulario con el


nombre de "FrmTutorial"
 SOLO configurar las propiedades indicadas en cada uno de los controles del
formulario(Ver Cuadro de Controles), lo que no se indica dejarlo tal como está.
Cuadro de Controles
DataGridView y
Botones TextFields ComboBox y DateTimePicker
PictureBox
Para el boton Para el Campo Para el Combo "Estado": Para el DataGridView:
"Nuevo": "Codigo":
 Name: cboEstado  Name:
 Name:  Name:  Enable: False dgvEmpleados
btnNuevo txtCodigo  DropDownStyle:  Selection Mode:
 Enable:  ReadOnly: DropDownList FullRowSelect
True True  Items:(Collection)>>
 Text: ACTIVO, ANULADO Para el PictureBox de
Nuevo Para el Campo la Foto:
"Apellido Paterno": Para el Combo "Sexo":
Para el boton  Name: pbFoto
"Modificar":  Name:  Name: cboSexo  BorderStyle:
txtApePaterno  Enable: False FixedSingle
 Name:  ReadOnly:  DropDownStyle:  SizeMode:
btnModific True DropDownList StretchImage
ar  Items:(Collection)>>
 Enable: Para el Campo MASCULINO,
True "Apellido Materno": FEMENINO
 Text:
Modificar  Name: Para el DateTimePicker "Fecha
txtApeMaterno Nacimiento":
Para el boton  ReadOnly:
"Eliminar": True  Name: dtpFecNac
 Enable: False
 Name: Para el Campo  Format: Short
btnEliminar "Nombres":
 Enable: Para el DateTimePicker "Fecha
True  Name: Reg":
 Text: txtNombres
Eliminar  ReadOnly:  Name:
True dtpFechaRegistro
Para el boton  Enable: False
"Grabar": Para el Campo  Format: Short
"Ingrese Nombres":
 Name: Para el DateTimePicker "Fecha
btnGrabar  Name: Modif":
 Enable: txtBusqueda
False  ReadOnly:  Name:
 Text: False dtpFechaModificacion
Grabar  Enable: False
Para el Campo  Format: Short
Para el boton "Registrado Por":
"Cancelar":
 Name:
 Name: txtUsuarioRegi
btnCancelar stra
 Enable:  Enable: False
False
 Text: Para el Campo
Cancelar "Modificado Por":

Para el boton  Name:


"Salir": txtUsuarioMod
ifica
 Name:  Enable: False
btnSalir
 Enable:
True
 Text: Salir

Para el boton "+"


(Agregar Foto):

 Name:
btnAgregar
Foto
 Enable:
False

Para el boton "x"


(Quitar Foto):

 Name:
btnQuitarFo
to
 Enable:
False

Ingresar el siguiente codigo dentro del Formulario FrmTutorial

1 'Importando la Capa de Entidades y la Capa Logica


2 Imports BusinessEntities
3 Imports BusinessLogic
'Importacion necesaria para trabajar con las imagenes
4 Imports System.IO
5
6 Public Class FrmTutorial
7
8 '************** DECLARACION DE VARIABLES GLOBALES ****************'
9 Dim _EmpleadoBL As New EmpleadoBL
Dim flagAccion As String = ""
10
11
'******************** METODOS *************************************'
12 Private Sub NueModEli()
13 btnNuevo.Enabled = False
14 btnModificar.Enabled = False
15 btnEliminar.Enabled = False
btnGrabar.Enabled = True
16 btnCancelar.Enabled = True
17 End Sub
18 Private Sub CancelarGrabar()
19 btnNuevo.Enabled = True
20 btnModificar.Enabled = True
btnEliminar.Enabled = True
21 btnGrabar.Enabled = False
22 btnCancelar.Enabled = False
23 End Sub
24 Private Sub Habilitar()
cboEstado.Enabled = True
25 txtApePaterno.ReadOnly = False
26 txtApeMaterno.ReadOnly = False
27 txtNombres.ReadOnly = False
28 dtpFecNac.Enabled = True
29 cboSexo.Enabled = True
btnAgregarFoto.Enabled = True
30 btnQuitarFoto.Enabled = True
31 End Sub
32 Private Sub Deshabilitar()
33 cboEstado.Enabled = False
34 txtApePaterno.ReadOnly = True
35 txtApeMaterno.ReadOnly = True
txtNombres.ReadOnly = True
36 dtpFecNac.Enabled = False
37 cboSexo.Enabled = False
38 btnAgregarFoto.Enabled = False
39 btnQuitarFoto.Enabled = False
End Sub
40 Private Sub Limpiar()
41 txtCodigo.Clear()
42 cboEstado.SelectedIndex = -1
43 txtApePaterno.Clear()
44 txtApeMaterno.Clear()
txtNombres.Clear()
45 pbFoto.Image = Nothing
46 dtpFecNac.Value = Now.Date
47 cboSexo.SelectedIndex = -1
48 End Sub
49
Private Sub ListarEmpleados()
50 Dim dtEmpleados As DataTable
51 dtEmpleados = _EmpleadoBL.ListarEmpleados(txtBusqueda.Text)
52 dgvEmpleados.DataSource = dtEmpleados
53
54 FormatoGrilla()
55 End Sub
56
Private Function Validar() As Boolean
57 If cboEstado.SelectedIndex = -1 Then
58 MsgBox("Seleccione Estado", MsgBoxStyle.Critical)
59 cboEstado.Focus()
60 Return False
61 End If
If txtApePaterno.Text = "" Then
62 MsgBox("Ingrese Apellido Paterno", MsgBoxStyle.Critical)
63 txtApePaterno.Focus()
64 Return False
65 End If
If txtApeMaterno.Text = "" Then
66 MsgBox("Ingrese Apellido Materno", MsgBoxStyle.Critical)
67 txtApeMaterno.Focus()
68 Return False
69 End If
70 If txtNombres.Text = "" Then
MsgBox("Ingrese Nombres", MsgBoxStyle.Critical)
71 txtNombres.Focus()
72 Return False
73 End If
74 If cboSexo.SelectedIndex = -1 Then
MsgBox("Seleccione Sexo", MsgBoxStyle.Critical)
75 cboSexo.Focus()
76 Return False
77 End If
78
79 Return True
80 End Function
81
Private Sub FormatoGrilla()
82 With dgvEmpleados
83 .Columns(0).Visible = True
84 .Columns(0).Width = 410
85
86 .Columns(1).Visible = False
.Columns(2).Visible = False
87 .Columns(3).Visible = False
88 .Columns(4).Visible = False
89 .Columns(5).Visible = False
90 .Columns(6).Visible = False
.Columns(7).Visible = False
91 .Columns(8).Visible = False
92 .Columns(9).Visible = False
93 .Columns(10).Visible = False
94 .Columns(11).Visible = False
95 .Columns(12).Visible = False
.Columns(13).Visible = False
96 End With
97 End Sub
98
99 Private Sub RecuperarDatosGrilla()
100 With dgvEmpleados.CurrentRow
txtCodigo.Text = .Cells("CodEmpleado").Value
101 If (.Cells("CodEstado").Value) = "001" Then cboEstado.SelectedIndex = 0
102Else cboEstado.SelectedIndex = 1
103 If IsDBNull(.Cells("Nombres").Value) Then txtNombres.Text = "" Else
104txtNombres.Text = .Cells("Nombres").Value
105 If IsDBNull(.Cells("ApePaterno").Value) Then txtApePaterno.Text = ""
Else txtApePaterno.Text = .Cells("ApePaterno").Value
106 If IsDBNull(.Cells("ApeMaterno").Value) Then txtApeMaterno.Text = ""
107Else txtApeMaterno.Text = .Cells("ApeMaterno").Value
108 If (.Cells("CodSexo").Value) = "001" Then cboSexo.SelectedIndex = 0
109Else cboSexo.SelectedIndex = 1
110 If IsDBNull(.Cells("FecNacimiento").Value) Then dtpFecNac.Value = ""
Else dtpFecNac.Value = .Cells("FecNacimiento").Value
111
112 '''' Recuperando Imagen
113 If (.Cells("Foto").Value) IsNot DBNull.Value Then
114 Dim byteFoto() As Byte = .Cells("Foto").Value
115 Dim recuperaFoto As New IO.MemoryStream(byteFoto)
pbFoto.Image = System.Drawing.Image.FromStream(recuperaFoto)
116 Else
117 pbFoto.Image = Nothing
118 End If
119 ''''''''''''''''''''''''
120
121 If IsDBNull(.Cells("FechaRegi").Value) Then dtpFechaRegistro.Value =
"01/01/1900" Else dtpFechaRegistro.Value = Trim(.Cells("FechaRegi").Value)
122 If IsDBNull(.Cells("UsuarioRegi").Value) Then txtUsuarioRegistra.Text =
123"" Else txtUsuarioRegistra.Text = Trim(.Cells("UsuarioRegi").Value)
124 If IsDBNull(.Cells("FechaModi").Value) Then dtpFechaModificacion.Value
125= "01/01/1900" Else dtpFechaModificacion.Value = Trim(.Cells("FechaModi").Value)
If IsDBNull(.Cells("UsuarioModi").Value) Then txtUsuarioModifica.Text =
126"" Else txtUsuarioModifica.Text = Trim(.Cells("UsuarioModi").Value)
127
128 End With
129 End Sub
130
131 '********** EL EVENTO LOAD DEL FORMULARIO**********************'
132 Private Sub FrmTutorial_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
133 Call ListarEmpleados()
134 End Sub
135
136 '********** EL EVENTO CLICK DEL BOTON AGREGAR FOTO*************'
Private Sub btnAgregarFoto_Click(ByVal sender As System.Object, ByVal e As
137System.EventArgs) Handles btnAgregarFoto.Click
138 Dim Buscar As New OpenFileDialog
139 Buscar.Multiselect = False
140 Buscar.Filter = "Archivo de Imagen (*.jpg)|*.jpg|Archivo de Imagen
(*.gif)|*.gif|Archivo de Imagen (*.png)|*.png|Todos los archivos|*.*"
141 Buscar.Title = "Seleccionar archivos"
142
143 If Buscar.ShowDialog = Windows.Forms.DialogResult.OK Then
144 Me.pbFoto.Image = Image.FromFile(Buscar.FileName)
145 End If
146 End Sub
147
'********** EL EVENTO CLICK DEL BOTON QUITAR FOTO************'
148 Private Sub btnQuitarFoto_Click(ByVal sender As System.Object, ByVal e As
149System.EventArgs) Handles btnQuitarFoto.Click
150 pbFoto.Image = Nothing
151 End Sub
152
'********** EL EVENTO CLICK DEL BOTON NUEVO********************'
153 Private Sub btnNuevo_Click(ByVal sender As System.Object, ByVal e As
154System.EventArgs) Handles btnNuevo.Click
155 NueModEli()
156 Limpiar()
157 Habilitar()
cboEstado.SelectedIndex = 0
158 flagAccion = "N"
159 End Sub
160
161 '********** EL EVENTO CLICK DEL BOTON MODIFICAR****************'
162 Private Sub btnModificar_Click(ByVal sender As System.Object, ByVal e As
163 System.EventArgs) Handles btnModificar.Click
If txtCodigo.Text = "" Then
164 MsgBox("Seleccione un Registro", MsgBoxStyle.Critical)
165 Exit Sub
166 End If
167 NueModEli()
Habilitar()
168 flagAccion = "M"
169 End Sub
170
171 '********** EL EVENTO CLICK DEL BOTON ELIMINAR****************'
172 Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As
173System.EventArgs) Handles btnEliminar.Click
If txtCodigo.Text = "" Then
174 MsgBox("Seleccione un Registro", MsgBoxStyle.Critical)
175 Exit Sub
176 End If
177
178
179 If MessageBox.Show("Esta seguro de Eliminar el Registro", _
"Tutorial", MessageBoxButtons.YesNo,
180
MessageBoxIcon.Question, _
181 MessageBoxDefaultButton.Button1) = DialogResult.Yes
182Then
183
184 flagAccion = "E"
185 Dim _EmpleadoBE As New EmpleadoBE
_EmpleadoBE.CodEmpleado = RTrim(txtCodigo.Text)
186
187 If _EmpleadoBL.GrabarEmpleado(_EmpleadoBE, flagAccion) Then
188 MsgBox("Se Eliminó El Registro Correctamente",
189MsgBoxStyle.Information)
190 Call ListarEmpleados()
flagAccion = ""
191 CancelarGrabar()
192 Deshabilitar()
193 Limpiar()
194 Else
195 MsgBox("Error al Grabar", MsgBoxStyle.Critical)
End If
196 Else
197 MsgBox("Se Cancelo la operacion.", MsgBoxStyle.Exclamation)
198 End If
199
200
201 End Sub
202
203 '********** EL EVENTO CLICK DEL BOTON GRABAR***************'
Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As
204System.EventArgs) Handles btnGrabar.Click
205 If Validar() = False Then
206 Exit Sub
207 End If
208
Dim _EmpleadoBE As New EmpleadoBE
209 _EmpleadoBE.CodEmpleado = RTrim(txtCodigo.Text)
210 _EmpleadoBE.ApePaterno = RTrim(txtApePaterno.Text)
211 _EmpleadoBE.ApeMaterno = RTrim(txtApeMaterno.Text)
212 _EmpleadoBE.Nombres = RTrim(txtNombres.Text)
213 _EmpleadoBE.FecNacimiento = dtpFecNac.Value.Date
'001:MASCULINO - 002: FEMENINO
214 _EmpleadoBE.CodSexo = IIf(cboSexo.SelectedIndex = 0, "001", "002")
215
216 'Capturando la Imagen'
217 Dim data() As Byte
218 If Not Me.pbFoto.Image Is Nothing Then
Dim ms As New MemoryStream
219 Me.pbFoto.Image.Save(ms, Imaging.ImageFormat.Jpeg)
220 data = ms.ToArray
221 Else
222 data = Nothing
223 End If
_EmpleadoBE.Foto = data
224 ''''''''''''''''''''''''''
225 '001:ACTIVO - 002: ANULADO
226 _EmpleadoBE.CodEstado = IIf(cboEstado.SelectedIndex = 0, "001", "002")
227 _EmpleadoBE.Terminal = System.Environment.MachineName
_EmpleadoBE.UsuarioRegi = "ADM"
228
_EmpleadoBE.UsuarioModi = "ADM"
229
230 If _EmpleadoBL.GrabarEmpleado(_EmpleadoBE, flagAccion) Then
231 MsgBox("Datos Grabados Correctamente", MsgBoxStyle.Information)
232 flagAccion = ""
233 NueModEli()
CancelarGrabar()
234 Deshabilitar()
235 Call ListarEmpleados()
236
Else
237 MsgBox("Error al Grabar", MsgBoxStyle.Critical)
238 End If
239
240 End Sub
241
242
243 '********** EL EVENTO CLICK DEL BOTON CANCELAR***************'
Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As
244System.EventArgs) Handles btnCancelar.Click
245 CancelarGrabar()
246 Limpiar()
247 Deshabilitar()
248 End Sub
249
'********** EL EVENTO CLICK DEL BOTON SALIR********************'
250 Private Sub btnSalir_Click(ByVal sender As System.Object, ByVal e As
251System.EventArgs) Handles btnSalir.Click
252 Me.Close()
253 End Sub
254
255 '********** EL EVENTO TEXCHANGED DEL TEXTFIELD txtBusqueda
********************'
256 Private Sub txtBusqueda_TextChanged(ByVal sender As System.Object, ByVal e As
257System.EventArgs) Handles txtBusqueda.TextChanged
258 Call ListarEmpleados()
259 End Sub
260
'********** EL EVENTO CELLCLICK DE LA GRILLA dgvEmpleados
261********************'
262 Private Sub dgvEmpleados_CellClick(ByVal sender As Object, ByVal e As
263System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvEmpleados.CellClick
264 RecuperarDatosGrilla()
265 End Sub
266
End Class
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290

 Doble Click en "My Project"(que está dentro del proyecto "Presentacion") y seleccionar la
opción "Application" (está en la parte laterial izquierda), luego seleccionar a "FrmTutorial"
como formulario de inicio (Ver figura)

 La Estructura de la Solucion "Tutorial_NCapas" debe quedar con la estructura que a


continuación se muestra en la figura:
FINALMENTE:

 Click derecho en la solución "Tutorial_NCapas" y seleccionar lo opcion "Establecer


Proyecto de Inicio", luego seleccionar como proyecto de inicio a "Presentacion" (Ver
figura).

Das könnte Ihnen auch gefallen