laboratorio 4 - vb 2005

5
UNJBG ITEL CARRERA Técnico Analista Programador de Sistemas ¡¡LÍDER EN CAPACITACIÓN INFORMÁTICA!! Garantía del proceso Enseñanza-Aprendizaje con las últimas tecnologías, con computadoras de última generación, impresoras, escáner, multimedia, redes, Internet, material didáctico paso a paso, biblioteca y aula virtual con docentes del mas alto nivel. CURSO Programación Visual .NET II Bimestre Académico : 2009- Docente : José Luis Ponce Segura. Ciclo : V (1 de 5) Fecha : Tacna, Mayo del 2009 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 FormBorderStyle ControlBox Startposition FrmConsultarEmpleados FixedToolWindow False CenterScreen Radiobutton1 Name rbtCodigo Radiobutton2 Name rbtApellidos Radiobutton3 Name rbtNombres Radiobutton3 Name rbtCargo

Upload: joselo27

Post on 12-Nov-2014

990 views

Category:

Documents


2 download

DESCRIPTION

Laboratorios de Visual Basic 2005 - ADO NET

TRANSCRIPT

Page 1: Laboratorio 4 - VB 2005

UNJBG ITEL

CARRERA Técnico Analista Programador de

Sistemas

¡¡LÍDER EN CAPACITACIÓN INFORMÁTICA!! Garantía del proceso Enseñanza-Aprendizaje con las últimas

tecnologías, con computadoras de última generación, impresoras, escáner, multimedia, redes, Internet, material

didáctico paso a paso, biblioteca y aula virtual con docentes del mas alto nivel.

CURSO

Programación Visual .NET II

Bimestre Académico : 2009- Docente : José Luis Ponce Segura. Ciclo : V (1 de 5) Fecha : Tacna, Mayo del 2009

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

FormBorderStyle ControlBox Startposition

FrmConsultarEmpleados FixedToolWindow False CenterScreen

Radiobutton1 Name rbtCodigo Radiobutton2 Name rbtApellidos Radiobutton3 Name rbtNombres Radiobutton3 Name rbtCargo

Page 2: Laboratorio 4 - VB 2005

Universidad Nacional Jorge Basadre Grohmann - ITEL Carrera: Técnico Analista Programador de Sistemas. Curso: Programación Visual .Net II

Docente: José Luis Ponce Segura Prac04 (2 de 5) e-mail: [email protected] Cel. : 952636911 www.redtacna.net

Objeto Propiedad Valor Asignado

ComboBox1 Name cboCargo Label1 Name lblTitulo Label2 Name lblMensaje TextBox1 Name txtBusqueda Button1 Text

Name &Imprimir btnImprimir

Button2 Text Name

&vista Previa btnVistaprevia

Button3 Text Name

&Conf. Hoja btnConfigurarhoja

Button4 Text Name

&Salir 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

Page 3: Laboratorio 4 - VB 2005

Universidad Nacional Jorge Basadre Grohmann - ITEL Carrera: Técnico Analista Programador de Sistemas. Curso: Programación Visual .Net II

Docente: José Luis Ponce Segura Prac04 (3 de 5) e-mail: [email protected] Cel. : 952636911 www.redtacna.net

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)

Page 4: Laboratorio 4 - VB 2005

Universidad Nacional Jorge Basadre Grohmann - ITEL Carrera: Técnico Analista Programador de Sistemas. Curso: Programación Visual .Net II

Docente: José Luis Ponce Segura Prac04 (4 de 5) e-mail: [email protected] Cel. : 952636911 www.redtacna.net

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"

Page 5: Laboratorio 4 - VB 2005

Universidad Nacional Jorge Basadre Grohmann - ITEL Carrera: Técnico Analista Programador de Sistemas. Curso: Programación Visual .Net II

Docente: José Luis Ponce Segura Prac04 (5 de 5) e-mail: [email protected] Cel. : 952636911 www.redtacna.net

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.