Top Banner
Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 163 - PARTE 2 PROGRAMACION ORIENTADA A OBJETOS Marco teorico capitulo 9 clases y objetos del libro de visual basic 2012 USO DEL DIAGRAMADOR DE CLASES PARA IMPLEMENTAR CLASES Y OBJETOS EN VISUAL BASIC 2012 ( VER video) Pasos 1. Ingrese al visual estudio 2102 ,elija aplicación de modo consola y ponga nombre al proyecto como APCIRCULO 2 clic derecho sobre el proyecto Elegir ver diagrama de clases
125

Plsi2015a-3 Clases y Objetos

Feb 02, 2016

Download

Documents

JoselimDurand

lenguaje de programacion
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 163 -

PARTE 2 PROGRAMACION ORIENTADA A OBJETOS

Marco teorico capitulo 9 clases y objetos del libro de visual basic 2012

USO DEL DIAGRAMADOR DE CLASES PARA IMPLEMENTAR CLASES Y OBJETOS EN VISUAL BASIC 2012 ( VER video)Pasos

1. Ingrese al visual estudio 2102 ,elija aplicación de modo consola y ponga nombre al proyecto como APCIRCULO

2 clic derecho sobre el proyecto

Elegir ver diagrama de clases

Page 2: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 164 -

3 Debe aparecer lo siguiente

1. Clic derecho sobre el área de trabajo elegir agregar y luego clase

Page 3: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 165 -

2. Poner el nombre de la clase circulo

3. Al hacer en aceptar aparece los siguiente

Page 4: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 166 -

7 Para agregar atributos a la nueva clase , clic derecho sobre la clase

Se puede agregar uno a uno las propiedades , campos, métodos , eventos, constructores, destructores y constantes

Pero existe otra manera mas rápida de agregar esos atributos8 Para ello clic derecho en la clase y luego detalles de la clase

9. Aparecerá lo siguiente

Page 5: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 167 -

10. Llene esos atributos con los siguientes valores

11.Al presionar enter el diseñador muestra el siguiente código

Public Class CIRCULO Protected Nombre1 As String Protected Area1 As Single Protected Radio1 As Single Public Event Evento1(ByVal Valor As Single) Public Event Evento2(ByVal Valor As Single) Public Sub New(Optional Nombre2 As String = "Sin Nombre", Optional r As Single = 10) End Sub Public Property Nombre As String Get End Get

Page 6: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 168 -

Set(value As String) End Set End Property

Public Property Radio() As Single Get End Get Set(value As Single) End Set End Property

Public ReadOnly Property Area As Single Get End Get End Property

Protected Overrides Sub Finalize() End Sub

''' <summary> ''' Calcula El Area ''' </summary> Function CalcularArea(r1 As Single) As Single

End Function

Public Sub AsignarNombre(Optional Nom1 As String = "Sn")

End Sub

Public Sub MostrarValores()

End Sub

End Class

12. El diagrama de clase seria lo siguiente

Page 7: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 169 -

6. Se puede modificar el código por ejemplo la propiedad Area es de solo lectura

13. Agregar la clase cilindro

Page 8: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 170 -

14. Ponga los siguientes valores

15 . El código generado es

Public Class CILINDRO Private Altura1 As Single Private Volumen1 As Single Public Sub New(Optional Nombre2 As String = "SN", Optional r As Single = 10, Optional h1 As Single = 1) End Sub

Public Property Altura As Single Get End Get Set(value As Single) End Set End Property

Public ReadOnly Property Volumen As Single Get End Get End Property

Public Function CalcularVolumen(v1 As Single) As Single End Function Public Sub MostrarValores() End SubEnd Class

Page 9: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 171 -

16. Se puede modificar el código por ejemplo la propiedad volumen es de solo lectura

Public ReadOnly Property Volumen As Single Get End Get End Property

17. El diagrama de la clase cilindro de seria lo siguiente

18 Para crear la herencia use la herramientas de herenciaSi no se muestra la herramienta hacer clic

Page 10: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 172 -

19.arrastre del cilindro al circuloAparece lo siguiente

20 El código de la clase cilindro se modifica a

Page 11: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 173 -

21 Crear la interface ( la interface es una nueva clase )

22 Arrastre el interface y agregue uno nuevo

Page 12: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 174 -

e

23 Con la herramienta de la herencia agrega las clases circulo y al método nombre al final la estructura debe quedar de la siguiente manera

Para implementar una interfaz trazando una línea de herencia1. En el diagrama de clases, muestre la interfaz y la clase que implementará la

interfaz.2. Trace una línea de herencia desde la clase a la interfaz.

Y debe aparece lo siguiente

24. El código de la clase Interface es lo siguiente

Public Interface ICirculo

End Interface

25. el Nuevo código de la clase circulo es

Page 13: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 175 -

IMPLEMENTAR LA CLASE CIRCULO CON EVENTOS se muestra el siguiente codigoImplementar dos eventos para la clasecírculoEvento 1. Sedispara cuandoel radio es negativoEvento 2 Se dispara cuando el radio es mayor que 100

En el explorador de soluciones se puede ver todos los componetes de esas dos clases

Page 14: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 176 -

Complete con el siguiente códigoCLASE CIRCULOPublic Class CIRCULO Protected Nombre1 As String Protected Area1 As Single Protected Radio1 As Single Public Event Evento1(ByVal Valor As Single) Public Event Evento2(ByVal Valor As Single) Public Sub New(Optional Nombre2 As String = "Sin Nombre", Optional r As Single = 10) Nombre1 = Nombre2 Radio = r End Sub Public Property Nombre As String Get Nombre = Nombre1 End Get Set(value As String) Nombre1 = value End Set End Property Public Property Radio() As Single Get Radio = Radio1 End Get Set(value As Single) Select Case value Case Is < 0 RaiseEvent Evento1(value) Case CSng(value > 0) To 100 Radio1 = value Case Is > 100 RaiseEvent Evento2(value) End Select End Set End Property Public ReadOnly Property Area As Single Get Area = Area1 End Get End Property

Protected Overrides Sub Finalize() Console.WriteLine("objeto destruido") End Sub ''' <summary> ''' Calcula El Area ''' </summary> Function CalcularArea(r1 As Single) As Single Area1 = Math.PI * Math.Pow(r1, 2) Return Area1 End Function

Page 15: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 177 -

Public Sub AsignarNombre(Optional Nom1 As String = "Sn") Nombre1 = Nom1 End Sub Public Function ObtenerValores() As String Dim Cadena As String = "" Area1 = CalcularArea(Radio1) Cadena = "Nombre =" + Nombre1 + " Radio = " + Str(Radio1) + " Area " + Str(Area1) Return Cadena End FunctionEnd Class

CLASE CILINDRO

Public Class CILINDRO Inherits CIRCULO ' Implements ICIRCULO Private Altura1 As Single Private Volumen1 As Single Public Sub New(Optional Nombre2 As String = "SN", Optional r As Single = 10, Optional h1 As Single = 1) MyBase.New(Nombre2, r) Altura1 = h1 End Sub Public Property Altura As Single Get Altura = Altura1 End Get Set(value As Single) Altura1 = value End Set End Property Public ReadOnly Property Volumen As Single Get Volumen = Volumen1 End Get End Property Public Function CalcularVolumen(v1 As Single) As Single Area1 = CalcularArea(Radio1) Volumen1 = Area * Altura1 Return Volumen1 End Function Public Function ObtenerValores() As String Dim Cadena As String Cadena = MyBase.ObtenerValores() Volumen1 = CalcularVolumen(Altura1) Cadena = Cadena + "Alt = " & Altura1 & "Vol = " & Volumen1 Return Cadena End FunctionEnd ClassPara que funcione la aplicacion hay que poner el código(proyecto agregar modulo)

Page 16: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 178 -

CODIGO DEL MODULO 1

Module Module1 Dim objeto1 As CIRCULO Dim objeto2 As CILINDRO Dim WithEvents Objeto3 As CIRCULO Dim WithEvents Objeto4 As CILINDRO Sub Main() objeto1 = New CIRCULO("CIRCULO1", 10) objeto2 = New CILINDRO("CILINDRO2", 10, 1) Objeto3 = New CIRCULO(10) Objeto4 = New CILINDRO() Console.WriteLine(" Objeto1 {0}", objeto1.ObtenerValores()) Console.WriteLine(" Objeto2 {0}", objeto2.ObtenerValores()) Console.WriteLine(" Objeto3 {0}", Objeto3.ObtenerValores()) Console.WriteLine(" Objeto4 {0}", Objeto4.ObtenerValores()) Objeto4.AsignarNombre("C4") Objeto4.Radio = 100 Console.WriteLine(" Result de Objeto4 {0}", Objeto4.ObtenerValores()) Objeto3.Radio = -4 ' provoca el evento 1 Objeto3.Radio = 200 ' provoca el evento 2 Objeto3.Radio = 30 ' no provoca ningun evento Objeto4.Radio = -4 ' provoca el evento 1 Objeto4.Radio = 200 ' provoca el evento 2 Objeto4.Radio = 30 ' no provoca ningun evento Console.ReadLine() End Sub Private Sub Ecirculo_Evento1(valor As Single) Handles Objeto3.Evento1 Console.WriteLine("{0} no se permite radios negativos", valor) End Sub Private Sub Ecirculo_Evento2(ByVal Valor As Single) Handles Objeto3.Evento2 Console.WriteLine("{0} no se permite valores superiores a 100", Valor) End Sub Private Sub Ecilindro_Evento1(valor As Single) Handles Objeto4.Evento1 Console.WriteLine("{0} no se permite radios negativos", valor) End Sub Private Sub ECilindro_Evento2(ByVal Valor As Single) Handles Objeto4.Evento2 Console.WriteLine("{0} no se permite valores superiores a 100", Valor) End SubEnd Module

Inteligence sense

Page 17: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 179 -

CLASES CON CONSTRUCTORES

7 Agregue el siguiente constructor a la clase circuloPublic Sub New(Optional ByVal r As Integer = 10) Radio = rEnd Sub

Declarar 100 objetos de tipos circuloTarea

1 Se tiene la clase factorial derivar la clase combinatoria,implemente su propeidades y métodos de cada clase

2. Se ingresa código y nombres de n alumnos usando POO elabore una aplicación que permita ingresar, mostrar, datos, buscar, grabar, recuperar datos, etc.

3. Implemente una clase llamada estadística que deberá tener los siguiente miembros

PropiedadesN: Número de datos ( propiedad de lectura y escrituraSuma, promedio, mediana, moda , mayor, menor desviacion tipica etc.( propiedades de solo lectura

MétodosIngresar. permite ingresar n datos a un arregloProcesar. Procesa y encuentra los valores de Suma, promedio,mediana, moda, el

mayor , el menor , desviación tipica, etc

9.10 PROGRAMACION ORIENTADA A OBJETOS EN PROGRAMACION VISUAL

1. En el mismo proyecoto Agregar \ Windows Formngrese a File New Proyect\Windows aplicacation

2. Aparecera el siguiente cuadro ponga de nombre PROBARCIRCULOPara ello agregue

Page 18: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 180 -

3.en proyecto en propiedades del proyeto configure proyecto inicial el formulario

Los componentes del proyecto seria

3 Puede ver los conponentes de la clase Circulo F2

Page 19: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 181 -

6 Diseñe en el formulario lo siguiente

6 continuación proceda a establecer las propiedades según se indica:

Objeto Propiedad ValorForm1 Text Propiedades metodos y eventos clase circulo.Datagridview1

Text Radio

Page 20: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 182 -

Texbox1 name txtResultadoGroupBox1 Text CIRCULOGroupBox2 Text CILINDRORadioButton1 Nombre rbCirculoObtenerRadioButton2 Nombre rbCirculoMostrarRadioButton3 Nombre rbCilindroObtenerRadioButton4 Nombre rbCilindroMostrar

7 Grabe con el nombre de circulo

9 Escriba el siguiente codigo en el formulario

Public Class Form1 Public Class Form1 Private WithEvents ObjetoCirculo As CIRCULO Private WithEvents ObjetoCilindro As CILINDRO Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load With Me.DataGridView1.DefaultCellStyle .Font = New Font("Tahoma", 15) .ForeColor = Color.Blue .BackColor = Color.Beige .SelectionForeColor = Color.Yellow .SelectionBackColor = Color.Black End With DataGridView1.ColumnCount = 2 DataGridView1.RowCount = 3 DataGridView1.Columns(0).HeaderText = "Propiedad " DataGridView1.Columns(1).HeaderText = "Valor " DataGridView1.Rows(0).Cells(0).Value = "Nombre" DataGridView1.Rows(0).Cells(1).Value = "SN"

DataGridView1.Rows(1).Cells(0).Value = "Radio" DataGridView1.Rows(1).Cells(1).Value = 10 DataGridView1.Rows(2).Cells(0).Value = "Altura" DataGridView1.Rows(2).Cells(1).Value = 1 ObjetoCirculo = New CIRCULO("CIRCULO", 10) ObjetoCilindro = New CILINDRO("CILINDRO", 10, 1) End Sub

Private Sub RbCirculoObtener_CheckedChanged(sender As Object, e As EventArgs) Handles RbCirculoObtener.CheckedChanged ObjetoCirculo.Nombre = DataGridView1.Rows(0).Cells(1).Value ObjetoCirculo.Radio = DataGridView1.Rows(1).Cells(1).Value End Sub

Page 21: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 183 -

Private Sub RbCirculoMostrar_CheckedChanged(sender As Object, e As EventArgs) Handles RbCirculoMostrar.CheckedChanged TxtResultado.Text = ObjetoCirculo.ObtenerValores End Sub Private Sub rbCilindroObtener_CheckedChanged(sender As Object, e As EventArgs) Handles rbCilindroObtener.CheckedChanged ObjetoCilindro.Nombre = DataGridView1.Rows(0).Cells(1).Value ObjetoCilindro.Radio = DataGridView1.Rows(1).Cells(1).Value ObjetoCilindro.Altura = DataGridView1.Rows(2).Cells(1).Value End Sub

Private Sub rbCilindroMostrar_CheckedChanged(sender As Object, e As EventArgs) Handles rbCilindroMostrar.CheckedChanged TxtResultado.Text = ObjetoCilindro.ObtenerValores End Sub

Private Sub ProcedimientoobjetoCirculo(ByVal Valor As Single) Handles ObjetoCirculo.Evento1, ObjetoCilindro.Evento1 MsgBox(" no se permite radios negativos", MsgBoxStyle.MsgBoxHelp, Valor.ToString) End Sub Private Sub ProcedimientoObjetoCilindro(ByVal Valor As Single) Handles ObjetoCirculo.Evento2, ObjetoCilindro.Evento2 MsgBox(" el radio debe ser menor que o igual que 100 ", MsgBoxStyle.Critical, Valor.ToString) End SubEnd Class

Al ingresar un de radio superior a 100 se dispara el evento 2 y si es le radio es negativo se disparar el evento 1

9.11 ARREGLO DE OBJETOS

14 Modifique la clase Form1 para que trabaje con arreglo de objetos

Page 22: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 184 -

+Agregue el siguiente codigo al boton propiedades

Private Sub btnPropiedades_Click(sender As Object, e As EventArgs) Handles btnPropiedades.Click Dim i As Integer Dim A(10) As CIRCULO ListBox1.Items.Clear() For i = 0 To 9 A(i) = New CIRCULO("Circulo " & i) A(i).Radio = i * 10 ListBox1.Items.Add("Objeto " & A(i).Nombre) ListBox1.Items.Add("Radio " & A(i).Radio) Next A(0).Radio = Val(Txtradio.Text) txtArea.Text = A(0).Area End SubELABORACION DE CONTROL DE USUARIO EN VISUAL ESTUDIO 2012( o controles personalizados)

Paso 1

Agregue un con control de usuario con

Page 23: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 185 -

Paso 2Diseñe el siguiente formulario

1. Implemente el siguiente código

Public Class UCirculo Protected Nombre1 As String Protected Area1 As Single Protected Radio1 As Single Public Event Evento1(ByVal Valor As Single)

Page 24: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 186 -

Public Event Evento2(ByVal Valor As Single) Public Property Nombre As String Get Nombre = Nombre1 End Get Set(value As String) Nombre1 = value End Set End Property Public Property Radio() As Single Get Radio = Radio1 End Get Set(value As Single) Select Case value Case Is < 0 RaiseEvent Evento1(value) Case CSng(value > 0) To 100 Radio1 = value Case Is > 100 RaiseEvent Evento2(value) End Select End Set End Property Public ReadOnly Property Area As Single Get Area = Area1 End Get End Property Function CalcularArea(r1 As Single) As Single Area1 = Math.PI * Math.Pow(r1, 2) Return Area1 End Function Public Sub AsignarNombre(Optional Nom1 As String = "Sn") Nombre1 = Nom1 End Sub Private Sub btnCalcular_Click(sender As Object, e As EventArgs) Handles btnCalcular.Click If IsNumeric(txtRadio.Text) Then Radio = txtRadio.Text Area1 = CalcularArea(Radio) txtArea.Text = Area1 Else MsgBox("INGRESE VALORES NUMERICOS") End If End Sub Private Sub UCirculo_Load(sender As Object, e As EventArgs) Handles MyBase.Load txtRadio.Text = Radio End SubEnd Class

Page 25: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 187 -

Paso 4 . Ejecute la aplicacion

Para crear un control de usuario mediante Visual Basic Express (2012)1. En el menú Archivo, haga clic en Nuevoproyecto.2. En el panel Plantillas, del cuadro de diálogo Nuevo proyecto, haga clic

en Biblioteca de clases y luego en Aceptar.3. En el menú Proyecto, haga clic en Agregar control de usuario.4. En el cuadro de diálogo Agregar nuevo elemento, seleccione Control de usuario.5. En el cuadro Nombre, escriba NamesControl y haga clic en Agregar.

Paso 5 generar la aplicacion

Paso 6 iniciar Nuevo proyecto para probarlos

Page 26: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 188 -

Paso 7 en la barra de herramienta escoja elegir elemento

8 Escoja el botón examinar

Page 27: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 189 -

8 Buscar el archivo .dll generado

9 Seleccionar y abrir

Page 28: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 190 -

10 . el control ya aparece en la barra de herramientas

Cree dos objetos circulo Como se muestra

Page 29: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 191 -

Y AGREGUE EL siguiente código

Public Class Form1 Private Sub Circulo_Evento1(ByVal Valor As Single) Handles UCirculo1.Evento1, UCirculo2.Evento1 MsgBox("radio negativo " & Valor) Me.BackColor = Color.AliceBlue End Sub Private Sub Circulo_Evento2(ByVal Valor As Single) Handles UCirculo1.Evento2, UCirculo2.Evento2 MsgBox("radio mayor que el maximo " & Valor) Me.BackColor = Color.Green End Sub Private Sub Circulo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UCirculo1.Load Me.BackColor = Color.Gray End SubEnd Class

11. puede ver las propiedades metodos y eventos del objeto usuario1 del tipo circulo

Page 30: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 192 -

EJEMPLOS DE CLASES Y OBJETOS EN VISUAL BASIC 2012TAREA.- Defina la clase Operacion que tiene los siguientes miembros

PropiedadesNro1: Propiedad para modificar el primer númeroNro2: propiedad para modificar el segundo nueúmero cilindroRes: resultado de la operación propiedad de solo lectura

MétodosIngresar : permite ingresar dos números realesSumar.- función que permite sumar los números ingresadosRestar.- función que permite restar los números ingresados

Option Explicit OnOption Strict OnPublic Class OPERACION Private N1 As Single Private N2 As Single Private R As Single Public Sub Ingresar() Console.Write("ingrese nro 1") N1 = CSng(Console.ReadLine) Console.Write("ingrese nro 2") N2 = CSng(Console.ReadLine) End Sub

Public Function Sumar() As Single R = N1 + N2 Return R End Function Public Function Restar() As Single R = N1 - N2 Return R End Function Property Nro1() As Single Get Return N1 End Get Set(ByVal value As Single) N1 = CSng(value) End Set End Property Property Nro2() As Single Get Return N2 End Get Set(ByVal value As Single) N2 = CSng(value) End Set End Property

Public ReadOnly Property Res() As Single

Page 31: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 193 -

Get Return R End Get End PropertyEnd Class

Código del módulo

Option Explicit OnOption Strict OnModule Module1 Dim objeto As OPERACION Sub Main() objeto = New OPERACION objeto.Ingresar() Console.WriteLine(" la suma es {0}", objeto.Sumar()) Console.WriteLine(" la resta es {0}", objeto.Restar()) objeto.Nro1 = 100 objeto.Sumar() Console.WriteLine(" El resultado es {0}", objeto.Res) Console.ReadLine() End SubEnd Module

El objeto llamado Operación debería tener los siguientes métodos y propiedades

EJEMPLOS REALIZADOS EL SEMESTRE ANTERIOR 2014 (MEJORADO)

PRACTICAS DEL LUNES 2 DE JUNIO DEL 2014Clase CuentaDiagram de clases

Page 32: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 194 -

CuentaClase

Campos

monto1

ncuenta1

propCuenta1

saldo1

tasa1

Propiedades

ncuenta

propcuenta

saldo

tasa

Métodos

Deposito

New

Retiro

Solucion

CODIGO CLASE CUENTA

Public Class Cuenta Protected ncuenta1 As String Protected tasa1 As Single Protected saldo1 As Single Protected monto1 As Single Protected propCuenta1 As String

Public Property ncuenta As Integer Get ncuenta = ncuenta1 End Get Set(value As Integer) ncuenta1 = value End Set End Property

Page 33: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 195 -

Public Property propcuenta As String Get propcuenta = propCuenta1 End Get Set(value As String) propCuenta1 = value

End Set End Property Sub New(Optional ncuenta2 As String = "sn", Optional propCuenta2 As String = "fulano", Optional saldo2 As Single = 0) propCuenta1 = propCuenta2 ncuenta1 = ncuenta2 saldo1 = saldo2 End Sub

Public ReadOnly Property saldo As Single Get saldo = saldo1 End Get End Property

Public Property tasa As Integer Get tasa = tasa1 End Get Set(value As Integer) tasa1 = value End Set End Property Sub Retiro() Console.Write(" monto a retirar") monto1 = Console.ReadLine saldo1 = saldo1 - monto1 End Sub Sub Deposito() Console.Write(" monto a Depositar") monto1 = Console.ReadLine saldo1 = saldo1 + monto1 End SubEnd Class

CODIGO DEL MODULO

Module Module1 Dim n As Integer Dim i, ncliente As Integer Dim Clientes(5) As Cuenta Sub Main() n = 3 For i = 0 To n - 1

Page 34: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 196 -

Clientes(i) = New Cuenta(i, "Cliente " & i + 1) Next For i = 0 To n - 1 Console.WriteLine("Ncuenta = {0} cliente {1} saldo {2} ", Clientes(i).ncuenta, Clientes(i).propcuenta, Clientes(i).saldo) Next Console.Write("ingrese el nro de cliente {0} a {1}", 0, n - 1) ncliente = CInt(Console.ReadLine()) Clientes(ncliente).Deposito() For i = 0 To n - 1 Console.WriteLine("Ncuenta = {0} cliente {1} saldo {2} ", Clientes(i).ncuenta, Clientes(i).propcuenta, Clientes(i).saldo) Next Console.ReadLine() End SubEnd Module

CLASES DE SI 18 AS 20 HORAS

Public Class PERSONA Protected Nombre As String Protected DNI As Integer Sub ingresar() Console.Write(" ingrese nombre") Nombre = Console.ReadLine Console.Write(" ingrese DNI") DNI = Console.ReadLine End Sub Sub VerDatos() Console.WriteLine(" Nombre {0}", Nombre) Console.WriteLine(" DNI {0}", DNI) End SubEnd ClassModule Module1 Dim Juan As PERSONA Sub Main() Juan = New PERSONA Juan.ingresar() Juan.VerDatos() Console.ReadLine() End SubEnd Module

Ejercicios clases con constructores

Public Class PERSONA Protected Nombre As String Protected DNI As Integer Public Sub New(Optional ByVal nombre1 As String = "sin nombre", Optional Dn1 As Integer = 11111) Nombre = nombre1 DNI = Dn1

Page 35: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 197 -

End Sub Sub ingresar() Console.Write(" ingrese nombre") Nombre = Console.ReadLine Console.Write(" ingrese DNI") DNI = Console.ReadLine End Sub Sub VerDatos() Console.WriteLine(" Nombre {0}", Nombre) Console.WriteLine(" DNI {0}", DNI) End SubEnd ClassModule Module1 Dim Juan, Pedro, Maria As PERSONA Sub Main() Juan = New PERSONA Pedro = New PERSONA("Pedro Picapiedra") Maria = New PERSONA(" Maria Parado", 234567) Juan.VerDatos() Pedro.VerDatos() Maria.VerDatos() Console.ReadLine() End SubEnd Module

Ejecicio con propiedades

Option Explicit OnOption Strict OnPublic Class PERSONA Protected Nombre1 As String Protected DNI1 As Integer Property Nombre() As String Get Nombre = Nombre1 End Get Set(value As String) Nombre1 = value End Set End Property Property DNI() As Integer Get DNI = DNI1 End Get

Page 36: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 198 -

Set(value As Integer) DNI1 = value End Set End Property Public Sub New(Optional ByVal nombre1 As String = "sin nombre", _ Optional Dn1 As Integer = 11111) Nombre = nombre1 DNI1 = Dn1 End Sub Sub ingresar() Console.Write(" ingrese nombre") Nombre = Console.ReadLine Console.Write(" ingrese DNI") DNI = CInt(Console.ReadLine) End Sub Sub VerDatos() Console.WriteLine(" Nombre {0}", Nombre) Console.WriteLine(" DNI {0}", DNI) End SubEnd ClassOption Explicit OnOption Strict OnModule Module1 Dim Juan, Pedro, Maria As PERSONA Sub Main() Juan = New PERSONA Pedro = New PERSONA("Pedro Picapiedra") Maria = New PERSONA(" Maria Parado", 234567) Juan.DNI = 9999 Pedro.VerDatos() Maria.VerDatos() Juan.VerDatos() Console.ReadLine() End SubEnd Module

CLASES Y OBJETOS CON ARREGLOS

Public Class PERSONA Protected Nombre1 As String

Page 37: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 199 -

Protected DNI1 As Integer Property Nombre() As String Get Nombre = Nombre1 End Get Set(value As String) Nombre1 = value End Set End Property Property DNI() As Integer Get DNI = DNI1 End Get Set(value As Integer) DNI1 = value End Set End Property Public Sub New(Optional ByVal nombre1 As String = "sin nombre", _ Optional Dn1 As Integer = 11111) Nombre = nombre1 DNI1 = Dn1 End Sub Sub ingresar() Console.Write(" ingrese nombre") Nombre = Console.ReadLine Console.Write(" ingrese DNI") DNI = CInt(Console.ReadLine) End Sub Sub VerDatos() Console.WriteLine(" Nombre {0}", Nombre) Console.WriteLine(" DNI {0}", DNI) End SubEnd ClassModule Module1

Sub Main() Dim i As Integer Dim n As Integer = 4 Dim A(10) As PERSONA For i = 0 To n - 1 A(i) = New PERSONA("P" & i, i) Next Console.WriteLine(" los objetos creado son") For i = 0 To n - 1 A(i).VerDatos() Next Console.ReadLine() End SubEnd Module

Modificar un elemento del arreglo de objetos

Page 38: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 200 -

jeto

Module Module1 Sub Main() Dim i As Integer, np As Integer Dim n As Integer = 4 Dim A(10) As PERSONA For i = 0 To n - 1 A(i) = New PERSONA("P" & i, i) Next Console.WriteLine(" los objetos creado son") For i = 0 To n - 1 A(i).VerDatos() Next Console.WriteLine("INGRESE EL NRO A A MODIFICAR {0} a {1} ", 0, n - 1) np = Console.ReadLine A(np).ingresar() Console.WriteLine(" los objetos modificados son") For i = 0 To n - 1 A(i).VerDatos() Next Console.ReadLine() End SubEnd Module

Implementacion de eventos

Option Explicit OnOption Strict On

Page 39: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 201 -

Public Class PERSONA Public Event Evento1(ByVal Valor As Single) Public Event Evento2(ByVal Valor As Single)

Protected Nombre1 As String Protected DNI1 As Integer Property Nombre() As String Get Nombre = Nombre1 End Get Set(value As String) Nombre1 = value End Set End Property Property DNI() As Integer Get DNI = DNI End Get Set(value As Integer) Select Case value Case Is < 0 RaiseEvent Evento1(value) Case CInt(value > 0) To 999999 DNI1 = value Case Is > 1000000 RaiseEvent Evento2(value) End Select End Set End Property Public Sub New(Optional ByVal nX As String = "sin nombre", _ Optional Dn1 As Integer = 11111) Nombre1 = nX DNI1 = Dn1 End Sub Sub ingresar() Console.Write(" ingrese nombre") Nombre = Console.ReadLine Console.Write(" ingrese DNI") DNI = CInt(Console.ReadLine) End Sub Sub VerDatos() Console.WriteLine(" Nombre {0}", Nombre) Console.WriteLine(" DNI {0}", DNI) End SubEnd ClassModule Module1 Private WithEvents Objeto As PERSONA Sub Main() Objeto = New PERSONA() Objeto.DNI = -40 ' provoca el evento 1 Objeto.DNI = 2000000000 ' provoca el evento 2

Page 40: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 202 -

Objeto.DNI = 300 ' no provoca ningun evento Console.WriteLine("dni {0} ", Objeto.DNI) Console.ReadLine() End Sub

Private Sub Evento1(ByVal Valor As Single) Handles Objeto.Evento1 Console.WriteLine("{0} no se permite dni ", Valor) ' MsgBox("no se permite dni negativo " & Valor) End Sub Private Sub Ecirculo_Evento2(ByVal Valor As Single) Handles Objeto.Evento2 Console.WriteLine("{0} no se permite valores superiores a 1000000", Valor) End Sub End Module

CLASE PERSONA

Public Class PERSONA Public Event Evento1(ByVal Valor As Single) Public Event Evento2(ByVal Valor As Single) Protected Nombre1 As String Protected DNI1 As Integer Property Nombre() As String Get Nombre = Nombre1 End Get Set(value As String) Nombre1 = value End Set End Property Property DNI() As Integer Get DNI = DNI End Get Set(value As Integer) Select Case value Case Is < 0 RaiseEvent Evento1(value) Case CInt(value > 0) To 999999 DNI1 = value Case Is > 1000000 RaiseEvent Evento2(value) End Select End Set End Property Public Sub New(Optional ByVal nX As String = "sin nombre", _ Optional Dn1 As Integer = 11111) Nombre1 = nX DNI1 = Dn1 End Sub Sub ingresar() Console.Write(" ingrese nombre")

Page 41: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 203 -

Nombre = Console.ReadLine Console.Write(" ingrese DNI") DNI = CInt(Console.ReadLine) End Sub Sub VerDatos() Console.WriteLine(" Nombre {0}", Nombre) Console.WriteLine(" DNI {0}", DNI) End SubEnd Class

Module Module1 Private WithEvents Objeto As PERSONA Sub Main() Objeto = New PERSONA() Objeto.DNI = -40 ' provoca el evento 1 Objeto.DNI = 2000000000 ' provoca el evento 2 Objeto.DNI = 300 ' no provoca ningun evento Console.WriteLine("dni {0} ", Objeto.DNI) Console.ReadLine() End Sub

Private Sub Evento1(ByVal Valor As Single) Handles Objeto.Evento1 Console.WriteLine("{0} no se permite dni ", Valor) ' MsgBox("no se permite dni negativo " & Valor) End Sub Private Sub Ecirculo_Evento2(ByVal Valor As Single) Handles Objeto.Evento2 Console.WriteLine("{0} no se permite valores superiores a 1000000", Valor) End SubEnd Module

PRACTICA DEL MIERCOLES 28 DE MAYO DEL 2014CLASE VEHICULOS

Public Class Vehiculo Protected placa As String Protected propietario As String Protected año As String Sub IngresarDatos() Console.Write("Ingrese Placa") placa = Console.ReadLine Console.Write("Ingrese Propietario") propietario = Console.ReadLine

Page 42: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 204 -

Console.Write("Ingrese Año") año = Console.ReadLine End Sub Sub VerDatos() Console.WriteLine("Placa {0} Propietario {1} Año {2} ", placa, propietario, año) End Sub Sub Encender() Console.WriteLine(" Carro Encedido") End Sub Sub Apagar() Console.WriteLine(" Carro APAGADO") End SubEnd ClassModule Module1 Dim carro As Vehiculo Sub Main() carro = New Vehiculo carro.IngresarDatos() carro.VerDatos() carro.Encender() carro.Apagar() Console.ReadLine() End SubEnd Module

Public Class Vehiculo Protected placa As String Protected propietario As String Protected año As Integer Public Sub New(Optional ByVal placa2 As String = "sin placa", Optional ByVal pro2 As String = "sin dueño", Optional ByVal año2 As Integer = 0) placa = placa2 propietario = pro2 año = año2 End Sub

Sub IngresarDatos() Console.Write("Ingrese Placa") : placa = Console.ReadLine Console.Write("Ingrese Propietario") : propietario = Console.ReadLine Console.Write("Ingrese Año") : año = Console.ReadLine End Sub Sub VerDatos() Console.WriteLine("Placa {0} Propietario {1} Año {2} ", placa, propietario, año) End Sub Sub Encender()

Page 43: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 205 -

Console.WriteLine(" Carro Encedido") End Sub Sub Apagar() Console.WriteLine(" Carro APAGADO") End SubEnd ClassModule Module1 Dim CJuan, CPedro, CLuis, Cmaria As Vehiculo Sub Main() CJuan = New Vehiculo CPedro = New Vehiculo("Wq33") CLuis = New Vehiculo("XX", "pedro") Cmaria = New Vehiculo("CCC", "MAria", 2014) CJuan.VerDatos() CPedro.VerDatos() Cmaria.VerDatos() CLuis.VerDatos() Console.ReadLine() End SubEnd Module

Public Class Vehiculo Protected placa1 As String Protected propietario1 As String Protected año1 As Integer Public Sub New(Optional ByVal placa2 As String = "sin placa", Optional ByVal pro2 As String = "sin dueño", _ Optional ByVal año2 As Integer = 0) placa1 = placa2 propietario1 = pro2 año1 = año2 End Sub Public Property propietario() As String Get propietario = propietario1 End Get Set(ByVal value As String) propietario1 = value End Set End Property Sub IngresarDatos() Console.Write("Ingrese Placa") : placa = Console.ReadLine Console.Write("Ingrese Propietario") : propietario = Console.ReadLine Console.Write("Ingrese Año") : año = Console.ReadLine End Sub Sub VerDatos() Console.WriteLine("Placa {0} Propietario {1} Año {2} ", placa, propietario, año) End Sub Sub Encender() Console.WriteLine(" Carro Encedido") End Sub Sub Apagar() Console.WriteLine(" Carro APAGADO")

Page 44: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 206 -

End SubEnd Class

Module Module1 Dim DUEÑOS(100) As Vehiculo Sub Main() Dim n = 100, i As Integer For i = 0 To n - 1 DUEÑOS(i) = New Vehiculo("A" & i, "Dueño " & i, 0) Next For i = 0 To n - 1 DUEÑOS(i).VerDatos() Next DUEÑOS(4).propietario = "juan perez" Console.ReadLine() End SubEnd Module

CLASE ESTADISTICA

Public Class ESTADISTICA Private i As Integer Protected N As Integer Protected datos(10) As Integer Protected media As Single Protected desviacion As Single Sub IngresarDatos() Console.Write(" cantidad de datos ") N = Console.ReadLine Console.Write("ingrese {0} datos ", N) Console.WriteLine() For i = 0 To N - 1 datos(i) = Console.ReadLine Next End Sub Sub MostrarDatos() Console.WriteLine(" los datos del objeto son ") For i = 0 To N - 1 Console.Write(" {0} ", datos(i)) Next Console.WriteLine() End Sub Public Sub New(Optional ByVal n2 As Integer = 3) N = n2 For i = 0 To N - 1 datos(i) = i + 1 Next End SubEnd Class

Module Module1 Dim Objeto1, objeto2 As ESTADISTICA

Page 45: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 207 -

Sub Main() Objeto1 = New ESTADISTICA objeto2 = New ESTADISTICA(2) Objeto1.MostrarDatos() objeto2.MostrarDatos() Console.ReadLine() End SubEnd Module

Diagrama de clases

SOLUCIONES DE EXAMENESGRUPO1 Lunes de 16 a 18 horas

Public Class Form1

Page 46: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 208 -

Private Sub AgregarEmpleadoToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles AgregarEmpleadoToolStripMenuItem.Click Form2.ShowDialog() End SubEnd Class

Public Class Form2 Dim cont As Integer = 0 Dim tg As Integer = 0 Dim te As Integer = 0 Dim Top As Integer = 0 Dim tsueldo As Single = 0

Private Sub Form2_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load TxtNombre.Enabled = False TxtSueldo.Enabled = False CboCargo.Enabled = False DataGridView1.ColumnCount = 4 DataGridView1.Columns(0).HeaderText = "Nombre y Apellidos" DataGridView1.Columns(1).HeaderText = "Fecha Nac" DataGridView1.Columns(2).HeaderText = "Cargo" DataGridView1.Columns(3).HeaderText = "Sueldo" CboCargo.Items.Add("Gerente") CboCargo.Items.Add("Empleado") CboCargo.Items.Add("Operario") End Sub

Private Sub BtnNuevo_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnNuevo.Click TxtNombre.Enabled = True TxtSueldo.Enabled = True CboCargo.Enabled = True End Sub

Private Sub BtnGuardar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnGuardar.Click tsueldo = tsueldo + TxtSueldo.Text DataGridView1.Rows.Add() DataGridView1.Rows(cont).Cells(0).Value = TxtNombre.Text DataGridView1.Rows(cont).Cells(1).Value = DateTimePicker2.Value

Page 47: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 209 -

DataGridView1.Rows(cont).Cells(2).Value = CboCargo.Text DataGridView1.Rows(cont).Cells(3).Value = TxtSueldo.Text Select Case CboCargo.Text Case "Gerente" tg = tg + 1 Case "Empleado" te = te + 1 Case "Operariop" Top = Top + 1 End Select cont = cont + 1 TxtNombre.Enabled = False TxtSueldo.Enabled = False CboCargo.Enabled = False End Sub

Private Sub BtnEstadistica_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnEstadistica.Click Form3.txtGerente.Text = tg Form3.txtEmpleado.Text = te Form3.txtOperario.Text = Top Form3.txtTotalSueldo.Text = tsueldo Form3.ShowDialog() End SubEnd Class

Page 48: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 210 -

Public Class Form3 Private Sub btnCerrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCerrar.Click Me.Close() End SubEnd Class

Pregunta 2

2. Implemente la clase trabajador que se deriva de la clase Persona

Page 49: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 211 -

Public Class Persona Private Nombre1 As String Public Property Nombre As String Get Nombre = Nombre1 End Get Set(ByVal value As String) Nombre1 = value End Set End PropertyEnd Class

Public Class Trabajador Inherits Persona Private Cargo1 As String Private Sueldo1 As String Public Property Cargo As String Get Cargo = Cargo1 End Get Set(ByVal value As String) Cargo1 = value End Set End Property

Public Property Sueldo As Single Get Sueldo = Sueldo1 End Get Set(ByVal value As Single) Sueldo1 = value End Set End PropertyEnd Class

Page 50: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 212 -

Public Class Form1 Dim juan As Persona Dim Pedro As Trabajador Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click juan = New Persona() Pedro = New Trabajador() juan.Nombre = "JUAN PEREZ" Pedro.Nombre = "PEDRO RIOS" Pedro.Cargo = "GERENTE" Pedro.Sueldo = 3000 TextBox1.Text = juan.Nombre TextBox2.Text = Pedro.Nombre TextBox3.Text = Pedro.Cargo TextBox4.Text = Pedro.Sueldo End SubEnd Class

EXAMEN 2 PRODUCTO turno Lunes de 18 a 20 horas

Public Class Form1 Private Sub AgregarEmpleadoToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles MnuAgregarProducto.Click Form2.ShowDialog() End Sub Private Sub SalirToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SalirToolStripMenuItem.Click Me.Close()

Page 51: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 213 -

End SubEnd Class

Public Class Form2 Dim cont As Integer = 0 Dim monto As Single Dim tmonto As Single = 0 Dim sp1 As Integer = 0 Dim sp2 As Integer = 0 Dim sp3 As Integer = 0 Dim pu1 As Single = 2 Dim pu2 As Single = 5 Dim pu3 As Single = 4 Private Sub Form2_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load TxtCant.Enabled = False CboTipo.Enabled = False CboPu.Enabled = False DataGridView1.ColumnCount = 4 DataGridView1.Columns(0).HeaderText = "Tipo Producto" DataGridView1.Columns(1).HeaderText = "Precio Unitario" DataGridView1.Columns(2).HeaderText = "Cantidad" DataGridView1.Columns(3).HeaderText = "Monto" CboTipo.Items.Add("P1") CboTipo.Items.Add("P2") CboTipo.Items.Add("P3") CboPu.Items.Add(pu1) CboPu.Items.Add(pu2) CboPu.Items.Add(pu3) End Sub

Page 52: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 214 -

Private Sub BtnNuevo_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnNuevo.Click TxtCant.Enabled = True CboTipo.Enabled = True CboPu.Enabled = True End Sub

Private Sub BtnGuardar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnGuardar.Click DataGridView1.Rows.Add() DataGridView1.Rows(cont).Cells(0).Value = CboTipo.Text DataGridView1.Rows(cont).Cells(1).Value = CboPu.Text DataGridView1.Rows(cont).Cells(2).Value = TxtCant.Text Select Case CboTipo.Text Case "P1" monto = pu1 * TxtCant.Text sp1 = sp1 + 1 Case "P2" sp2 = sp2 + 1 monto = pu2 * TxtCant.Text Case "P3" sp3 = sp3 + 1 monto = pu3 * TxtCant.Text End Select DataGridView1.Rows(cont).Cells(3).Value = monto tmonto = tmonto + monto cont = cont + 1 TxtCant.Enabled = False CboPu.Enabled = False CboTipo.Enabled = False End Sub Private Sub BtnEstadistica_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnEstadistica.Click Form3.txtP1.Text = sp1 Form3.txtP2.Text = sp2 Form3.txtP3.Text = sp3 Form3.txtTotaVenta.Text = tmonto Form3.ShowDialog() End SubEnd Class

Public Class Form3 Private Sub btnCerrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCerrar.Click Me.Close() End SubEnd Class

Page 53: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 215 -

2 .implemente la clase automovil que se deriva de la clase Vehiculo

Page 54: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 216 -

Public Class Form1 Dim auto1 As Vehiculo Dim auto2 As Automovil Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click auto1 = New Vehiculo() auto2 = New Automovil() auto1.Propietario = "JUAN PEREZ" auto2.Propietario = "PEDRO RIOS" auto2.Modelo = "SEDAN" auto2.Año = 2012 TextBox1.Text = auto1.Propietario TextBox2.Text = auto2.Propietario TextBox3.Text = auto2.Modelo TextBox4.Text = auto2.Año End SubEnd Class

PREGUNTA 3 TURNO MIERCOLES DE 9 A11 HORAS

CLASE POSTULANTE

Public Class Form1 Private Sub AgregarEmpleadoToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles mnuAgregarPostulante.Click Form2.ShowDialog() End Sub

Private Sub SalirToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SalirToolStripMenuItem.Click Me.Close() End SubEnd Class

Page 55: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 217 -

Public Class Form2 Dim cont As Integer = 0 Dim monto As Single Dim tmonto As Single = 0 Dim sva1 As Integer = 0 Dim sva2 As Integer = 0 Dim sva3 As Integer = 0 Dim sma1 As Integer = 0 Dim sma2 As Integer = 0 Dim sma3 As Integer = 0 Private Sub Form2_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load txtCodigo.Enabled = False CboArea.Enabled = False CboSexo.Enabled = False BtnGuardar.Enabled = True DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).HeaderText = "Codigo Postulante" DataGridView1.Columns(1).HeaderText = "Area" DataGridView1.Columns(2).HeaderText = "Sexo" CboArea.Items.Add("Ingenierias") CboArea.Items.Add("Sociales") CboArea.Items.Add("Biomedicas") CboSexo.Items.Add("Masculino") CboSexo.Items.Add("Femenino") End Sub

Private Sub BtnNuevo_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnNuevo.Click txtCodigo.Enabled = True

Page 56: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 218 -

CboArea.Enabled = True CboSexo.Enabled = True BtnGuardar.Enabled = True End Sub

Private Sub BtnGuardar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnGuardar.Click DataGridView1.Rows.Add() DataGridView1.Rows(cont).Cells(0).Value = txtCodigo.Text DataGridView1.Rows(cont).Cells(1).Value = CboArea.Text DataGridView1.Rows(cont).Cells(2).Value = CboSexo.Text

Select Case CboArea.Text Case "Ingenierias" If CboSexo.Text = "Masculino" Then sva1 = sva1 + 1 Else sma1 = sma1 + 1 End If Case "Sociales" If CboSexo.Text = "Masculino" Then sva2 = sva2 + 1 Else sma2 = sma2 + 1 End If Case "Biomedicas" If CboSexo.Text = "Masculino" Then sva3 = sva3 + 1 Else sma3 = sma3 + 1 End If End Select cont = cont + 1 txtCodigo.Enabled = False CboSexo.Enabled = False CboArea.Enabled = False End Sub

Private Sub BtnEstadistica_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnEstadistica.Click Form3.DataGridView1.ColumnCount = 4 Form3.DataGridView1.RowCount = 3 Form3.DataGridView1.Columns(0).HeaderText = "Area" Form3.DataGridView1.Columns(1).HeaderText = "Varones" Form3.DataGridView1.Columns(2).HeaderText = "Mujeres" Form3.DataGridView1.Columns(3).HeaderText = "Total"

Form3.DataGridView1.Rows(0).Cells(0).Value = CboArea.Items(0) Form3.DataGridView1.Rows(0).Cells(1).Value = sva1 Form3.DataGridView1.Rows(0).Cells(2).Value = sma1 Form3.DataGridView1.Rows(0).Cells(3).Value = sva1 + sma1

Page 57: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 219 -

Form3.DataGridView1.Rows(1).Cells(0).Value = CboArea.Items(1) Form3.DataGridView1.Rows(1).Cells(1).Value = sva2 Form3.DataGridView1.Rows(1).Cells(2).Value = sma2 Form3.DataGridView1.Rows(1).Cells(3).Value = sva2 + sma2 Form3.DataGridView1.Rows(2).Cells(0).Value = CboArea.Items(2) Form3.DataGridView1.Rows(2).Cells(1).Value = sva3 Form3.DataGridView1.Rows(2).Cells(2).Value = sma3 Form3.DataGridView1.Rows(2).Cells(3).Value = sva3 + sma3 Form3.ShowDialog() End SubEnd Class

Public Class Form3 Private Sub btnCerrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCerrar.Click Me.Close() End SubEnd Class

Implemente la clase circulo que se deriva de la clase punto

Public Class Punto

Page 58: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 220 -

Private X1 As Integer Private y1 As Integer Public Property X As Integer Get X = X1 End Get Set(ByVal value As Integer) X1 = value End Set End Property Public Property Y As Integer Get Y = y1 End Get Set(ByVal value As Integer) y1 = value End Set End PropertyEnd Class

Public Class Circulo Inherits Punto Private Radio1 As Integer Public Property Radio As Integer Get Radio = Radio1 End Get Set(ByVal value As Integer) Radio1 = value End Set End PropertyEnd Class

Public Class Form1 Dim p1 As Punto Dim p2 As Circulo

Page 59: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 221 -

Dim Grafico As Graphics Dim pen As Pen

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load p1 = New Punto() p2 = New Circulo() pen = New Pen(Color.Red, 4) Grafico = PictureBox1.CreateGraphics End Sub

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click p2.X = 100 p2.Y = 200 p2.Radio = 100 TextBox1.Text = p2.X TextBox2.Text = p2.Y TextBox3.Text = p2.Radio End Sub

Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles PictureBox1.MouseDown p2.X = e.X p2.Y = e.Y TextBox1.Text = p2.X TextBox2.Text = p2.Y p2.Radio = TextBox3.Text Grafico.DrawEllipse(pen, p2.X - p2.Radio, p2.Y - p2.Radio, p2.Radio * 2, p2.Radio * 2) End SubEnd Class

PREGUNTA 4 TURNO MIERCOLES DE 11 A13 HORASCLASE NOTAS

Public Class Form1 Private Sub AgregarEmpleadoToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles mnuAgregarPostulante.Click Form2.ShowDialog() End Sub Private Sub SalirToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SalirToolStripMenuItem.Click

Page 60: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 222 -

Me.Close() End Sub

Public Class Form2 Dim cont As Integer = 0 Dim fila As Integer Dim snota As Integer = 0 Dim promedio As Single = 0 Dim codgana As String Dim mayor As Integer = -100 Private Sub Form2_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load CboCodigo.Enabled = False CboNota.Enabled = False BtnGuardar.Enabled = True DataGridView1.ColumnCount = 2 DataGridView1.Columns(0).HeaderText = "Codigo alumno" DataGridView1.Columns(1).HeaderText = "Nota" For fila = 1 To 30 cboCodigo.Items.Add("A" & fila) Next For fila = 0 To 20 CboNota.Items.Add(fila.ToString) Next End Sub

Private Sub BtnNuevo_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnNuevo.Click CboCodigo.Enabled = True CboNota.Enabled = True BtnGuardar.Enabled = True End Sub

Private Sub BtnGuardar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnGuardar.Click DataGridView1.Rows.Add()

Page 61: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 223 -

DataGridView1.Rows(cont).Cells(0).Value = CboCodigo.Text DataGridView1.Rows(cont).Cells(1).Value = CboNota.Text snota = snota + CboNota.Text If CboNota.Text > mayor Then mayor = CboNota.Text codgana = CboCodigo.Text End If cont = cont + 1 CboCodigo.Enabled = False CboNota.Enabled = False End Sub Private Sub BtnEstadistica_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnEstadistica.Click Form3.TxtPnota.Text = snota / cont Form3.txtMaximaNota.Text = mayor Form3.txtGanador.Text = codgana Form3.ShowDialog() End SubEnd Class

Public Class Form3 Private Sub btnCerrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCerrar.Click Me.Close() End SubClase animal

Señores alumnos de sistemas de información 2015ASe envía material para el curso de SI2015AEn las prácticas de laboratorio de esta semana se revisara los trabajos 1 y 2, se asignara temas por grupo de prácticas para el trabajo 2 (a los grupos que no se han escrito)Entrega del primer trabajo en su turno sobre 20 puntos, fuera del turno sobre 15 puntosTercera práctica de aquí 3 semanas mostrar el funcionamiento y modificaciones del sistema de ventas (se entregara instalador SQLserver 2008)VIDEOS De sistema de ventas expuesto por Juan Carlos ARCILLA DIAZ Ver cana decanal www.youtube.com/jcarlosad7

Page 62: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 224 -

Blog www.incanato.site90.comJuan Carlos Arcila DíazChiclayo - Perú Enero – 2014Se realizará Prácticas para el examen (del primer y segundo trabajo)Se preguntara sobre recursividad. Solución de las preguntas del examen tentativoComo realizar macros en excelMDI hay 3 formularios hechos (mostrar su modificaciones)

- Preguntas sobre controles button, textbox, cuadros de listas, cuadros combinados, menú strip,menus contextuales, cuadros de diálogos, eventos del mouse y del teclado, cajas de dialogo (open files dialog,etc )

- Creación de formularios y controles en tiempo de ejecución- Input box, message box, timer animación sencilla- Propiedades métodos eventos- Gráficos- Procedimientos de eventos

En evaluación de expresiones hay 2 trabajosArchivos, escritura lectura, leer una matriz, grabar los Valores de una funciónCadenas. Elaborar funciones de cadenas, ejemplo buscar una su cadena, reemplazar una su cadena , Trabajo adicional juegoMatrices mostrar una parte de una matriz, Preguntas sobre clases y objetos

1. crear una clase con sus propiedades, campos, métodos, eventos 2. Usar la clase creada en modo consola o formulario

SaludosIng. Veliz

SISTEMA EJEMPLO DE CLASES Y OBJETOS ( CLASE VEHICULO)

Page 63: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 225 -

Public Class VEHICULO Private nro1 As Integer Private Año1 As Integer Private Propietario1 As String Private Placa1 As String Private Foto1 As String Private Marca1 As String Private CantCombustible1 As Single Public Event SinCombustible(ByVal Valor As Single) Public Event ExcesoCombustible(ByVal Valor As Single)

Sub New(Optional nro2 As Integer = 0, Optional año2 As Integer = 0, Optional Propietario2 As String = "SN", _ Optional placa2 As String = "SP", Optional marca2 As String = "Sm", _ Optional foto2 As String = "sf", Optional ccombustible As Single = 0) nro1 = nro2 Año1 = año2 Propietario1 = Propietario2 Marca1 = marca2 Foto1 = foto2 Placa1 = placa2 CantCombustible1 = ccombustible End Sub

Public Property CantCombustible() As Single Get CantCombustible = CantCombustible1 End Get Set(value As Single) Select Case value Case Is < 10 RaiseEvent SinCombustible(value) Case CSng(value > 0) To 40 CantCombustible1 = value Case Is > 40 RaiseEvent ExcesoCombustible(value) End Select End Set End Property

Page 64: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 226 -

Public Property Nro As Integer Get Nro = nro1 End Get Set(value As Integer) nro1 = value End Set End Property

Public Property Año As Integer Get Año = Año1 End Get Set(value As Integer) Año1 = value End Set End Property

Public Property Propietario As String Get Propietario = Propietario1 End Get Set(value As String) Propietario1 = Propietario End Set End Property

Public Property Placa As String Get Placa = Placa1 End Get Set(value As String) Placa1 = value End Set End Property Public Property Marca As String Get Marca = Marca1 End Get Set(value As String) Marca1 = value End Set End Property

Public Property Foto As String Get Foto = Foto1 End Get Set(value As String) Foto1 = value End Set End Property

Page 65: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 227 -

Protected Overrides Sub Finalize()

End Sub

Public Sub AgregarCombustible(q As Single) CantCombustible1 = CantCombustible1 + q End Sub

Public Sub Recorrer(km As Single) CantCombustible1 = CantCombustible1 - km * 0.02 End SubEnd Class

' *** CLASE FORMULARIOImports System.IOPublic Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load DataGridView1.ColumnCount = nc DataGridView1.RowCount = 12 End Sub Sub MostrarPropObjeto(objeto As VEHICULO, fila As Integer) DataGridView1.Rows(fila).Cells(0).Value = fila DataGridView1.Rows(fila).Cells(1).Value = objeto.Año DataGridView1.Rows(fila).Cells(2).Value = objeto.Propietario DataGridView1.Rows(fila).Cells(3).Value = objeto.Placa DataGridView1.Rows(fila).Cells(4).Value = objeto.Marca DataGridView1.Rows(fila).Cells(5).Value = objeto.Foto DataGridView1.Rows(fila).Cells(6).Value = objeto.CantCombustible End Sub Private Sub btnCargar_Click(sender As Object, e As EventArgs) Handles btnCargar.Click Dim fila As Integer = 0 Dim archivo As StreamReader Dim cadena As String Dim cadena1 As String Dim pos1 As Integer Dim lugar As Integer ' OpenFileDialog1.ShowDialog() ' nombreArchivo = OpenFileDialog1.FileName archivo = New StreamReader(nombreArchivo) cadena = archivo.ReadLine cont = 0 pos1 = encontrar(cadena, vbTab, lugar) 'insertar cabecera Do While (pos1 >= 0 And pos1 < Len(cadena)) cadena1 = Extrae(cadena, lugar, pos1 - 1) DataGridView1.Columns(cont).HeaderText = cadena1 cont = cont + 1 lugar = pos1 + 1 pos1 = encontrar(cadena, vbTab, lugar) Loop

Page 66: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 228 -

' insertamos los demas registros cadena = archivo.ReadLine cont = 0 Do While Not (cadena Is Nothing) obtenerPropiedades(cadena, prop, np) autos(cont) = New VEHICULO(Val(prop(0)), Val(prop(1)), prop(2), prop(3), prop(4), prop(5), Val(prop(6))) MostrarPropObjeto(autos(cont), cont) cadena = archivo.ReadLine cont = cont + 1 Loop nf = cont archivo.Close() End Sub

Private Sub btnCrear_Click(sender As Object, e As EventArgs) Handles btnCrear.Click Dim objeto As VEHICULO Dim Cadena As String Cadena = "0 2005 JUAN P1 FORDFOTO1 0" obtenerPropiedades(Cadena, prop, np) objeto = New VEHICULO(Val(prop(0)), Val(prop(1)), prop(2), prop(3), prop(4), prop(5), Val(prop(6))) 'a(0) = New VEHICULO() MostrarPropObjeto(objeto, 0) End Sub

Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles btnGrabar.Click Dim fila As Integer = 0 Dim archivo As StreamWriter ' OpenFileDialog1.ShowDialog() ' nombreArchivo = OpenFileDialog1.FileName archivo = New StreamWriter(nombreArchivo) ' grabando cabecera For col = 0 To nc - 1 archivo.Write("{0}{1}", DataGridView1.Columns(col).HeaderText, vbTab) Next archivo.WriteLine() For fila = 0 To nf - 1 For col = 0 To nc - 1 archivo.Write("{0}{1}", DataGridView1.Rows(fila).Cells(col).Value, vbTab) Next archivo.WriteLine() Next archivo.Close() End Sub Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick Dim fila As Integer Dim objeto As VEHICULO

Page 67: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 229 -

fila = DataGridView1.CurrentRow.Index objeto = autos(fila) txtNro.Text = objeto.Nro txtAño.Text = objeto.Año txtPropietario.Text = objeto.Propietario txtplaca.Text = objeto.Placa txtMarca.Text = objeto.Marca txtFoto.Text = objeto.Foto txtCombustible.Text = objeto.CantCombustible PictureBox1.Load("E:\DATOS\FOTOS\" & objeto.Foto) End SubEnd Class

PRACTICAS SI 2015 DEL DIA MARTES 09 DE JUNIO DEL 2015Turno de 5 a 7 pm

Elaborar la siguiente aplicación

Imports System.IOPublic Class Form1 Dim NombreArchivo As String Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles btnBorrar.Click TextBox1.Clear() End Sub

Private Sub btnFuente_Click(sender As Object, e As EventArgs) Handles btnFuente.Click FontDialog1.ShowDialog() TextBox1.Font = FontDialog1.Font End Sub

Page 68: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 230 -

Private Sub btnColorTexto_Click(sender As Object, e As EventArgs) Handles btnColorTexto.Click ColorDialog1.ShowDialog() TextBox1.ForeColor = ColorDialog1.Color End Sub

Private Sub BtnColorFuente_Click(sender As Object, e As EventArgs) Handles BtnColorFuente.Click ColorDialog1.ShowDialog() TextBox1.BackColor = ColorDialog1.Color End Sub Private Sub btnCrear_Click(sender As Object, e As EventArgs) Handles btnCrear.Click ' Form2.ShowDialog() Dim x As Form2 x = New Form2 x.MdiParent = Me x.Show() End Sub

Private Sub btnAbrir_Click(sender As Object, e As EventArgs) Handles btnAbrir.Click Dim texto As String Dim archivo As StreamReader Dim cadena As String = "" OpenFileDialog1.ShowDialog() nombrearchivo = OpenFileDialog1.FileName archivo = New StreamReader(nombrearchivo) texto = archivo.ReadLine() Do While Not (texto Is Nothing) cadena = cadena + vbCrLf + texto texto = archivo.ReadLine() Loop TextBox1.Text = cadena End Sub

Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles btnGrabar.Click Dim archivo As StreamWriter SaveFileDialog1.ShowDialog() nombrearchivo = SaveFileDialog1.FileName archivo = New StreamWriter(nombrearchivo) archivo.WriteLine("{0}", TextBox1.Text) archivo.Close() End SubEnd Class

PRACTICAS DE 7-9 PM DEL DIA MARTES 09 DE JUNIO DEL 2015

Creacion de controles en tiempo de ejecucion

Page 69: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 231 -

Public Class Form1 Dim BOTON(20) As Button Dim posx As Integer = 10 Dim cont As Integer = 0 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click BOTON(cont) = New Button BOTON(cont).Text = "Boton " & cont BOTON(cont).Location = New Point(posx, posx) Me.Controls.Add(BOTON(cont)) cont = cont + 1 posx = posx + 20 End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim ncontroles As Integer = Me.Controls.Count ListBox1.Items.Add("Name Text") For Each Control As Control In Me.Controls ListBox1.Items.Add(Control.Name & " " & Control.Text) Next Control ListBox1.Items.Add("nro controles " & ncontroles) End SubEnd Class

Mostrar la hora cada interval de tiempo en una etiquetay que cambia de color el formulario s emueve por la pantalla

Page 70: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 232 -

Public Class Form1 Dim cont As Integer = 0 Dim posform As Integer = 0 Dim ls As Integer = 500 Dim li As Integer = 10 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnIniciar.Click Timer1.Interval = 10 Timer1.Enabled = True End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnParar.Click Timer1.Enabled = False End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Label1.Text = TimeOfDay cont = cont + 1 If cont Mod 2 = 0 Then Label1.ForeColor = Color.FromArgb(255, 0, 0) Else Label1.ForeColor = Color.FromArgb(0, 255, 0) End If If posform < ls Then posform = posform + 1 Else posform = li End If Me.Left = posform End SubEnd Class

Formularios que se mueven

Page 71: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 233 -

Public Class Form1 Dim cont As Integer = 0 Dim li As Integer = 10 Dim ls As Integer = 400 Private Sub btnIniciar_Click(sender As Object, e As EventArgs) Handles btnIniciar.Click Timer1.Interval = 10 Timer1.Enabled = True Form2.Show() End Sub Private Sub BtnParar_Click(sender As Object, e As EventArgs) Handles BtnParar.Click Timer1.Enabled = False End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick If cont Mod ls = 0 Then Me.Left = ls Form2.Left = li Else Form2.Left = Form2.Left + 1 Me.Left = ls - (cont Mod ls) End If cont = cont + 1 End SubEnd ClassMover un control en un contenedor a la vez se mueve el formulario

Page 72: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 234 -

Public Class Form1 Dim cont As Integer = 0 Dim li As Integer = 10 Dim ls As Integer = 400 Dim lipanel As Integer = 10 Dim lspanel As Integer = 200 Dim lilabel As Integer = 10 Dim lslabel As Integer = 100

Private Sub btnIniciar_Click(sender As Object, e As EventArgs) Handles btnIniciar.Click Timer1.Interval = 10 Timer1.Enabled = True End Sub Private Sub BtnParar_Click(sender As Object, e As EventArgs) Handles btnParar.Click Timer1.Enabled = False End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick If cont Mod ls = 0 Then Me.Left = li Else Me.Left = (cont Mod ls) End If If cont Mod lspanel = 0 Then Panel1.Left = lipanel Else Panel1.Left = (cont Mod lspanel) End If If cont Mod lslabel = 0 Then Label1.Left = lilabel Else Label1.Left = (cont Mod lslabel) End If

Page 73: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 235 -

If cont Mod 2 = 0 Then Label1.ForeColor = Color.Red

Else Label1.ForeColor = Color.Green End If

cont = cont + 1 End SubEnd Class

Practica del miercoles 10 de junio del 2015 Mover los controles y listar

Public Class Form1 Dim paso As Integer = 10 Private Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click Dim ncontroles As Integer = Me.Controls.Count ListBox1.Items.Add("Name Text") For Each Control As Control In Me.Controls ListBox1.Items.Add(Control.Name & " " & Control.Text) Next Control ListBox1.Items.Add("nro controles " & ncontroles) End Sub

Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles MyBase.MouseDown txtBoton.Text = e.Button txtX.Text = e.X txtY.Text = e.Y If e.Button = 1048576 Then For Each Control As Control In Me.Controls

Page 74: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 236 -

Control.Left = Control.Left - paso Next Control End If If e.Button = 2097152 Then For Each Control As Control In Me.Controls Control.Left = Control.Left + paso Next Control End If ' Button1.Left = Button1.Left - paso End Sub

Private Sub btnMover_Click(sender As Object, e As EventArgs) Handles btnMover.Click Timer1.Interval = 10 Timer1.Enabled = True

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Label1.Text = TimeOfDay If Me.Left < 400 Then Me.Left = Me.Left + 1 Else Me.Left = 10 End If If Button1.Left < 100 Then Button1.Left = Button1.Left + 1 Else Button1.Left = 0 End If End Sub

Private Sub btnDetener_Click(sender As Object, e As EventArgs) Handles btnDetener.Click Timer1.Enabled = False End SubEnd Class

Practicas miercoles 7 miercoles 10 de junio del 2015

Abrir y grabar un archivo

Imports System.IOPublic Class Form1 Dim nombreArchivo As String = "E:\datos\unsa.txt" Private Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click Dim archivo As StreamWriter SaveFileDialog1.ShowDialog() nombreArchivo = SaveFileDialog1.FileName

Page 75: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 237 -

archivo = New StreamWriter(nombreArchivo) archivo.WriteLine("{0}", TextBox1.Text) archivo.Close() End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim archivo As StreamReader Dim texto As String Dim cadena As String = "" OpenFileDialog1.ShowDialog() nombreArchivo = OpenFileDialog1.FileName archivo = New StreamReader(nombreArchivo) texto = archivo.ReadLine() Do While Not (texto Is Nothing) cadena = cadena + vbCrLf + texto texto = archivo.ReadLine() Loop TextBox1.Text = cadena archivo.Close() End Sub

Private Sub btnColorLetra_Click(sender As Object, e As EventArgs) Handles btnColorLetra.Click ColorDialog1.ShowDialog() TextBox1.ForeColor = ColorDialog1.Color End Sub

Private Sub btnFondo_Click(sender As Object, e As EventArgs) Handles btnFondo.Click ColorDialog1.ShowDialog() TextBox1.BackColor = ColorDialog1.Color End Sub

Private Sub btnfuente_Click(sender As Object, e As EventArgs) Handles btnfuente.Click FontDialog1.ShowDialog() TextBox1.Font = FontDialog1.Font End SubEnd Class

Ejemplo de cadenas

Page 76: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 238 -

Module Module1 Function CLETRAS(cadena As String, cad1 As String) As Integer Dim fila As Integer Dim cont = 0 For fila = 0 To Len(cadena) - 1 If cadena(fila) = cad1 Then cont = cont + 1 Next CLETRAS = cont End FunctionEnd Module

Public Class Form1 Dim nfilas As Integer = 60 Dim grafico As Graphics Dim pen As Pen Dim pen1 As Pen Dim brocha As SolidBrush Dim cx As Integer = 10 Dim cy As Integer = 400 Dim ancho As Integer = 400 Dim alto As Integer = 410 Dim ex As Integer = 8 Dim ey As Integer = 8 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim fila As Integer With Me.DataGridView1.DefaultCellStyle .Font = New Font("Tahoma", 15) .ForeColor = Color.Blue .BackColor = Color.Beige .SelectionForeColor = Color.Yellow .SelectionBackColor = Color.Black End With DataGridView1.ColumnCount = 2

Page 77: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 239 -

DataGridView1.RowCount = nfilas + 1 DataGridView1.Columns(0).HeaderText = "Letra" DataGridView1.Columns(1).HeaderText = "Cantidad" For fila = 0 To nfilas - 1 DataGridView1.Rows(fila).Cells(0).Value = Chr(32 + fila) Next End Sub

Private Sub btnProcesar_Click(sender As Object, e As EventArgs) Handles btnProcesar.Click Dim cadena As String Dim nletras As Integer Dim fila As Integer cadena = TextBox1.Text For fila = 0 To nfilas - 1 nletras = CLETRAS(cadena, Chr(32 + fila)) DataGridView1.Rows(fila).Cells(1).Value = nletras Next End Sub

Private Sub btnGraficar_Click(sender As Object, e As EventArgs) Handles btnGraficar.Click Dim fila, y As Integer grafico = PictureBox1.CreateGraphics pen = New Pen(Color.Red, 2) pen1 = New Pen(Color.Blue, 1) brocha = New SolidBrush(Color.Green) ' coordenadas grafico.DrawLine(pen1, 0, cy, ancho, cy) grafico.DrawLine(pen1, cx, 0, cx, alto) For fila = 0 To nfilas - 1 y = DataGridView1.Rows(fila).Cells(1).Value grafico.FillRectangle(brocha, cx + fila * ex, cy - y * ey, ex, y * ey) grafico.DrawRectangle(pen, cx + fila * ex, cy - y * ey, ex, y * ey) Next End Sub

Private Sub btnLimpiar_Click(sender As Object, e As EventArgs) Handles btnLimpiar.Click TextBox1.Text = "" grafico.Clear(Color.Black) End SubEnd Class

Contar palabras

Page 78: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 240 -

Se debe lleer de un archive uo aumentar esacio en cadallienaModule Module1 Public cadena As String Public pos1, pos2 As Integer Public letras(1000) As String Public letras1(1000) As String Public frec(1000) As Integer Public nf As Integer = 0 Public nf1 As Integer = 0 Function encontrado(cadena() As String, cad1 As String, nf As Integer) As Boolean Dim fila As Integer Dim res As Boolean = False For fila = 0 To nf - 1 If cadena(fila) = cad1 Then res = True Exit For End If Next Return res End Function

Function Extrae(cadena As String, pos1 As Integer, pos2 As Integer) As String Dim subcadena As String = "" Dim fila As Integer Dim cont As Integer = 0 For fila = pos1 To pos2 subcadena = subcadena + cadena(fila) Next Return subcadena End Function Sub obtenerPalabras(cadena As String, letras() As String, ByRef nf As Integer) Dim cont As Integer = 0 Dim cadena1 As String pos1 = buscarNoespacio(cadena, " ", 0)

Page 79: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 241 -

Do While pos1 >= 0 pos2 = buscarEspacio(cadena, " ", pos1) cadena1 = Extrae(cadena, pos1, pos2 - 1) letras(cont) = cadena1 pos1 = buscarNoespacio(cadena, " ", pos2) cont = cont + 1 nf = cont Loop End Sub

Function AgregarEspacio(cadena As String) As String Dim fila As Integer Dim cad1 As String = "" For fila = 0 To Len(cadena) - 1 cad1 = cad1 + cadena(fila) If cadena(fila) = vbCrLf Then cad1 = cad1 + " " Next Return cad1 End Function

Function buscarNoespacio(cadena As String, cad1 As String, posini As Integer) As Integer Dim fila As Integer Dim pos As Integer = -1 For fila = posini To Len(cadena) - 1 If cadena(fila) <> cad1 Then pos = fila Exit For End If Next Return pos End Function Function buscarEspacio(cadena As String, cad1 As String, posini As Integer) As Integer Dim fila As Integer Dim pos As Integer = -1 For fila = posini To Len(cadena) - 1 If cadena(fila) = cad1 Then pos = fila Exit For End If Next Return pos End FunctionEnd Module

CODIGO DEL FORMULARIO

Public Class Form1 Function ContarPalabras(cadena() As String, cad1 As String, nf As Integer) As Integer

Page 80: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 242 -

Dim fila As Integer Dim cont As Integer = 0 For fila = 0 To nf - 1 If cadena(fila) = cad1 Then cont = cont + 1 Next Return cont End Function Private Sub BtnPalabras_Click(sender As Object, e As EventArgs) Handles BtnPalabras.Click 'cadena = " A B C A " : TextBox1.Text = cadena cadena = TextBox1.Text cadena = AgregarEspacio(cadena) cadena = " " + cadena + " " obtenerPalabras(cadena, letras, nf) ' mostrar los valoes en el cuadro de listas For fila = 0 To nf - 1 ListBox1.Items.Add(letras(fila)) Next ListBox1.Items.Add(" cantidad letras " & nf) ' buscar un vector de no repitido Dim cont1 As Integer = 1 : letras1(0) = letras(0) Dim nombre As String For fila = 1 To nf - 1 nombre = letras(fila) If encontrado(letras1, nombre, cont1) = False Then letras1(cont1) = nombre cont1 = cont1 + 1 End If Next nf1 = cont1 ' encontrar las frecuencias For fila = 0 To nf1 - 1 frec(fila) = ContarPalabras(letras, letras1(fila), nf) Next 'imprimir frecuencias For fila = 0 To nf1 - 1 ListBox1.Items.Add(letras1(fila) & " frec " & frec(fila)) Next End Sub

Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles btnBorrar.Click TextBox1.Text = "" ListBox1.Items.Clear() End SubEnd Class

Clases del jueves 11 junio del 20015 9-11

Crear un formulario en tiempo de ejecucion

Page 81: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 243 -

Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim f1 As Form2 f1 = New Form2() ' f1.MdiParent = Me f1.ShowDialog() End SubEnd Class

Crear un boton en tiempo de ejecucion

Public Class Form1 Private WithEvents objeto As New Button() Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click objeto.Left = 50 objeto.Top = 20 objeto.Name = "btnnombre" objeto.Text = "btnnombre" Me.Controls.Add(objeto) AddHandler objeto.Click, AddressOf Saludo End Sub Private Sub Saludo(ByVal sender As Object, ByVal e As EventArgs) MsgBox("hola") End SubEnd Class

Como cargar una foto

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click OpenFileDialog1.ShowDialog() PictureBox1.Load(OpenFileDialog1.FileName) End Sub

Practicas del Jueves 11 de junio del 2015 turno de 11 13 horas

Mover una figura en forma automática y con las teclas direccionales

Public Class Form1 Dim lienzo As Graphics Dim pen As Pen Dim brocha As SolidBrush Dim posx As Integer = 10 Dim posy As Integer = 10 Dim paso As Integer = 2 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load lienzo = PictureBox1.CreateGraphics pen = New Pen(Color.FromArgb(255, 0, 0), 3) brocha = New SolidBrush(Color.FromArgb(0, 255, 0)) End Sub

Page 82: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 244 -

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnMover.Click Timer1.Interval = 10 Timer1.Enabled = True End Sub 'lienzo.DrawRectangle(pen, 10, 10, 20, 10) Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick lienzo.Clear(Color.Black) If posx < 400 Then posx = posx + paso Else posx = 10 End If lienzo.FillRectangle(brocha, posx, 10, 120, 110) lienzo.DrawRectangle(pen, posx, 10, 120, 110) End Sub Private Sub btnDetener_Click(sender As Object, e As EventArgs) Handles btnDetener.Click Timer1.Enabled = False End Sub Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown lienzo.Clear(Color.Black) Select Case e.KeyCode Case Keys.Left posx = posx - paso Case Keys.Right posx = posx + paso Case Keys.Up posy = posy - paso Case Keys.Down posy = posy + paso End Select lienzo.DrawRectangle(pen, posx, posy, 20, 10) End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged End SubEnd Class

SELECCIONAR TEXTO EN TEXTBOX

Botón textboxEstablecer texto seleccionado en un control textboxtextBox1.Text = "Hello World"; textBox1.Select(6, 5); MessageBox.Show(textBox1.SelectedText);

Usando con la opción selectstar

Page 83: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 245 -

Public Class Form1 Private Sub TextBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseClick TextBox1.Select(3, 5) End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnSeleccioanr.Click TextBox1.Select(3, 5) MessageBox.Show(TextBox1.SelectedText) End SubEnd Class

Seleccione el texto con el mouse y ,muestre

Para seleccionar todoPrivate Sub Button1_Click(sender As Object, e As EventArgs) Handles btnSeleccioanr.Click TextBox1.SelectAll() MessageBox.Show(TextBox1.SelectedText) End Sub

Seleccionar con SelectionStart y SelectionLength

Public Class Form1

Page 84: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 246 -

Private Sub TextBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseClick TextBox1.SelectionStart = 3 TextBox1.SelectionLength = 5 End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnSeleccioanr.Click TextBox1.SelectionStart = 3 TextBox1.SelectionLength = 5 MessageBox.Show(TextBox1.SelectedText) End SubEnd Class

Selección con el control richt textboxEl RichTextBox control permite al usuario introducir y editar texto mientras que también proporciona características de formato más avanzadas que el convencional TextBoxcontro

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnSeleccioanr.Click RichTextBox1.Text = " Ingenieria Industrial 2015" RichTextBox1.SelectionStart = RichTextBox1.Find("Industrial") RichTextBox1.SelectionColor = Color.Red ' El color que quieras End SubEnd Class

Diferencia entre textbox y RichTextBox 

Page 85: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 247 -

Se puede usar también la selección Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnSeleccioanr.Click RichTextBox1.Select(3, 5) RichTextBox1.SelectionColor = Color.Red ' El color que quieras End Sub

También funciona con select allSelecciona y pone la fuente del tipo indicado Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnSeleccioanr.Click RichTextBox1.Select(3, 5) RichTextBox1.SelectionFont = New Font("Tahoma", 18, FontStyle.Bold) End SubEn ritchtextbox se puede pegar graficosComo grabar un texto enriquecido en recht box

Richt textbox

Page 86: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 248 -

Public Class Form1 Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles btnBorrar.Click RichTextBox1.Clear() End Sub Private Sub btnSalir_Click(sender As Object, e As EventArgs) Handles btnSalir.Click Me.Close() End Sub

Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles btnGrabar.Click SaveFileDialog1.Title = "Abrir Documento rtf" SaveFileDialog1.Filter = "Documento rtf|*.rtf" SaveFileDialog1.ShowDialog() RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.RichText) End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnAbrir1.Click OpenFileDialog1.Title = "Abrir Documento rtf" OpenFileDialog1.Filter = "Documento rtf|*.rtf" OpenFileDialog1.ShowDialog() RichTextBox1.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.RichText) End SubEnd Class

EJEMPLO SIMPLIFICADO DE UN CONTROL RichTextBox1

Page 87: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 249 -

CODIGO DEL MODULOModule Module1 Function rotarCadena(cadena As String, tipo As Integer) As String Dim fila As Integer Dim cadres As String = "" Dim ne As Integer = Len(cadena) Select Case tipo Case 1 cadres = cadena(ne - 1) For fila = 0 To ne - 2 cadres = cadres + cadena(fila) Next

Page 88: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 250 -

Case 2 For fila = 1 To ne - 1 cadres = cadres + cadena(fila) Next cadres = cadres + cadena(0) End Select Return cadres End FunctionEnd Module

CODIGO DEL FORMULARIOPublic Class Form1 Dim Color As Color Dim Pos As Integer Dim pos1 As Integer = 1 Dim posini As Integer = 1 Dim tipo As Integer = 1 Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles btnBorrar.Click RichTextBox1.Clear() End Sub

Private Sub btnSalir_Click(sender As Object, e As EventArgs) Handles btnSalir.Click Me.Close() End Sub

Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles btnGrabar.Click SaveFileDialog1.Title = "Abrir Documento rtf" SaveFileDialog1.Filter = "Documento rtf|*.rtf" SaveFileDialog1.ShowDialog() RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.RichText) End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnAbrir1.Click OpenFileDialog1.Title = "Abrir Documento rtf" OpenFileDialog1.Filter = "Documento rtf|*.rtf" OpenFileDialog1.ShowDialog() RichTextBox1.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.RichText) End Sub

Private Sub BtnColor_Click(sender As Object, e As EventArgs) Handles BtnColor.Click ColorDialog1.ShowDialog() Color = ColorDialog1.Color RichTextBox1.SelectionColor = Color ' El color que quieras

End Sub

Page 89: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 251 -

Private Sub btnFuente_Click(sender As Object, e As EventArgs) Handles btnFuente.Click FontDialog1.ShowDialog() RichTextBox1.SelectionFont = FontDialog1.Font End Sub

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btnBusca.Click ' RichTextBox1.SelectionStart = RichTextBox1.Find(txtBusca.Text) Pos = InStr(pos1, RichTextBox1.Text, txtBusca.Text) If Pos > 0 Then RichTextBox1.Select(Pos - 1, Len(txtBusca.Text)) RichTextBox1.SelectionColor = Color.Red pos1 = Pos + Len(txtBusca.Text) Else MsgBox(" Ya no hay conicidencias ") pos1 = 1 End If End Sub

Private Sub btnReempla_Click(sender As Object, e As EventArgs) Handles btnReempla.Click RichTextBox1.Text = Replace(RichTextBox1.Text, txtBusca.Text, txtReempla.Text, posini) End Sub

Private Sub btnRotarDerecha_Click(sender As Object, e As EventArgs) Handles btnRotarDerecha.Click 'RichTextBox1.Clear() RichTextBox1.Text = rotarCadena(RichTextBox1.Text, 2) End Sub

Private Sub btnRotarIz_Click(sender As Object, e As EventArgs) Handles btnRotarIz.Click RichTextBox1.Text = rotarCadena(RichTextBox1.Text, 1) End Sub

Private Sub BtnRotarDerAuto_Click(sender As Object, e As EventArgs) Handles BtnRotarDerAuto.Click Timer1.Interval = 10 Timer1.Enabled = True tipo = 1 End Sub

Private Sub btnRotarIzAuto_Click(sender As Object, e As EventArgs) Handles btnRotarIzAuto.Click Timer1.Interval = 10 Timer1.Enabled = True tipo = 2 End Sub

Page 90: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 252 -

Private Sub btnParar_Click(sender As Object, e As EventArgs) Handles btnParar.Click Timer1.Enabled = False End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick RichTextBox1.Text = rotarCadena(RichTextBox1.Text, tipo) End SubEnd Class

Practicas del martes 16 d ejunio del 2015Turno de 5-7 pmClase person

Public Class Persona

Protected DNI1 As Integer Protected nombre1 As String Protected sexo1 As Boolean Public Event Evento1(ByVal Valor As Single) Public Property DNI As Integer Get DNI = DNI1 End Get Set(value As Integer) If value > 1000 And value < 100000000 Then DNI1 = value Else RaiseEvent Evento1(value)

End If

Page 91: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 253 -

End Set End Property Public Property Nombre As String Get Nombre = nombre1 End Get Set(value As String) nombre1 = value

End Set End Property

Public Property sexo As Boolean Get sexo = sexo1 End Get Set(value As Boolean) sexo1 = value End Set End Property Sub New(Optional dni2 As Integer = 0, Optional nombre2 As String = "fulano", _ Optional Sexo2 As Boolean = True) DNI1 = dni2 nombre1 = nombre2 sexo1 = Sexo2 End Sub Function ObtenerValores() As String Dim cad1 As String = "" cad1 = " Nombre " + nombre1 + vbCrLf + "Dni " + DNI + vbCrLf + "sexo " + sexo1 Return cad1 End Function

End Class

Page 92: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 254 -

Public Class Persona Protected DNI1 As Integer Protected nombre1 As String Protected sexo1 As Boolean Public Event Evento1(ByVal Valor As Single) Public Property DNI As Integer Get DNI = DNI1 End Get Set(value As Integer) If value > 1000 And value < 100000000 Then DNI1 = value Else RaiseEvent Evento1(value) End If End Set End Property Public Property Nombre As String Get Nombre = nombre1 End Get Set(value As String) nombre1 = value End Set End Property

Public Property sexo As Boolean Get sexo = sexo1 End Get Set(value As Boolean) sexo1 = value End Set End Property Sub New(Optional dni2 As Integer = 0, Optional nombre2 As String = "fulano", _ Optional Sexo2 As Boolean = True) DNI1 = dni2 nombre1 = nombre2 sexo1 = Sexo2 End Sub Function ObtenerValores() As String Dim cad1 As String = "" cad1 = " Nombre " + nombre1 + vbCrLf + "Dni " + CStr(DNI) + vbCrLf + "sexo " + CStr(sexo1) Return cad1 End Function

End Class

Module Module1 Dim juan As Persona

Page 93: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 255 -

Dim Pedro As Persona Dim A(10) As Persona Dim WithEvents Objeto As Persona Dim nA() As String = {"juan", "pedro", "Lucas", "mario"} Sub Main() Dim fila As Integer objeto = New Persona juan = New Persona(12345678, "juan perez") Pedro = New Persona(222222, "Pedro picapiedra", True) Console.WriteLine(" valores de objeto {0} ", objeto.ObtenerValores()) Console.WriteLine(" valores de Juan {0} ", juan.ObtenerValores()) Console.WriteLine(" valores de Pedro {0} ", Pedro.ObtenerValores()) juan.Nombre = "JUAN CARLOS" objeto.DNI = 12345678 objeto.DNI = -1200 Console.ReadLine() Console.WriteLine(" valores de Juan {0} ", juan.ObtenerValores()) For fila = 0 To 3 ' A(fila) = New Persona(1000 + fila, "nombre " + CStr(fila)) A(fila) = New Persona() A(fila).Nombre = nA(fila) Console.WriteLine(" valores de A{0} es {1} ", fila, A(fila).ObtenerValores) Next Console.ReadLine() End Sub Private Sub xevento1(valor As Integer) Handles objeto.Evento1 Console.WriteLine("{0} ingrese otra vez", valor) End Sub

End Module

En Modo Formulario

Page 94: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 256 -

Public Class Form1 Dim objeto As Persona Private Sub btnCrear_Click(sender As Object, e As EventArgs) Handles btnCrear.Click objeto = New Persona(CInt(txtDNI.Text), txtNombre.Text, CBool(txtSexo.Text)) End Sub Private Sub Ver_Click(sender As Object, e As EventArgs) Handles Ver.Click Try txtDNI.Text = objeto.DNI txtNombre.Text = objeto.Nombre txtSexo.Text = objeto.sexo Catch ex As Exception MsgBox(ex.Message) End Try End SubEnd Class

Imports System.IO

Public Class Form1 Dim objeto As Persona Public Const max As Integer = 10 Dim A(max) As Persona Private Sub btnCrear_Click(sender As Object, e As EventArgs) Handles btnCrear.Click Dim dn2 As String Dim pos As Integer Dim nombre2 As String Dim sexo2 As Boolean Dim cadena As String Dim fila As Integer ' objeto = New Persona(CInt(txtDNI.Text), txtNombre.Text, CBool(txtSexo.Text)) Dim archivo As New StreamReader("E:\datos\personas.txt") cadena = archivo.ReadLine() pos = InStr(cadena, vbTab, 0) dn2 = Mid(cadena, 1, pos - 1) txtDNI.Text = dn2 archivo.Close() 'Do While Not (cadena Is Nothing)

' Console.WriteLine("Línea: {0} - Contenido: {1}", ContadorLin, Linea) ' ContadorLin += 1 ' Linea = srLector.ReadLine() 'Loop

End Sub

Private Sub Ver_Click(sender As Object, e As EventArgs) Handles Ver.Click 'Try

Page 95: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 257 -

' txtDNI.Text = objeto.DNI ' txtNombre.Text = objeto.Nombre ' txtSexo.Text = objeto.sexo

'Catch ex As Exception ' MsgBox(ex.Message)

'End Try

End SubEnd Class

Practicas del dia martes 16 de junio del 2015Turno de 7-9Clase animal

Page 96: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 258 -

Public Class ANIMAL Protected Nombre1 As String Protected Peso1 As Single Protected foto1 As String Public Event Evento1(ByVal Valor As Single) Property Nombre As String Get Nombre = Nombre1 End Get Set(value As String) Nombre1 = value End Set End Property Property Peso As Single Get Peso = Peso1 End Get Set(value As Single) If Peso > 10 And Peso < 2000 Then RaiseEvent Evento1(value) Else Peso1 = value End If End Set End Property Property foto As String Get foto = foto1 End Get Set(value As String) foto1 = value End Set End Property Sub New(Optional nombre2 As String = "Animal", _ Optional peso2 As Single = 0, Optional foto2 As String = "sin foto") Nombre1 = nombre2 Peso1 = peso2 foto1 = foto2 End Sub Function MostrarValor() As String Dim cadena As String cadena = "Nombre " + Nombre1 + vbCrLf + "peso " + Peso1 + "foto " + foto1 Return cadena

End FunctionEnd Class

Page 97: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 259 -

Public Class Form1 Dim objeto As ANIMAL Dim gato As ANIMAL Dim perro As ANIMAL Private WithEvents vaca As ANIMAL

Private Sub btnCrear1(sender As Object, e As EventArgs) Handles btnCrear.Click ' objeto = New ANIMAL() gato = New ANIMAL("GARFIELD", 2, "Garfield.BMP") 'perro = New ANIMAL("FIDO") 'vaca = New ANIMAL 'vaca.Nombre = "MANUELA" 'vaca.Peso = 400

End Sub

Private Sub EVENTOVACA(valor As Single) Handles vaca.Evento1 MsgBox("INGRESE PESO CORRETO" & valor) End Sub

Private Sub BTNtDOS_Click(sender As Object, e As EventArgs) Handles BTNtDOS.Click ListBox1.Items.Add("OBJETO " & objeto.MostrarValor) ListBox1.Items.Add("GATO " & gato.MostrarValor) ListBox1.Items.Add("PERRO " & perro.MostrarValor) ListBox1.Items.Add("VACA " & vaca.MostrarValor) TextBox4.Text = objeto.MostrarValor End Sub

Private Sub BTNgENERAR_Click(sender As Object, e As EventArgs) Handles BTNgENERAR.Click vaca.Peso = -400

Page 98: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 260 -

End Sub Private Sub btnCrear_Click(sender As Object, e As EventArgs) Handles btnCrear.Click ' objeto = New ANIMAL() gato = New ANIMAL("GARFIELD", 2, "E:\DATOS\avion1.BMP") 'perro = New ANIMAL("FIDO") 'vaca = New ANIMAL 'vaca.Nombre = "MANUELA" 'vaca.Peso = 400

End Sub Private Sub btnMostrar_Click(sender As Object, e As EventArgs) Handles btnMostrar.Click TxtNombre.Text = gato.Nombre txtPeso.Text = gato.Peso txtFoto.Text = gato.foto Dim NOMBRE As String NOMBRE = "E:\DATOS\avion1.bmp" PictureBox1.Load(NOMBRE)

End SubEnd Class

Public Class ANIMAL Protected Nombre1 As String Protected Peso1 As Single Protected foto1 As String Public Event Evento1(ByVal Valor As Single) Property Nombre As String Get Nombre = Nombre1 End Get Set(value As String) Nombre1 = value End Set End Property Property Peso As Single Get Peso = Peso1 End Get Set(value As Single) If Peso < 0 Then RaiseEvent Evento1(value)

Else Peso1 = value

End If End Set End Property Property foto As String Get

Page 99: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 261 -

foto = foto1 End Get Set(value As String) foto1 = value End Set End Property Sub New(Optional nombre2 As String = "Animal", _ Optional peso2 As Single = 0, Optional foto2 As String = "sin foto") Nombre1 = nombre2 Peso1 = peso2 foto1 = foto2 End Sub Function MostrarValor() As String Dim cadena As String cadena = "Nombre " + Nombre1 + vbCrLf + "peso " + CStr(Peso1) + vbCrLf + "foto " + foto1 Return cadena

End FunctionEnd Class

CLASE ESTADISTICA MODO CONSOLAClase del miercoles 17 de junio del 2015

Código de la clase

Page 100: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 262 -

Public Class ESTADISTICA Const maxdatos As Integer = 10 Protected N1 As Integer ' cantidad de datos Protected A(maxdatos) As Single Protected Prom1 As Single Protected suma1 As Single Protected max1 As Single Protected min1 As Single Public Event Evento1(ByVal Valor As Single) Property N As Integer Get N = N1 End Get Set(value As Integer) If value < 2 Then RaiseEvent Evento1(value) End If N1 = value End Set End Property public readonly Property Prom As Single Get Prom1 = Prom End Get End Property Sub New(Optional Ndatos As Integer = 3) Dim fila As Integer N1 = Ndatos For fila = 0 To N1 - 1 A(fila) = fila + 1 Next End Sub Sub Asignar(A1() As Single, ndatos As Integer) Dim fila As Integer Dim mayor As Single = -1000 Dim menor As Single = 1000 Dim suma As Single = 0 N1 = ndatos For fila = 0 To N1 - 1 A(fila) = A1(fila) suma = suma + A(fila)

Page 101: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 263 -

If A(fila) > mayor Then mayor = A(fila) If A(fila) < menor Then menor = A(fila) Next suma1 = suma Prom1 = suma1 / N1 max1 = mayor min1 = menor End Sub Function VerDatos() As String Dim fila As Integer Dim cadena As String = "" For fila = 0 To N1 - 1 cadena = cadena + vbCrLf + CStr(A(fila)) Next Return cadena End Function Function VerResultados() As String Dim cadena As String cadena = "Prom " + CStr(Prom1) + vbCrLf + "Suma1" + CStr(suma1) + _ "max1 " + CStr(max1) + "Min " + CStr(min1) VerResultados = cadena End FunctionEnd Class

CODIGO DEL MODULO

Module Module1 Dim objeto As ESTADISTICA Dim ob2 As ESTADISTICA Dim WithEvents Ob3 As ESTADISTICA Dim A(100) As ESTADISTICA Dim X(100) As Single

Sub Main() X(0) = 11 X(1) = 14 X(2) = 13 objeto = New ESTADISTICA ob2 = New ESTADISTICA(5) Ob3 = New ESTADISTICA Console.WriteLine(" datos del objeto {0}", objeto.VerDatos()) Console.WriteLine("resultadasod {0} ", objeto.VerResultados()) objeto.Asignar(X, 3) Console.WriteLine(" datos del objeto {0}", objeto.VerDatos()) Console.WriteLine("resultadasod {0} ", objeto.VerResultados()) Console.ReadLine() End Sub Private Sub proc1(ByVal Valor As Single) Handles Ob3.Evento1 MsgBox(" ingrese valores mayore que 2" & Valor) End SubEnd Module

Page 102: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 264 -

CLASE ESTADISTICA EN MODO FORMULARIO

CODIGO DE LA CLASE MODIFICADOPublic Class ESTADISTICA Const maxdatos As Integer = 10 Protected N1 As Integer ' cantidad de datos Protected A(maxdatos) As Single Protected Prom1 As Single Protected suma1 As Single Protected max1 As Single Protected min1 As Single Public Event Evento1(ByVal Valor As Single) Public Property N As Integer Get N = N1 End Get Set(value As Integer) If value < 2 Then RaiseEvent Evento1(value) End If N1 = value End Set End Property

Public ReadOnly Property Prom As Single Get Prom1 = Prom End Get End Property Public Sub New(Optional Ndatos As Integer = 3) Dim fila As Integer

Page 103: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 265 -

N1 = Ndatos For fila = 0 To N1 - 1 A(fila) = fila + 1 Next End Sub Public Sub Asignar(A1() As Single, ndatos As Integer) Dim fila As Integer Dim mayor As Single = -1000 Dim menor As Single = 1000 Dim suma As Single = 0 N1 = ndatos For fila = 0 To N1 - 1 A(fila) = A1(fila) suma = suma + A(fila) If A(fila) > mayor Then mayor = A(fila) If A(fila) < menor Then menor = A(fila) Next suma1 = suma Prom1 = suma1 / N1 max1 = mayor min1 = menor End Sub Public Function VerDatos() As String Dim fila As Integer Dim cadena As String = "" For fila = 0 To N1 - 1 cadena = cadena + vbCrLf + CStr(A(fila)) Next Return cadena End Function Public Function VerResultados() As Single() Dim Vector(5) As Single Vector(0) = N1 Vector(1) = suma1 Vector(2) = Prom1 Vector(3) = max1 Vector(4) = min1

VerResultados = Vector

End FunctionEnd Class

CODIGO DEL FORMULARIO

Imports System.IOPublic Class Form1 Dim Maxdatos As Integer = 10 Dim Vector(Maxdatos) As Single Dim VR(Maxdatos) As Single Dim objeto As ESTADISTICA Dim Nd As Integer = 3

Page 104: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 266 -

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load DataGridView1.ColumnCount = 2 DataGridView1.Columns(0).Width = 50 DataGridView1.Columns(1).Width = 100 DataGridView1.Columns(0).HeaderText = "Dato" DataGridView1.Columns(1).HeaderText = "Valor"

DataGridView2.RowCount = 5 DataGridView2.ColumnCount = 2 DataGridView2.Columns(0).Width = 50 DataGridView2.Columns(1).Width = 100 DataGridView2.Columns(0).HeaderText = "Resultado" DataGridView2.Columns(1).HeaderText = "Valor" DataGridView2.Rows(0).Cells(0).Value = "N " DataGridView2.Rows(1).Cells(0).Value = "Suma " DataGridView2.Rows(2).Cells(0).Value = " Promedio" DataGridView2.Rows(3).Cells(0).Value = "Maximo " DataGridView2.Rows(4).Cells(0).Value = "Minimo " End Sub

Private Sub btnIniciar_Click(sender As Object, e As EventArgs) Handles btnIniciar.Click Dim fila As Integer Nd = Val(txtN.Text) DataGridView1.RowCount = Nd + 1 For fila = 0 To Nd - 1 DataGridView1.Rows(fila).Cells(0).Value = fila + 1 Next End Sub

Private Sub btnCrear_Click(sender As Object, e As EventArgs) Handles btnCrear.Click Dim fila As Integer For fila = 0 To Nd - 1 Vector(fila) = DataGridView1.Rows(fila).Cells(1).Value Next objeto = New ESTADISTICA() objeto.Asignar(Vector, Nd) End Sub Private Sub btnMostrar_Click(sender As Object, e As EventArgs) Handles btnMostrar.Click TextBox1.Text = objeto.VerDatos VR = objeto.VerResultados() DataGridView2.Rows(0).Cells(1).Value = VR(0) DataGridView2.Rows(1).Cells(1).Value = VR(1) DataGridView2.Rows(2).Cells(1).Value = VR(2) DataGridView2.Rows(3).Cells(1).Value = VR(3) DataGridView2.Rows(4).Cells(1).Value = VR(4) End Sub

Private Sub BtnAbrir_Click(sender As Object, e As EventArgs) Handles BtnAbrir.Click Dim Cadena As String

Page 105: Plsi2015a-3 Clases y Objetos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Véliz Vilca - 267 -

Dim cont As Integer = 0 Dim fila As Integer OpenFileDialog1.ShowDialog() Dim archivo As New StreamReader(OpenFileDialog1.FileName) Cadena = archivo.ReadLine() Vector(0) = CSng(Cadena) Do While Not (Cadena Is Nothing) Vector(cont) = CSng(Cadena) Cadena = archivo.ReadLine() cont = cont + 1 Loop Nd = cont txtN.Text = Nd btnIniciar_Click(sender, e)

For fila = 0 To Nd - 1 DataGridView1.Rows(fila).Cells(1).Value = Vector(fila) Next archivo.Close() objeto = New ESTADISTICA() objeto.Asignar(Vector, Nd) End Sub

Private Sub BtnGrabar_Click(sender As Object, e As EventArgs) Handles BtnGrabar.Click SaveFileDialog1.ShowDialog() Dim archivo As New StreamWriter(SaveFileDialog1.FileName) For fila = 0 To Nd - 1 archivo.WriteLine("{0}", Vector(fila)) Next archivo.Close() End SubEnd Class

CLASE PRODUCTO