SlideShare una empresa de Scribd logo
UNJBG
                                        ¡¡LÍDER EN CAPACITACIÓN INFORMÁTICA!!
             ITEL
                                   Garantía del proceso Enseñanza-Aprendizaje con las últimas
           CARRERA
                                      tecnologías, con computadoras de última generación,
        Técnico Analista                                                                                      CURSO
                                    impresoras, escáner, multimedia, redes, Internet, material
        Programador de                                                                               Programación Visual .NET II
                                 didáctico paso a paso, biblioteca y aula virtual con docentes del
           Sistemas
                                                          mas alto nivel.



                                      GUÍA DE LABORATORIO N° 04

OBJETIVOS:
• Listado y/o Consultas utilizando comandos SQL.
• Uso de componentes PageSetupDialog, PrintDocument, PrintPreviewdialog, PrintDialog.

1. CREACIÓN DE FORMULARIO PARA CONSULTA DE EMPLEADOS(FrmConsultarEmpleados.vb)
    Agregue un nuevo formulario a su proyecto y guárdelo con el nombre de FrmConsultarEmpleados.vb
    • Proceda a agregar los siguientes objetos según se observa a continuación:




              Importante: Observará Usted en la imagen anterior que se ha agregado 4 componentes nuevos, ellos
              son: PageSetupDialog, PrintDocument, PrintPreviewDialog y PrintDialog.

    •     Proceda a Establecer las propiedades a c/u de los objetos según el siguiente cuadro. Además deberá
          establecer otras propiedades para mejorar la apariencia de nuestro formulario.
                         Objeto                 Propiedad                       Valor Asignado
                     Form1                 Name                      FrmConsultarEmpleados
                                           FormBorderStyle           FixedToolWindow
                                           ControlBox                False
                                           Startposition             CenterScreen
                     Radiobutton1          Name                      rbtCodigo
                     Radiobutton2          Name                      rbtApellidos
                     Radiobutton3          Name                      rbtNombres
                     Radiobutton3          Name                      rbtCargo

Bimestre Académico     : 2009-                                                             Docente   :   José Luis Ponce Segura.
Ciclo                  : V                                (1 de 5)                         Fecha     :   Tacna, Mayo del 2009
Universidad Nacional Jorge Basadre Grohmann - ITEL
Carrera: Técnico Analista Programador de Sistemas.                                   Curso: Programación Visual .Net II



                        Objeto              Propiedad                    Valor Asignado
                   ComboBox1           Name                   cboCargo
                   Label1              Name                   lblTitulo
                   Label2              Name                   lblMensaje
                   TextBox1            Name                   txtBusqueda
                   Button1             Text                   &Imprimir
                                       Name                   btnImprimir
                   Button2             Text                   &vista Previa
                                       Name                   btnVistaprevia
                   Button3             Text                   &Conf. Hoja
                                       Name                   btnConfigurarhoja
                   Button4             Text                   &Salir
                                       Name                   btnSalir

    •   Ahora proceda a escribir el código correspondiente:
 Option Compare Text
 Imports System.Data.SqlClient
 Imports System.Data
 Imports System.IO
 Imports System.Text
   ' Esto va en la sección declaraciones...
   Dim strcampo, oper As String
   Dim Comando As SqlCommand
   Dim t As Integer
   Dim cargo As Boolean
   Dim miDt As New DataTable
   Dim fil As Byte
 Private Sub FrmConsultarEmpleados_Load(ByVal ….EventArgs) Handles MyBase.Load
   VerOpciones(True)
   DataGridView1.ReadOnly = True
 End Sub
 Private Sub rbtCodigo_Click(ByVal sender As .......) Handles rbtCodigo.Click,
                                  rbtApellidos.Click, rbtNombres.Click, rbtCargo.Click
   Select Case sender.name
     Case "rbtCodigo"
       strcampo = "codemp"
       oper = " codigo "
     Case "rbtApellidos"
       strcampo = " apeemp "
       oper = " apellido "
     Case "rbtNombres"
       strcampo = "nomemp"
       oper = " nombre "
     Case "rbtCargo"
       VerOpciones(False)
       cboCargo.Items.Clear()
       LlenarCargos()
       DataGridView1.DataSource = Nothing
       cargo = True
       Exit Sub
   End Select
   VerOpciones(True)
   cargo = False
   lblTitulo.Text = "ingrese " & oper & " a buscar"
   DataGridView1.DataSource = Nothing
   txtBusqueda.Clear()
   txtBusqueda.Focus()
 End Sub

Docente: José Luis Ponce Segura                      Prac04 (2 de 5)                      e-mail: jlponcesg@hotmail.com
Cel. : 952636911                                                                                       www.redtacna.net
Universidad Nacional Jorge Basadre Grohmann - ITEL
Carrera: Técnico Analista Programador de Sistemas.                     Curso: Programación Visual .Net II


 Private Sub LlenarCargos()
   Dim cm As New SqlCommand("select * from Cargo", Conexion)
   Dim miDr As SqlDataReader
   Conexion.Open()
   miDr = cm.ExecuteReader()
   While miDr.Read()
     cboCargo.Items.Add(miDr("codcar") & ": " & miDr("descar"))
   End While
   miDr.Close()
   Conexion.Close()
 End Sub
 Private Sub cboCargo_Leave(ByVal sender As ......) Handles cboCargo.Leave
   cboCargo.Text = ""
 End Sub
 Private Sub cboCargo_SelectedIndexChanged(...) Handles cboCargo.SelectedIndexChanged
   buscar()
 End Sub
 Private Sub btnBuscar_Click(ByVal…… System.EventArgs) Handles btnBuscar.Click
   buscar()
 End Sub
 Private Sub btnImprimir_Click(ByVal … System.EventArgs) Handles btnImprimir.Click
   If ContarGrilla() = False Then MsgBox("No hay datos que imprimir") : Exit Sub
   With PrintDialog1 'Dialogo de Print
     .Document = PrintDocument1
     .AllowPrintToFile = False
     .AllowSelection = True
     .AllowSomePages = True
     If .ShowDialog() = Windows.Forms.DialogResult.OK Then
       PrintDocument1.PrinterSettings = .PrinterSettings
       PrintDocument1.Print()
     End If
   End With
 End Sub
 Private Sub btnVistaPrevia_Click(ByVal ... EventArgs) Handles btnVistaPrevia.Click
   If ContarGrilla() = False Then MsgBox("No hay datos que imprimir") : Exit Sub
   With PrintPreviewDialog1 'Dialogo de Preview
     .Document = PrintDocument1
     .Text = "Lista de Empleados..."
     .WindowState = FormWindowState.Maximized
     .ShowDialog()
   End With
 End Sub
 Private Sub btnConfigurarHoja_Click(ByVal…EventArgs) Handles btnConfigurarHoja.Click
   If ContarGrilla() = False Then MsgBox("No hay datos que imprimir") : Exit Sub
   With PageSetupDialog1 'Dialogo de Page Setup
     .Document = PrintDocument1
     .ShowDialog()
   End With
 End Sub
 Private Sub PrintDocument1_PrintPage(ByVal ...) Handles PrintDocument1.PrintPage
   Dim i As Integer
   Dim stb, stbencabezado, stblinea As New StringBuilder()
   Dim texto, texto1, texto2, texto3 As String
   Dim Fuente As New Font("Courier New", 10)
   Dim Brocha As Brush = Brushes.Blue
   Dim X As Integer = e.MarginBounds.Left
   Dim Y As Integer = e.MarginBounds.Top

    texto1 = "Tacna, " & Now.Date
    e.Graphics.DrawString(texto1, Fuente, Brocha, e.MarginBounds.Width, Y)

Docente: José Luis Ponce Segura                      Prac04 (3 de 5)      e-mail: jlponcesg@hotmail.com
Cel. : 952636911                                                                       www.redtacna.net
Universidad Nacional Jorge Basadre Grohmann - ITEL
Carrera: Técnico Analista Programador de Sistemas.                     Curso: Programación Visual .Net II


    Y = Y + Fuente.GetHeight * 2

    texto2 = "Listado de Empleados"
    Dim centro As Integer
    centro = e.MarginBounds.Width / 2
    e.Graphics.DrawString(texto2.ToString.ToUpper, Fuente, Brocha, centro, Y)
    Y = Y + Fuente.GetHeight * 2

    'Encabezado de Datos
    stbencabezado.Append("Código".ToString.PadRight(7))
    stbencabezado.Append("Nombres".ToString.PadRight(20))
    stbencabezado.Append("Apellidos".ToString.PadRight(20))
    stbencabezado.Append("Dirección".ToString.PadRight(20))
    stbencabezado.Append("Teléfono".ToString.PadRight(10))
    texto = stbencabezado.ToString
    e.Graphics.DrawString(texto, Fuente, Brocha, X, Y)
    Y = Y + Fuente.GetHeight
    stbencabezado.Length = 0

    stblinea.Append("-", 75)
    texto3 = stblinea.ToString
    e.Graphics.DrawString(texto3, Fuente, Brocha, X, Y)
    Y = Y + Fuente.GetHeight
    stblinea.Length = 0

   For i = 0 To miDt.Rows.Count - 1
     stb.Append(miDt.Rows(i)(0).ToString.PadRight(7))
     stb.Append(miDt.Rows(i)(1).ToString.PadRight(20))
     stb.Append(miDt.Rows(i)(2).ToString.ToUpper.PadRight(20))
     stb.Append(miDt.Rows(i)(3).ToString.PadRight(20))
     stb.Append(miDt.Rows(i)(5).ToString.PadRight(10))
     texto = stb.ToString
     e.Graphics.DrawString(texto, Fuente, Brocha, X, Y)
     Y = Y + Fuente.GetHeight
     stb.Length = 0
   Next
 End Sub
 Private Sub buscar()
   Dim strSQL As String
   Dim miDr As SqlDataReader
   If cargo = True Then
     strSQL = "SELECT * FROM Empleado WHERE " & "codcar='" & _
                         Microsoft.VisualBasic.Left(Me.cboCargo.SelectedItem, 5) & "'"
   Else
     strSQL = "SELECT * FROM Empleado WHERE " & Trim(strcampo) & " LIKE '" & _
                                                      Trim(Me.txtBusqueda.Text) & "%'"
     If txtBusqueda.Text = "" Then
       MsgBox("ingrese el " & oper & " del empleado a buscar")
       txtBusqueda.Focus()
       Exit Sub
     End If
   End If
   Comando = New SqlCommand(strSQL, Conexion)
   Conexion.Open()
   miDt.Clear()
   miDr = Comando.ExecuteReader
   miDt.Load(miDr, LoadOption.OverwriteChanges)
   t = miDt.Rows.Count
   If t > 0 Then
     DataGridView1.DataSource = miDt
     lblMensaje.Text = "Se econtraron " & CStr(t) & " coincidencias"
Docente: José Luis Ponce Segura                      Prac04 (4 de 5)      e-mail: jlponcesg@hotmail.com
Cel. : 952636911                                                                       www.redtacna.net
Universidad Nacional Jorge Basadre Grohmann - ITEL
Carrera: Técnico Analista Programador de Sistemas.                                Curso: Programación Visual .Net II

      Else
        lblMensaje.Text = ("No se econtraron datos....")
        DataGridView1.DataSource = Nothing
      End If
      Conexion.Close()
    End Sub

    Private Sub txtBusqueda_KeyPress(ByVal sender As ....) Handles txtBusqueda.KeyPress
      If e.KeyChar = Chr(13) Then
        buscar()
      End If
    End Sub
    Private Sub VerOpciones(ByVal nc As Boolean)
      lblTitulo.Visible = nc
      txtBusqueda.Visible = nc
      btnBuscar.Visible = nc
      cboCargo.Visible = Not nc
    End Sub
    Private Sub txtBusqueda_TextChanged(ByVal sender...) Handles txtBusqueda.TextChanged
      If txtBusqueda.TextLength > 0 Then
        btnBuscar.Visible = True
      Else
        btnBuscar.Visible = False
      End If
    End Sub
    Function ContarGrilla() As Boolean
      Dim i As Integer
      i = Me.DataGridView1.RowCount
      If i > 0 Then
        Return True
      Else
        Return False
      End If
    End Function
    Private Sub DataGridView1_CellMouseClick(ByVal sender As Object, ByVal e As
                             System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles
                                                             DataGridView1.CellMouseClick
      fil = DataGridView1.CurrentRow.Index
      If DataGridView1.Item(9, fil).Value.ToString = Nothing Then
        PictureBox1.Image = Nothing
      Else
        PictureBox1.Image = System.Drawing.Image.FromFile(DataGridView1.Item(9,
    fil).Value)
      End If
    End Sub
    Private Sub btnSalir_Click(ByVal sender As ....) Handles btnSalir.Click
      Me.Close()
    End Sub


     •   Procedamos a guardar y a ejecutar nuestra aplicación.


TAREA ENCARGADA: ….. / …… / ………….

•    Implemente los formularios correspondientes para Consulta de Clientes, Artículos, Cargo y otros según sea
     necesario y deberá enlazarlos al menú según corresponda
•    Implemente la Búsqueda Avanzada del formulario FrmActualizarEmpleado de la guía de Laboratorio Nº 3,
     de tal manera que muestre el presente formulario y al seleccionar un empleado deberá retornar al formulario
     anterior y mostrar los datos de éste empleado.


Docente: José Luis Ponce Segura                      Prac04 (5 de 5)                 e-mail: jlponcesg@hotmail.com
Cel. : 952636911                                                                                  www.redtacna.net

Más contenido relacionado

PDF
Guía de Laboratorio 1 - VB.NET 2005
PDF
Guia de Laboratorios 2 - VB.NET 2005
PDF
Guia de Laboratorios 3 - VB.NET 2005
PDF
Guia de Laboratorios 5 - VB.NET 2005
PDF
Practica Siete Delphi
PDF
Guia N4 Proyectos Web My Sql Y Php
PDF
Guia de Laboratorios 7 - VB.NET 2005
PDF
Practica Uno Delphi
Guía de Laboratorio 1 - VB.NET 2005
Guia de Laboratorios 2 - VB.NET 2005
Guia de Laboratorios 3 - VB.NET 2005
Guia de Laboratorios 5 - VB.NET 2005
Practica Siete Delphi
Guia N4 Proyectos Web My Sql Y Php
Guia de Laboratorios 7 - VB.NET 2005
Practica Uno Delphi

La actualidad más candente (19)

PDF
Practica Seis Delphi
PDF
Practica Cuatro Delphi
PDF
Guia de Laboratorios 6 - VB.NET 2005
PDF
Guia n1 tam 2009 1
PDF
Curso C M S 03
PDF
Manual poo-unidad-visual-basic
PDF
Guia bootstrap
DOCX
Guía JavaScript
PDF
Guia no3 ado.net
DOCX
Copia de entorno de grado (1)
DOCX
Formulario
PDF
Guia N3 Proyectos Web Php Css, Js
PDF
introduccion al desarrollo de aplicaciones en c#
PDF
Windows forms c# visual basic .net ejercicios
PDF
C6 net beansentradasysalidas
DOCX
Guía Teórica unidad III, Interfaz Gráficas de Usuarios
PDF
Computación 3
DOCX
Proyecto programacion 2.
Practica Seis Delphi
Practica Cuatro Delphi
Guia de Laboratorios 6 - VB.NET 2005
Guia n1 tam 2009 1
Curso C M S 03
Manual poo-unidad-visual-basic
Guia bootstrap
Guía JavaScript
Guia no3 ado.net
Copia de entorno de grado (1)
Formulario
Guia N3 Proyectos Web Php Css, Js
introduccion al desarrollo de aplicaciones en c#
Windows forms c# visual basic .net ejercicios
C6 net beansentradasysalidas
Guía Teórica unidad III, Interfaz Gráficas de Usuarios
Computación 3
Proyecto programacion 2.
Publicidad

Similar a Guia de Laboratorios 4 - VB.NET 2005 (20)

PDF
Guia no4 ado.net
PDF
Guia no3 ado.net
DOCX
3. planteamiento de las actividades y estrategias de aprendizaje
PDF
Control Data
PDF
Guia n5 tam 2009 1
PDF
Conector
DOC
Creacion de formularios en access 2007
PPS
Base de datos
PDF
Guia no2 ado.net
PDF
Tutorial De Proyecto para calcular salario de vacaciones y aguinaldo
PPS
Conexión Base de Datos Access con Visual 2005
PDF
PDF
C:\fakepath\laboratorio nº 2
PDF
PDF
Guia n2 tam 2009 1
DOC
95511389 visual-foxpro-trucos
PDF
Curso online-access-2007-avanzado-lw
PDF
Curso online-access-2007-avanzado-lw
PDF
Curso online Access 2007 avanzado
Guia no4 ado.net
Guia no3 ado.net
3. planteamiento de las actividades y estrategias de aprendizaje
Control Data
Guia n5 tam 2009 1
Conector
Creacion de formularios en access 2007
Base de datos
Guia no2 ado.net
Tutorial De Proyecto para calcular salario de vacaciones y aguinaldo
Conexión Base de Datos Access con Visual 2005
C:\fakepath\laboratorio nº 2
Guia n2 tam 2009 1
95511389 visual-foxpro-trucos
Curso online-access-2007-avanzado-lw
Curso online-access-2007-avanzado-lw
Curso online Access 2007 avanzado
Publicidad

Más de Jose Ponce (19)

PDF
Insertar Videos Youtube en Moodle
PPS
Net1 capitulo iii - estructuras condicionales
PPS
Net1 capitulo ii - variables de memoria & array
PDF
Sesion 1 introduccion a moodle
PPTX
PROYECTO “MEJORAMIENTO DE LA PRODUCCIÓN AGROPECUARIA RECURSOS NATURALES Y MED...
PPS
ADO .NET
PDF
Guia N5 Proyectos Web Consultas Php Y My Sql
PDF
Guia N2 Proyectos Web Php
PDF
Guia N1 Proyectos Web Html
PDF
Practica Tres Delphi
PDF
Practica Dos Delphi
PDF
Practica Cinco Delphi
PDF
Manual de Joomla
PPSX
Proyectos Web 1 Fundamentos
PPSX
Proyectos Web 3 Introduccion Php
PPSX
Proyectos Web 2 Introduccion Html
PDF
Curso Cms 03
PPSX
Curso Cms 2 Sistema De GestióN De Contenidos
PPSX
Curso Cms 1 Fundamentos
Insertar Videos Youtube en Moodle
Net1 capitulo iii - estructuras condicionales
Net1 capitulo ii - variables de memoria & array
Sesion 1 introduccion a moodle
PROYECTO “MEJORAMIENTO DE LA PRODUCCIÓN AGROPECUARIA RECURSOS NATURALES Y MED...
ADO .NET
Guia N5 Proyectos Web Consultas Php Y My Sql
Guia N2 Proyectos Web Php
Guia N1 Proyectos Web Html
Practica Tres Delphi
Practica Dos Delphi
Practica Cinco Delphi
Manual de Joomla
Proyectos Web 1 Fundamentos
Proyectos Web 3 Introduccion Php
Proyectos Web 2 Introduccion Html
Curso Cms 03
Curso Cms 2 Sistema De GestióN De Contenidos
Curso Cms 1 Fundamentos

Último (20)

PDF
COMPLETO__PROYECTO_VIVAN LOS NIÑOS Y SUS DERECHOS_EDUCADORASSOS.pdf
PDF
Breve historia de los Incas -- Patricia Temoche [Temoche, Patricia] -- Breve ...
PDF
La Evaluacion Formativa en Nuevos Escenarios de Aprendizaje UGEL03 Ccesa007.pdf
PDF
Didactica de la Investigacion Educativa SUE Ccesa007.pdf
PDF
OK OK UNIDAD DE APRENDIZAJE 5TO Y 6TO CORRESPONDIENTE AL MES DE AGOSTO 2025.pdf
PDF
Cronograma de clases de Práctica Profesional 2 2025 UDE.pdf
PDF
Escuela de Negocios - Robert kiyosaki Ccesa007.pdf
PDF
Metodologías Activas con herramientas IAG
PDF
IDH_Guatemala_2.pdfnjjjkeioooe ,l dkdldp ekooe
PDF
Punto Critico - Brian Tracy Ccesa007.pdf
PDF
Unidad de Aprendizaje 5 de Matematica 1ro Secundaria Ccesa007.pdf
PDF
Unidad de Aprendizaje 5 de Educacion para el Trabajo EPT Ccesa007.pdf
PDF
Escuela Sabática 6. A través del Mar Rojo.pdf
PDF
Gasista de unidades unifuncionales - pagina 23 en adelante.pdf
PDF
Híper Mega Repaso Histológico Bloque 3.pdf
DOCX
V UNIDAD - SEGUNDO GRADO. del mes de agosto
PDF
Crear o Morir - Andres Oppenheimer Ccesa007.pdf
PDF
Romper el Circulo de la Creatividad - Colleen Hoover Ccesa007.pdf
PDF
SESION 12 INMUNIZACIONES - CADENA DE FRÍO- SALUD FAMILIAR - PUEBLOS INDIGENAS...
PDF
ciencias-1.pdf libro cuarto basico niños
COMPLETO__PROYECTO_VIVAN LOS NIÑOS Y SUS DERECHOS_EDUCADORASSOS.pdf
Breve historia de los Incas -- Patricia Temoche [Temoche, Patricia] -- Breve ...
La Evaluacion Formativa en Nuevos Escenarios de Aprendizaje UGEL03 Ccesa007.pdf
Didactica de la Investigacion Educativa SUE Ccesa007.pdf
OK OK UNIDAD DE APRENDIZAJE 5TO Y 6TO CORRESPONDIENTE AL MES DE AGOSTO 2025.pdf
Cronograma de clases de Práctica Profesional 2 2025 UDE.pdf
Escuela de Negocios - Robert kiyosaki Ccesa007.pdf
Metodologías Activas con herramientas IAG
IDH_Guatemala_2.pdfnjjjkeioooe ,l dkdldp ekooe
Punto Critico - Brian Tracy Ccesa007.pdf
Unidad de Aprendizaje 5 de Matematica 1ro Secundaria Ccesa007.pdf
Unidad de Aprendizaje 5 de Educacion para el Trabajo EPT Ccesa007.pdf
Escuela Sabática 6. A través del Mar Rojo.pdf
Gasista de unidades unifuncionales - pagina 23 en adelante.pdf
Híper Mega Repaso Histológico Bloque 3.pdf
V UNIDAD - SEGUNDO GRADO. del mes de agosto
Crear o Morir - Andres Oppenheimer Ccesa007.pdf
Romper el Circulo de la Creatividad - Colleen Hoover Ccesa007.pdf
SESION 12 INMUNIZACIONES - CADENA DE FRÍO- SALUD FAMILIAR - PUEBLOS INDIGENAS...
ciencias-1.pdf libro cuarto basico niños

Guia de Laboratorios 4 - VB.NET 2005

  • 1. UNJBG ¡¡LÍDER EN CAPACITACIÓN INFORMÁTICA!! ITEL Garantía del proceso Enseñanza-Aprendizaje con las últimas CARRERA tecnologías, con computadoras de última generación, Técnico Analista CURSO impresoras, escáner, multimedia, redes, Internet, material Programador de Programación Visual .NET II didáctico paso a paso, biblioteca y aula virtual con docentes del Sistemas mas alto nivel. GUÍA DE LABORATORIO N° 04 OBJETIVOS: • Listado y/o Consultas utilizando comandos SQL. • Uso de componentes PageSetupDialog, PrintDocument, PrintPreviewdialog, PrintDialog. 1. CREACIÓN DE FORMULARIO PARA CONSULTA DE EMPLEADOS(FrmConsultarEmpleados.vb) Agregue un nuevo formulario a su proyecto y guárdelo con el nombre de FrmConsultarEmpleados.vb • Proceda a agregar los siguientes objetos según se observa a continuación: Importante: Observará Usted en la imagen anterior que se ha agregado 4 componentes nuevos, ellos son: PageSetupDialog, PrintDocument, PrintPreviewDialog y PrintDialog. • Proceda a Establecer las propiedades a c/u de los objetos según el siguiente cuadro. Además deberá establecer otras propiedades para mejorar la apariencia de nuestro formulario. Objeto Propiedad Valor Asignado Form1 Name FrmConsultarEmpleados FormBorderStyle FixedToolWindow ControlBox False Startposition CenterScreen Radiobutton1 Name rbtCodigo Radiobutton2 Name rbtApellidos Radiobutton3 Name rbtNombres Radiobutton3 Name rbtCargo Bimestre Académico : 2009- Docente : José Luis Ponce Segura. Ciclo : V (1 de 5) Fecha : Tacna, Mayo del 2009
  • 2. Universidad Nacional Jorge Basadre Grohmann - ITEL Carrera: Técnico Analista Programador de Sistemas. Curso: Programación Visual .Net II Objeto Propiedad Valor Asignado ComboBox1 Name cboCargo Label1 Name lblTitulo Label2 Name lblMensaje TextBox1 Name txtBusqueda Button1 Text &Imprimir Name btnImprimir Button2 Text &vista Previa Name btnVistaprevia Button3 Text &Conf. Hoja Name btnConfigurarhoja Button4 Text &Salir Name btnSalir • Ahora proceda a escribir el código correspondiente: Option Compare Text Imports System.Data.SqlClient Imports System.Data Imports System.IO Imports System.Text ' Esto va en la sección declaraciones... Dim strcampo, oper As String Dim Comando As SqlCommand Dim t As Integer Dim cargo As Boolean Dim miDt As New DataTable Dim fil As Byte Private Sub FrmConsultarEmpleados_Load(ByVal ….EventArgs) Handles MyBase.Load VerOpciones(True) DataGridView1.ReadOnly = True End Sub Private Sub rbtCodigo_Click(ByVal sender As .......) Handles rbtCodigo.Click, rbtApellidos.Click, rbtNombres.Click, rbtCargo.Click Select Case sender.name Case "rbtCodigo" strcampo = "codemp" oper = " codigo " Case "rbtApellidos" strcampo = " apeemp " oper = " apellido " Case "rbtNombres" strcampo = "nomemp" oper = " nombre " Case "rbtCargo" VerOpciones(False) cboCargo.Items.Clear() LlenarCargos() DataGridView1.DataSource = Nothing cargo = True Exit Sub End Select VerOpciones(True) cargo = False lblTitulo.Text = "ingrese " & oper & " a buscar" DataGridView1.DataSource = Nothing txtBusqueda.Clear() txtBusqueda.Focus() End Sub Docente: José Luis Ponce Segura Prac04 (2 de 5) e-mail: jlponcesg@hotmail.com Cel. : 952636911 www.redtacna.net
  • 3. Universidad Nacional Jorge Basadre Grohmann - ITEL Carrera: Técnico Analista Programador de Sistemas. Curso: Programación Visual .Net II Private Sub LlenarCargos() Dim cm As New SqlCommand("select * from Cargo", Conexion) Dim miDr As SqlDataReader Conexion.Open() miDr = cm.ExecuteReader() While miDr.Read() cboCargo.Items.Add(miDr("codcar") & ": " & miDr("descar")) End While miDr.Close() Conexion.Close() End Sub Private Sub cboCargo_Leave(ByVal sender As ......) Handles cboCargo.Leave cboCargo.Text = "" End Sub Private Sub cboCargo_SelectedIndexChanged(...) Handles cboCargo.SelectedIndexChanged buscar() End Sub Private Sub btnBuscar_Click(ByVal…… System.EventArgs) Handles btnBuscar.Click buscar() End Sub Private Sub btnImprimir_Click(ByVal … System.EventArgs) Handles btnImprimir.Click If ContarGrilla() = False Then MsgBox("No hay datos que imprimir") : Exit Sub With PrintDialog1 'Dialogo de Print .Document = PrintDocument1 .AllowPrintToFile = False .AllowSelection = True .AllowSomePages = True If .ShowDialog() = Windows.Forms.DialogResult.OK Then PrintDocument1.PrinterSettings = .PrinterSettings PrintDocument1.Print() End If End With End Sub Private Sub btnVistaPrevia_Click(ByVal ... EventArgs) Handles btnVistaPrevia.Click If ContarGrilla() = False Then MsgBox("No hay datos que imprimir") : Exit Sub With PrintPreviewDialog1 'Dialogo de Preview .Document = PrintDocument1 .Text = "Lista de Empleados..." .WindowState = FormWindowState.Maximized .ShowDialog() End With End Sub Private Sub btnConfigurarHoja_Click(ByVal…EventArgs) Handles btnConfigurarHoja.Click If ContarGrilla() = False Then MsgBox("No hay datos que imprimir") : Exit Sub With PageSetupDialog1 'Dialogo de Page Setup .Document = PrintDocument1 .ShowDialog() End With End Sub Private Sub PrintDocument1_PrintPage(ByVal ...) Handles PrintDocument1.PrintPage Dim i As Integer Dim stb, stbencabezado, stblinea As New StringBuilder() Dim texto, texto1, texto2, texto3 As String Dim Fuente As New Font("Courier New", 10) Dim Brocha As Brush = Brushes.Blue Dim X As Integer = e.MarginBounds.Left Dim Y As Integer = e.MarginBounds.Top texto1 = "Tacna, " & Now.Date e.Graphics.DrawString(texto1, Fuente, Brocha, e.MarginBounds.Width, Y) Docente: José Luis Ponce Segura Prac04 (3 de 5) e-mail: jlponcesg@hotmail.com Cel. : 952636911 www.redtacna.net
  • 4. Universidad Nacional Jorge Basadre Grohmann - ITEL Carrera: Técnico Analista Programador de Sistemas. Curso: Programación Visual .Net II Y = Y + Fuente.GetHeight * 2 texto2 = "Listado de Empleados" Dim centro As Integer centro = e.MarginBounds.Width / 2 e.Graphics.DrawString(texto2.ToString.ToUpper, Fuente, Brocha, centro, Y) Y = Y + Fuente.GetHeight * 2 'Encabezado de Datos stbencabezado.Append("Código".ToString.PadRight(7)) stbencabezado.Append("Nombres".ToString.PadRight(20)) stbencabezado.Append("Apellidos".ToString.PadRight(20)) stbencabezado.Append("Dirección".ToString.PadRight(20)) stbencabezado.Append("Teléfono".ToString.PadRight(10)) texto = stbencabezado.ToString e.Graphics.DrawString(texto, Fuente, Brocha, X, Y) Y = Y + Fuente.GetHeight stbencabezado.Length = 0 stblinea.Append("-", 75) texto3 = stblinea.ToString e.Graphics.DrawString(texto3, Fuente, Brocha, X, Y) Y = Y + Fuente.GetHeight stblinea.Length = 0 For i = 0 To miDt.Rows.Count - 1 stb.Append(miDt.Rows(i)(0).ToString.PadRight(7)) stb.Append(miDt.Rows(i)(1).ToString.PadRight(20)) stb.Append(miDt.Rows(i)(2).ToString.ToUpper.PadRight(20)) stb.Append(miDt.Rows(i)(3).ToString.PadRight(20)) stb.Append(miDt.Rows(i)(5).ToString.PadRight(10)) texto = stb.ToString e.Graphics.DrawString(texto, Fuente, Brocha, X, Y) Y = Y + Fuente.GetHeight stb.Length = 0 Next End Sub Private Sub buscar() Dim strSQL As String Dim miDr As SqlDataReader If cargo = True Then strSQL = "SELECT * FROM Empleado WHERE " & "codcar='" & _ Microsoft.VisualBasic.Left(Me.cboCargo.SelectedItem, 5) & "'" Else strSQL = "SELECT * FROM Empleado WHERE " & Trim(strcampo) & " LIKE '" & _ Trim(Me.txtBusqueda.Text) & "%'" If txtBusqueda.Text = "" Then MsgBox("ingrese el " & oper & " del empleado a buscar") txtBusqueda.Focus() Exit Sub End If End If Comando = New SqlCommand(strSQL, Conexion) Conexion.Open() miDt.Clear() miDr = Comando.ExecuteReader miDt.Load(miDr, LoadOption.OverwriteChanges) t = miDt.Rows.Count If t > 0 Then DataGridView1.DataSource = miDt lblMensaje.Text = "Se econtraron " & CStr(t) & " coincidencias" Docente: José Luis Ponce Segura Prac04 (4 de 5) e-mail: jlponcesg@hotmail.com Cel. : 952636911 www.redtacna.net
  • 5. Universidad Nacional Jorge Basadre Grohmann - ITEL Carrera: Técnico Analista Programador de Sistemas. Curso: Programación Visual .Net II Else lblMensaje.Text = ("No se econtraron datos....") DataGridView1.DataSource = Nothing End If Conexion.Close() End Sub Private Sub txtBusqueda_KeyPress(ByVal sender As ....) Handles txtBusqueda.KeyPress If e.KeyChar = Chr(13) Then buscar() End If End Sub Private Sub VerOpciones(ByVal nc As Boolean) lblTitulo.Visible = nc txtBusqueda.Visible = nc btnBuscar.Visible = nc cboCargo.Visible = Not nc End Sub Private Sub txtBusqueda_TextChanged(ByVal sender...) Handles txtBusqueda.TextChanged If txtBusqueda.TextLength > 0 Then btnBuscar.Visible = True Else btnBuscar.Visible = False End If End Sub Function ContarGrilla() As Boolean Dim i As Integer i = Me.DataGridView1.RowCount If i > 0 Then Return True Else Return False End If End Function Private Sub DataGridView1_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick fil = DataGridView1.CurrentRow.Index If DataGridView1.Item(9, fil).Value.ToString = Nothing Then PictureBox1.Image = Nothing Else PictureBox1.Image = System.Drawing.Image.FromFile(DataGridView1.Item(9, fil).Value) End If End Sub Private Sub btnSalir_Click(ByVal sender As ....) Handles btnSalir.Click Me.Close() End Sub • Procedamos a guardar y a ejecutar nuestra aplicación. TAREA ENCARGADA: ….. / …… / …………. • Implemente los formularios correspondientes para Consulta de Clientes, Artículos, Cargo y otros según sea necesario y deberá enlazarlos al menú según corresponda • Implemente la Búsqueda Avanzada del formulario FrmActualizarEmpleado de la guía de Laboratorio Nº 3, de tal manera que muestre el presente formulario y al seleccionar un empleado deberá retornar al formulario anterior y mostrar los datos de éste empleado. Docente: José Luis Ponce Segura Prac04 (5 de 5) e-mail: jlponcesg@hotmail.com Cel. : 952636911 www.redtacna.net