TUTORIAL DE LA APLICACIÓN

1. Base de Datos

1.1 Creando la Tabla Empleado

CREATE TABLE [Empleado](
 [CodEmpleado] [char](10) NOT NULL,
 [Nombres] [varchar](100) NULL,
 [ApePaterno] [varchar](50) NULL,
 [ApeMaterno] [varchar](50) NULL,
 [FecNacimiento] [date] NULL,
 [CodSexo] [char](3) NULL,
 [Foto] [image] NULL,
 [CodEstado] [char](3) NULL,
 [Terminal] [varchar](15) NULL,
 [FechaRegi] [datetime] NULL,
 [UsuarioRegi] [varchar](15) NULL,
 [FechaModi] [datetime] NULL,
 [UsuarioModi] [varchar](15) NULL,
 CONSTRAINT [PK_Empleado] PRIMARY KEY CLUSTERED 
(
 [CodEmpleado] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

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

--STORED PROCEDURE PARA GENERAR CODIGO DE EMPLEADO
CREATE PROCEDURE [dbo].[USP_Empleado_GenerarCodigo]
AS
BEGIN
select 
'EMP' +
RIGHT('0000000'+CONVERT(VARCHAR(20),ISNULL(MAX(RIGHT(CodEmpleado,7)),0)+1),7)
from Empleado
END

GO

-- STORED PROCEDURE PARA INSERTAR
CREATE PROCEDURE [dbo].[USP_Empleado_Insertar]
(
 @CodEmpleado char(10),
 @Nombres varchar(100) = NULL,
 @ApePaterno varchar(50) = NULL,
 @ApeMaterno varchar(50) = NULL,
 @FecNacimiento date = NULL,
 @CodSexo char(3) = NULL,
 @Foto image = NULL,
 @CodEstado char(3) = NULL,
 @Terminal varchar(15) = NULL,
 @UsuarioRegi varchar(15) = NULL)
AS

BEGIN
 
  INSERT
  INTO [Empleado]
  (
  [CodEmpleado],
  [Nombres],
  [ApePaterno],
  [ApeMaterno],
  [FecNacimiento],
  [CodSexo],
  [Foto],
  [CodEstado],
  [Terminal],
  [FechaRegi],
  [UsuarioRegi]
  )
  VALUES
  (
  @CodEmpleado,
  @Nombres,
  @ApePaterno,
  @ApeMaterno,
  @FecNacimiento,
  @CodSexo,
  @Foto,
  @CodEstado,
  @Terminal,
  GETDATE(),
  @UsuarioRegi
  )
END

GO

--STORED PROCEDURE PARA ACTUALIZAR
CREATE PROCEDURE [USP_Empleado_Actualizar]
(
 @CodEmpleado char(10),
 @Nombres varchar(100) = NULL,
 @ApePaterno varchar(50) = NULL,
 @ApeMaterno varchar(50) = NULL,
 @FecNacimiento date = NULL,
 @CodSexo char(3) = NULL,
 @Foto image = NULL,
 @CodEstado char(3) = NULL,
 @Terminal varchar(15) = NULL,
 @UsuarioModi varchar(15) = NULL)
AS

BEGIN
  UPDATE [Empleado]
  SET 
  [CodEmpleado] = @CodEmpleado,
  [Nombres] = @Nombres,
  [ApePaterno] = @ApePaterno,
  [ApeMaterno] = @ApeMaterno,
  [FecNacimiento] = @FecNacimiento,
  [CodSexo] = @CodSexo,
  [Foto] = @Foto,
  [CodEstado] = @CodEstado,
  [Terminal] = @Terminal,
  [FechaModi] = GETDATE(),
  [UsuarioModi] = @UsuarioModi
  WHERE
  [CodEmpleado] = @CodEmpleado

END

GO

--STORED PROCEDURE PARA ELIMINAR
CREATE PROCEDURE [USP_Empleado_Eliminar]
(
 @CodEmpleado char(10)
)
AS

BEGIN
 
 DELETE FROM Empleado 
 WHERE [CodEmpleado] = @CodEmpleado

END

GO

--PROCEDURE PARA LISTAR REGISTROS POR CRITERIO DE BUSQUEDA
CREATE PROCEDURE [dbo].[USP_Empleado_Listar]
@Criterio varchar(150)
AS
begin 
select Empleado=ApePaterno+' '+ApeMaterno+' '+Nombres,* from Empleado
where (ApePaterno+''+ApeMaterno+''+Nombres) like '%'+@Criterio+'%'
end

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"
Public Class EmpleadoBE
    'Campos de la entidad
    Private _CodEmpleado As String
    Private _Nombres As String
    Private _ApePaterno As String
    Private _ApeMaterno As String
    Private _FecNacimiento As Date
    Private _CodSexo As String
    Private _Foto As Byte()
    Private _CodEstado As String
    Private _Terminal As String
    Private _FechaRegi As Date
    Private _UsuarioRegi As String
    Private _FechaModi As Date
    Private _UsuarioModi As String

    'Propiedades de la entidad
    Public Property CodEmpleado() As String
        Get
            Return _CodEmpleado
        End Get
        Set(ByVal value As String)
            _CodEmpleado = value
        End Set
    End Property

    Public Property Nombres() As String
        Get
            Return _Nombres
        End Get
        Set(ByVal value As String)
            _Nombres = value
        End Set
    End Property

    Public Property ApePaterno() As String
        Get
            Return _ApePaterno
        End Get
        Set(ByVal value As String)
            _ApePaterno = value
        End Set
    End Property

    Public Property ApeMaterno() As String
        Get
            Return _ApeMaterno
        End Get
        Set(ByVal value As String)
            _ApeMaterno = value
        End Set
    End Property

    Public Property FecNacimiento() As Date
        Get
            Return _FecNacimiento
        End Get
        Set(ByVal value As Date)
            _FecNacimiento = value
        End Set
    End Property

    Public Property CodSexo() As String
        Get
            Return _CodSexo
        End Get
        Set(ByVal value As String)
            _CodSexo = value
        End Set
    End Property

    Public Property Foto() As Byte()
        Get
            Return _Foto
        End Get
        Set(ByVal value As Byte())
            _Foto = value
        End Set
    End Property

    Public Property CodEstado() As String
        Get
            Return _CodEstado
        End Get
        Set(ByVal value As String)
            _CodEstado = value
        End Set
    End Property

    Public Property Terminal() As String
        Get
            Return _Terminal
        End Get
        Set(ByVal value As String)
            _Terminal = value
        End Set
    End Property

    Public Property FechaRegi() As Date
        Get
            Return _FechaRegi
        End Get
        Set(ByVal value As Date)
            _FechaRegi = value
        End Set
    End Property

    Public Property UsuarioRegi() As String
        Get
            Return _UsuarioRegi
        End Get
        Set(ByVal value As String)
            _UsuarioRegi = value
        End Set
    End Property

    Public Property FechaModi() As Date
        Get
            Return _FechaModi
        End Get
        Set(ByVal value As Date)
            _FechaModi = value
        End Set
    End Property

    Public Property UsuarioModi() As String
        Get
            Return _UsuarioModi
        End Get
        Set(ByVal value As String)
            _UsuarioModi = value
        End Set
    End Property
End Class


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
Imports System.Data
Imports System.Data.SqlClient

Public Class Conexion
    Public Function Conexion() As SqlConnection
        'Cambiar la Base de Datos y el Password de acuerdo a su configuracion
        Dim cadconex As String = "Server=.;DATABASE=xxx;User ID=sa;Password=xxx"
        Dim cn As New SqlConnection(cadconex)
        Return cn
    End Function
End Class

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
Imports BusinessEntities 'Importamos la capa de entidades, si tienen error es porque no se agrego la referencia
Imports System.Data
Imports System.Data.SqlClient

Public Class EmpleadoDA
    'Instanciamos el objeto _Conexion de la clase Conexion para obtener la cadena de conexion a la BD
    Dim _Conexion As New Conexion

    'Funcion que me ve permitir generar el codigo del empleado
    Private Function GenerarCorrelativo() As String
        Dim cmd As New SqlCommand
        Dim da As New SqlDataAdapter
        Dim dt As New DataTable
        cmd.Connection = _Conexion.Conexion
        cmd.CommandText = "USP_Empleado_GenerarCodigo"
        cmd.CommandType = CommandType.StoredProcedure
        da.SelectCommand = cmd
        da.Fill(dt)
        Return dt.Rows(0).Item(0)
    End Function

    'Metodo para registrar un nuevo empleado
    Private Sub Registrar(ByVal EmpleadoBE As EmpleadoBE, ByVal sqlCon As SqlConnection, _
                          ByVal sqlTrans As SqlTransaction)
        Try
            Dim cmd As New SqlCommand
            cmd.CommandText = "USP_Empleado_Insertar"
            cmd.Connection = sqlCon
            cmd.Transaction = sqlTrans
            cmd.CommandType = CommandType.StoredProcedure

            'Los parametros que va recibir son las propiedades de la clase Empleado
            cmd.Parameters.Add("@CodEmpleado", SqlDbType.Char).Value = EmpleadoBE.CodEmpleado
            cmd.Parameters.Add("@Nombres", SqlDbType.VarChar).Value = EmpleadoBE.Nombres
            cmd.Parameters.Add("@ApePaterno", SqlDbType.VarChar).Value = EmpleadoBE.ApePaterno
            cmd.Parameters.Add("@ApeMaterno", SqlDbType.VarChar).Value = EmpleadoBE.ApeMaterno
            cmd.Parameters.Add("@FecNacimiento", SqlDbType.Date).Value = EmpleadoBE.FecNacimiento
            cmd.Parameters.Add("@CodSexo", SqlDbType.Char).Value = EmpleadoBE.CodSexo
            cmd.Parameters.Add("@Foto", SqlDbType.Image).Value = EmpleadoBE.Foto

            cmd.Parameters.Add("@CodEstado", SqlDbType.Char).Value = EmpleadoBE.CodEstado
            cmd.Parameters.Add("@Terminal", SqlDbType.VarChar).Value = EmpleadoBE.Terminal
            cmd.Parameters.Add("@UsuarioRegi", SqlDbType.VarChar).Value = EmpleadoBE.UsuarioRegi

            cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub

    'Metodo para Modificar un empleado
    Private Sub Modificar(ByVal EmpleadoBE As EmpleadoBE, ByVal sqlCon As SqlConnection, _
                          ByVal sqlTrans As SqlTransaction)
        Try
            Dim cmd As New SqlCommand
            cmd.CommandText = "USP_Empleado_Actualizar"
            cmd.Connection = sqlCon
            cmd.Transaction = sqlTrans
            cmd.CommandType = CommandType.StoredProcedure

            cmd.Parameters.Add("@CodEmpleado", SqlDbType.Char).Value = EmpleadoBE.CodEmpleado
            cmd.Parameters.Add("@Nombres", SqlDbType.VarChar).Value = EmpleadoBE.Nombres
            cmd.Parameters.Add("@ApePaterno", SqlDbType.VarChar).Value = EmpleadoBE.ApePaterno
            cmd.Parameters.Add("@ApeMaterno", SqlDbType.VarChar).Value = EmpleadoBE.ApeMaterno
            cmd.Parameters.Add("@FecNacimiento", SqlDbType.Date).Value = EmpleadoBE.FecNacimiento
            cmd.Parameters.Add("@CodSexo", SqlDbType.Char).Value = EmpleadoBE.CodSexo
            cmd.Parameters.Add("@Foto", SqlDbType.Image).Value = EmpleadoBE.Foto

            cmd.Parameters.Add("@CodEstado", SqlDbType.Char).Value = EmpleadoBE.CodEstado
            cmd.Parameters.Add("@Terminal", SqlDbType.VarChar).Value = EmpleadoBE.Terminal
            cmd.Parameters.Add("@UsuarioModi", SqlDbType.VarChar).Value = EmpleadoBE.UsuarioModi

            cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub

    'Metodo para Eliminar un empleado
    Private Sub Eliminar(ByVal EmpleadoBE As EmpleadoBE, ByVal sqlCon As SqlConnection, _
                          ByVal sqlTrans As SqlTransaction)
        Try
            Dim cmd As New SqlCommand
            cmd.CommandText = "USP_Empleado_Eliminar"
            cmd.Connection = sqlCon
            cmd.Transaction = sqlTrans
            cmd.CommandType = CommandType.StoredProcedure

            cmd.Parameters.Add("@CodEmpleado", SqlDbType.Char).Value = EmpleadoBE.CodEmpleado

            cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub

    'Funcion Principal que hara toda la logica para grabar la data
    Public Function GrabarEmpleado(ByVal EmpleadoBE As EmpleadoBE, ByVal flagAccion As String) As Boolean
        Dim resultado As Boolean = True
        Dim cn As New SqlConnection
        Dim sqlTrans As SqlTransaction
        Dim correlativo As String

        cn = _Conexion.Conexion
        cn.Open()
        sqlTrans = cn.BeginTransaction

        Try
            'N:Nuevo   M:Modificar   E:Eliminar 

            If flagAccion = "N" Then
                correlativo = GenerarCorrelativo()
                EmpleadoBE.CodEmpleado = correlativo
                Registrar(EmpleadoBE, cn, sqlTrans)
            End If

            If flagAccion = "M" Then
                Modificar(EmpleadoBE, cn, sqlTrans)
            End If

            If flagAccion = "E" Then
                Eliminar(EmpleadoBE, cn, sqlTrans)
            End If


            sqlTrans.Commit()
            resultado = True

        Catch ex As SqlException
            sqlTrans.Rollback()
            resultado = False
        Catch ex As Exception
            sqlTrans.Rollback()
            resultado = False
        Finally
            cn.Close()
            sqlTrans = Nothing
        End Try

        Return resultado
    End Function


    'Funcion que me va permitir capturar la lista de registros en la tabla empleado y que me va retornar
    'un Datatable
    Public Function ListarEmpleados(ByVal Criterio As String) As DataTable
        Dim cmd As New SqlCommand
        Dim da As New SqlDataAdapter
        Dim dt As New DataTable

        cmd.Connection = _Conexion.Conexion
        cmd.CommandText = "USP_Empleado_Listar"
        cmd.CommandType = CommandType.StoredProcedure

        cmd.Parameters.Add("@Criterio", SqlDbType.VarChar).Value = Criterio
        da.SelectCommand = cmd
        da.Fill(dt)
        Return dt
    End Function
End Class



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 "BusinessLogic" y agregar una nueva clase con el nombre de "EmpleadoBL"
  • Agregar el siguiente codigo dentro de la clase "EmpleadoBL"
La Clase EmpleadoBL.vb
Imports BusinessEntities 'Importamos la capa de entidades
Imports DataAccess 'Importamos la capa de acceso a datos
Public Class EmpleadoBL
    'Instanciamos el objeto _EmpleadoDA de la Clase EmpleadoDA
    Dim _EmpleadoDA As New EmpleadoDA

    Public Function GrabarEmpleado(ByVal EmpleadoBE As EmpleadoBE, _
                                   ByVal flagAccion As String) As Boolean
        Return _EmpleadoDA.GrabarEmpleado(EmpleadoBE, flagAccion)
    End Function

    Public Function ListarEmpleados(ByVal Criterio As String) As DataTable
        Return _EmpleadoDA.ListarEmpleados(Criterio)
    End Function
End Class


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
Botones TextFields ComboBox y DateTimePicker DataGridView y PictureBox
Para el boton "Nuevo":
  • Name: btnNuevo
  • Enable: True
  • Text: Nuevo
Para el boton "Modificar":
  • Name: btnModificar
  • Enable: True
  • Text: Modificar
Para el boton "Eliminar":
  • Name: btnEliminar
  • Enable: True
  • Text: Eliminar
Para el boton "Grabar":
  • Name: btnGrabar
  • Enable: False
  • Text: Grabar
Para el boton "Cancelar":
  • Name: btnCancelar
  • Enable: False
  • Text: Cancelar
Para el boton "Salir":
  • Name: btnSalir
  • Enable: True
  • Text: Salir
Para el boton "+" (Agregar Foto):
  • Name: btnAgregarFoto
  • Enable: False
Para el boton "x" (Quitar Foto):
  • Name: btnQuitarFoto
  • Enable: False
Para el Campo "Codigo":
  • Name: txtCodigo
  • ReadOnly: True
Para el Campo "Apellido Paterno":
  • Name: txtApePaterno
  • ReadOnly: True
Para el Campo "Apellido Materno":
  • Name: txtApeMaterno
  • ReadOnly: True
Para el Campo "Nombres":
  • Name: txtNombres
  • ReadOnly: True
Para el Campo "Ingrese Nombres":
  • Name: txtBusqueda
  • ReadOnly: False
Para el Campo "Registrado Por":
  • Name: txtUsuarioRegistra
  • Enable: False
Para el Campo "Modificado Por":
  • Name: txtUsuarioModifica
  • Enable: False
Para el Combo "Estado":
  • Name: cboEstado
  • Enable: False
  • DropDownStyle: DropDownList
  • Items:(Collection)>> ACTIVO, ANULADO
Para el Combo "Sexo":
  • Name: cboSexo
  • Enable: False
  • DropDownStyle: DropDownList
  • Items:(Collection)>> MASCULINO, FEMENINO
Para el DateTimePicker "Fecha Nacimiento":
  • Name: dtpFecNac
  • Enable: False
  • Format: Short
Para el DateTimePicker "Fecha Reg":
  • Name: dtpFechaRegistro
  • Enable: False
  • Format: Short
Para el DateTimePicker "Fecha Modif":
  • Name: dtpFechaModificacion
  • Enable: False
  • Format: Short
Para el DataGridView:
  • Name: dgvEmpleados
  • Selection Mode: FullRowSelect
Para el PictureBox de la Foto:
  • Name: pbFoto
  • BorderStyle: FixedSingle
  • SizeMode: StretchImage

Ingresar el siguiente codigo dentro del Formulario FrmTutorial
'Importando la Capa de Entidades y la Capa Logica
Imports BusinessEntities
Imports BusinessLogic
'Importacion necesaria para trabajar con las imagenes
Imports System.IO

Public Class FrmTutorial

    '**************  DECLARACION DE VARIABLES GLOBALES ****************'
    Dim _EmpleadoBL As New EmpleadoBL
    Dim flagAccion As String = ""

    '******************** METODOS *************************************'
    Private Sub NueModEli()
        btnNuevo.Enabled = False
        btnModificar.Enabled = False
        btnEliminar.Enabled = False
        btnGrabar.Enabled = True
        btnCancelar.Enabled = True
    End Sub
    Private Sub CancelarGrabar()
        btnNuevo.Enabled = True
        btnModificar.Enabled = True
        btnEliminar.Enabled = True
        btnGrabar.Enabled = False
        btnCancelar.Enabled = False
    End Sub
    Private Sub Habilitar()
        cboEstado.Enabled = True
        txtApePaterno.ReadOnly = False
        txtApeMaterno.ReadOnly = False
        txtNombres.ReadOnly = False
        dtpFecNac.Enabled = True
        cboSexo.Enabled = True
        btnAgregarFoto.Enabled = True
        btnQuitarFoto.Enabled = True
    End Sub
    Private Sub Deshabilitar()
        cboEstado.Enabled = False
        txtApePaterno.ReadOnly = True
        txtApeMaterno.ReadOnly = True
        txtNombres.ReadOnly = True
        dtpFecNac.Enabled = False
        cboSexo.Enabled = False
        btnAgregarFoto.Enabled = False
        btnQuitarFoto.Enabled = False
    End Sub
    Private Sub Limpiar()
        txtCodigo.Clear()
        cboEstado.SelectedIndex = -1
        txtApePaterno.Clear()
        txtApeMaterno.Clear()
        txtNombres.Clear()
        pbFoto.Image = Nothing
        dtpFecNac.Value = Now.Date
        cboSexo.SelectedIndex = -1
    End Sub

    Private Sub ListarEmpleados()
        Dim dtEmpleados As DataTable
        dtEmpleados = _EmpleadoBL.ListarEmpleados(txtBusqueda.Text)
        dgvEmpleados.DataSource = dtEmpleados

        FormatoGrilla()
    End Sub

    Private Function Validar() As Boolean
        If cboEstado.SelectedIndex = -1 Then
            MsgBox("Seleccione Estado", MsgBoxStyle.Critical)
            cboEstado.Focus()
            Return False
        End If
        If txtApePaterno.Text = "" Then
            MsgBox("Ingrese Apellido Paterno", MsgBoxStyle.Critical)
            txtApePaterno.Focus()
            Return False
        End If
        If txtApeMaterno.Text = "" Then
            MsgBox("Ingrese Apellido Materno", MsgBoxStyle.Critical)
            txtApeMaterno.Focus()
            Return False
        End If
        If txtNombres.Text = "" Then
            MsgBox("Ingrese Nombres", MsgBoxStyle.Critical)
            txtNombres.Focus()
            Return False
        End If
        If cboSexo.SelectedIndex = -1 Then
            MsgBox("Seleccione Sexo", MsgBoxStyle.Critical)
            cboSexo.Focus()
            Return False
        End If

        Return True
    End Function

    Private Sub FormatoGrilla()
        With dgvEmpleados
            .Columns(0).Visible = True
            .Columns(0).Width = 410

            .Columns(1).Visible = False
            .Columns(2).Visible = False
            .Columns(3).Visible = False
            .Columns(4).Visible = False
            .Columns(5).Visible = False
            .Columns(6).Visible = False
            .Columns(7).Visible = False
            .Columns(8).Visible = False
            .Columns(9).Visible = False
            .Columns(10).Visible = False
            .Columns(11).Visible = False
            .Columns(12).Visible = False
            .Columns(13).Visible = False
        End With
    End Sub

    Private Sub RecuperarDatosGrilla()
        With dgvEmpleados.CurrentRow
            txtCodigo.Text = .Cells("CodEmpleado").Value
            If (.Cells("CodEstado").Value) = "001" Then cboEstado.SelectedIndex = 0 Else cboEstado.SelectedIndex = 1
            If IsDBNull(.Cells("Nombres").Value) Then txtNombres.Text = "" Else txtNombres.Text = .Cells("Nombres").Value
            If IsDBNull(.Cells("ApePaterno").Value) Then txtApePaterno.Text = "" Else txtApePaterno.Text = .Cells("ApePaterno").Value
            If IsDBNull(.Cells("ApeMaterno").Value) Then txtApeMaterno.Text = "" Else txtApeMaterno.Text = .Cells("ApeMaterno").Value
            If (.Cells("CodSexo").Value) = "001" Then cboSexo.SelectedIndex = 0 Else cboSexo.SelectedIndex = 1
            If IsDBNull(.Cells("FecNacimiento").Value) Then dtpFecNac.Value = "" Else dtpFecNac.Value = .Cells("FecNacimiento").Value

            '''' Recuperando Imagen
            If (.Cells("Foto").Value) IsNot DBNull.Value Then
                Dim byteFoto() As Byte = .Cells("Foto").Value
                Dim recuperaFoto As New IO.MemoryStream(byteFoto)
                pbFoto.Image = System.Drawing.Image.FromStream(recuperaFoto)
            Else
                pbFoto.Image = Nothing
            End If
            ''''''''''''''''''''''''

            If IsDBNull(.Cells("FechaRegi").Value) Then dtpFechaRegistro.Value = "01/01/1900" Else dtpFechaRegistro.Value = Trim(.Cells("FechaRegi").Value)
            If IsDBNull(.Cells("UsuarioRegi").Value) Then txtUsuarioRegistra.Text = "" Else txtUsuarioRegistra.Text = Trim(.Cells("UsuarioRegi").Value)
            If IsDBNull(.Cells("FechaModi").Value) Then dtpFechaModificacion.Value = "01/01/1900" Else dtpFechaModificacion.Value = Trim(.Cells("FechaModi").Value)
            If IsDBNull(.Cells("UsuarioModi").Value) Then txtUsuarioModifica.Text = "" Else txtUsuarioModifica.Text = Trim(.Cells("UsuarioModi").Value)

        End With
    End Sub

    '**********  EL EVENTO LOAD DEL FORMULARIO**********************'
    Private Sub FrmTutorial_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call ListarEmpleados()
    End Sub

    '**********  EL EVENTO CLICK DEL BOTON AGREGAR FOTO*************'
    Private Sub btnAgregarFoto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarFoto.Click
        Dim Buscar As New OpenFileDialog
        Buscar.Multiselect = False
        Buscar.Filter = "Archivo de Imagen (*.jpg)|*.jpg|Archivo de Imagen (*.gif)|*.gif|Archivo de Imagen (*.png)|*.png|Todos los archivos|*.*"
        Buscar.Title = "Seleccionar archivos"

        If Buscar.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.pbFoto.Image = Image.FromFile(Buscar.FileName)
        End If
    End Sub

    '**********  EL EVENTO CLICK DEL BOTON QUITAR FOTO************'
    Private Sub btnQuitarFoto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuitarFoto.Click
        pbFoto.Image = Nothing
    End Sub

    '**********  EL EVENTO CLICK DEL BOTON NUEVO********************'
    Private Sub btnNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNuevo.Click
        NueModEli()
        Limpiar()
        Habilitar()
        cboEstado.SelectedIndex = 0
        flagAccion = "N"
    End Sub

    '**********  EL EVENTO CLICK DEL BOTON MODIFICAR****************'
    Private Sub btnModificar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnModificar.Click
        If txtCodigo.Text = "" Then
            MsgBox("Seleccione un Registro", MsgBoxStyle.Critical)
            Exit Sub
        End If
        NueModEli()
        Habilitar()
        flagAccion = "M"
    End Sub

    '**********  EL EVENTO CLICK DEL BOTON ELIMINAR****************'
    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminar.Click
        If txtCodigo.Text = "" Then
            MsgBox("Seleccione un Registro", MsgBoxStyle.Critical)
            Exit Sub
        End If
       

        If MessageBox.Show("Esta seguro de Eliminar el Registro", _
                           "Tutorial", MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
                           MessageBoxDefaultButton.Button1) = DialogResult.Yes Then

            flagAccion = "E"
            Dim _EmpleadoBE As New EmpleadoBE
            _EmpleadoBE.CodEmpleado = RTrim(txtCodigo.Text)

            If _EmpleadoBL.GrabarEmpleado(_EmpleadoBE, flagAccion) Then
                MsgBox("Se Eliminó El Registro Correctamente", MsgBoxStyle.Information)
                Call ListarEmpleados()
                flagAccion = ""
                CancelarGrabar()
                Deshabilitar()
                Limpiar()
            Else
                MsgBox("Error al Grabar", MsgBoxStyle.Critical)
            End If
        Else
            MsgBox("Se Cancelo la operacion.", MsgBoxStyle.Exclamation)
        End If

       
    End Sub

    '**********  EL EVENTO CLICK DEL BOTON GRABAR***************'
    Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click
        If Validar() = False Then
            Exit Sub
        End If

        Dim _EmpleadoBE As New EmpleadoBE
        _EmpleadoBE.CodEmpleado = RTrim(txtCodigo.Text)
        _EmpleadoBE.ApePaterno = RTrim(txtApePaterno.Text)
        _EmpleadoBE.ApeMaterno = RTrim(txtApeMaterno.Text)
        _EmpleadoBE.Nombres = RTrim(txtNombres.Text)
        _EmpleadoBE.FecNacimiento = dtpFecNac.Value.Date
        '001:MASCULINO    -  002: FEMENINO
        _EmpleadoBE.CodSexo = IIf(cboSexo.SelectedIndex = 0, "001", "002")

        'Capturando la Imagen'
        Dim data() As Byte
        If Not Me.pbFoto.Image Is Nothing Then
            Dim ms As New MemoryStream
            Me.pbFoto.Image.Save(ms, Imaging.ImageFormat.Jpeg)
            data = ms.ToArray
        Else
            data = Nothing
        End If
        _EmpleadoBE.Foto = data
        ''''''''''''''''''''''''''
        '001:ACTIVO    -  002: ANULADO
        _EmpleadoBE.CodEstado = IIf(cboEstado.SelectedIndex = 0, "001", "002")
        _EmpleadoBE.Terminal = System.Environment.MachineName
        _EmpleadoBE.UsuarioRegi = "ADM"
        _EmpleadoBE.UsuarioModi = "ADM"

        If _EmpleadoBL.GrabarEmpleado(_EmpleadoBE, flagAccion) Then
            MsgBox("Datos Grabados Correctamente", MsgBoxStyle.Information)
            flagAccion = ""
            NueModEli()
            CancelarGrabar()
            Deshabilitar()
            Call ListarEmpleados()

        Else
            MsgBox("Error al Grabar", MsgBoxStyle.Critical)
        End If

    End Sub

    
    '**********  EL EVENTO CLICK DEL BOTON CANCELAR***************'
    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        CancelarGrabar()
        Limpiar()
        Deshabilitar()
    End Sub

    '**********  EL EVENTO CLICK DEL BOTON SALIR********************'
    Private Sub btnSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSalir.Click
        Me.Close()
    End Sub

    '**********  EL EVENTO TEXCHANGED DEL TEXTFIELD txtBusqueda ********************'
    Private Sub txtBusqueda_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBusqueda.TextChanged
        Call ListarEmpleados()
    End Sub

    '**********  EL EVENTO CELLCLICK DE LA GRILLA dgvEmpleados ********************'
    Private Sub dgvEmpleados_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvEmpleados.CellClick
        RecuperarDatosGrilla()
    End Sub

End Class

  • 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).

Video Demostrativo de la Aplicación

Copyright © 2021 TRUJILLOSOFT