Está en la página 1de 106

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz 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 aplicacin de modo consola y ponga nombre
al proyecto como APCIRCULO

2 clic derecho sobre el proyecto


Elegir ver diagrama de clases

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

3 Debe aparecer lo siguiente

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

- 164 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

2. Poner el nombre de la clase circulo

3. Al hacer en aceptar aparece los siguiente

- 165 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 166 -

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

Se puede agregar uno a uno las propiedades , campos, mtodos , eventos,


constructores, destructores y constantes
Pero existe otra manera mas rpida de agregar esos atributos
8 Para ello clic derecho en la clase y luego detalles de la clase

9. Aparecer lo siguiente

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 167 -

10. Llene esos atributos con los siguientes valores

11.Al presionar enter el diseador muestra el siguiente cdigo


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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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

- 168 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 169 -

6. Se puede modificar el cdigo por ejemplo la propiedad Area es de solo lectura

13. Agregar la clase cilindro

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 170 -

14. Ponga los siguientes valores

15 . El cdigo 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 Sub
End Class

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 171 -

16. Se puede modificar el cdigo 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 herencia


Si no se muestra la herramienta hacer clic

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

19.arrastre del cilindro al circulo


Aparece lo siguiente

20 El cdigo de la clase cilindro se modifica a

- 172 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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

22 Arrastre el interface y agregue uno nuevo

- 173 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 174 -

e
23 Con la herramienta de la herencia agrega las clases circulo y al mtodo nombre al
final la estructura debe quedar de la siguiente manera
Para implementar una interfaz trazando una lnea de herencia
1. En el diagrama de clases, muestre la interfaz y la clase que implementar la
interfaz.
2. Trace una lnea de herencia desde la clase a la interfaz.
Y debe aparece lo siguiente

24. El cdigo de la clase Interface es lo siguiente


Public Interface ICirculo

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 175 -

End Interface
25. el Nuevo cdigo de la clase circulo es

IMPLEMENTAR LA CLASE CIRCULO CON EVENTOS se muestra el siguiente


codigo
Implementar dos eventos para la clasecrculo
Evento 1. Sedispara cuandoel radio es negativo
Evento 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 176 -

Complete con el siguiente cdigo


CLASE CIRCULO
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)
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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 177 -

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
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 Function
End 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 178 -

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 Function
End Class
Para que funcione la aplicacion hay que poner el cdigo(proyecto agregar modulo)
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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 179 -

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 Sub
End Module
Inteligence sense

CLASES CON CONSTRUCTORES


7 Agregue el siguiente constructor a la clase circulo
Public Sub New(Optional ByVal r As Integer = 10)
Radio = r
End Sub
Declarar 100 objetos de tipos circulo
Tarea
1 Se tiene la clase factorial derivar la clase combinatoria,implemente su propeidades y
mtodos de cada clase
2. Se ingresa cdigo y nombres de n alumnos usando POO elabore una aplicacin que
permita ingresar, mostrar, datos, buscar, grabar, recuperar datos, etc.
3. Implemente una clase llamada estadstica que deber tener los siguiente miembros
Propiedades
N: Nmero de datos ( propiedad de lectura y escritura
Suma, promedio, mediana, moda , mayor, menor desviacion tipica etc.( propiedades de
solo lectura
Mtodos

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 180 -

Ingresar. permite ingresar n datos a un arreglo


Procesar. Procesa y encuentra los valores de Suma, promedio,mediana, moda, el
mayor , el menor , desviacin 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 PROBARCIRCULO
Para ello agregue

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

Los componentes del proyecto seria

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

3 Puede ver los conponentes de la clase Circulo F2

6 Disee en el formulario lo siguiente

- 181 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 182 -

6 continuacin proceda a establecer las propiedades segn se indica:


Objeto
Propiedad
Valor
Form1
Text
Propiedades metodos y eventos clase circulo.
Datagridview Text
Radio
1
Texbox1
name
txtResultado
GroupBox1
Text
CIRCULO
GroupBox2
Text
CILINDRO
RadioButton1 Nombre
rbCirculoObtener
RadioButton2 Nombre
rbCirculoMostrar
RadioButton3 Nombre
rbCilindroObtener
RadioButton4 Nombre
rbCilindroMostrar
7 Grabe con el nombre de circulo

9 Escriba el siguiente codigo en el formulario

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 183 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 184 -

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 Sub
End 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

+
Agregue el siguiente codigo al boton propiedades
Private Sub btnPropiedades_Click(sender As Object, e As EventArgs) Handles
btnPropiedades.Click

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 185 -

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 Sub
ELABORACION DE CONTROL DE USUARIO EN VISUAL ESTUDIO 2012( o
controles personalizados)
Paso 1
Agregue un con control de usuario con

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

Paso 2
Disee el siguiente formulario

1. Implemente el siguiente cdigo


Public Class UCirculo
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 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)

- 186 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 187 -

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 Sub
End Class
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 dilogo 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 dilogo Agregar nuevo elemento, seleccione Control de usuario.
5. En el cuadro Nombre, escriba NamesControl y haga clic en Agregar.

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

Paso 5 generar la aplicacion

Paso 6 iniciar Nuevo proyecto para probarlos

- 188 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

Paso 7 en la barra de herramienta escoja elegir elemento

8 Escoja el botn examinar

- 189 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

8 Buscar el archivo .dll generado

9 Seleccionar y abrir

- 190 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

10 . el control ya aparece en la barra de herramientas

Cree dos objetos circulo Como se muestra

- 191 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 192 -

Y AGREGUE EL siguiente cdigo


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 Sub
End Class

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

EJEMPLOS DE CLASES Y OBJETOS EN VISUAL BASIC 2012


TAREA.- Defina la clase Operacion que tiene los siguientes miembros
Propiedades
Nro1: Propiedad para modificar el primer nmero
Nro2: propiedad para modificar el segundo nuemero cilindro
Res: resultado de la operacin propiedad de solo lectura
Mtodos
Ingresar : permite ingresar dos nmeros reales
Sumar.- funcin que permite sumar los nmeros ingresados
Restar.- funcin que permite restar los nmeros ingresados
Option Explicit On
Option Strict On
Public 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

- 193 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 194 -

Get
Return R
End Get
End Property
End Class
Cdigo del mdulo
Option Explicit On
Option Strict On
Module 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 Sub
End Module
El objeto llamado Operacin debera tener los siguientes mtodos y propiedades

EJEMPLOS REALIZADOS EL SEMESTRE ANTERIOR 2014 (MEJORADO)


PRACTICAS DEL LUNES 2 DE JUNIO DEL 2014
Clase Cuenta
Diagram de clases

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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

- 195 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 196 -

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 Sub
End 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 197 -

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 Sub
End 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 Sub
End Class
Module Module1
Dim Juan As PERSONA
Sub Main()
Juan = New PERSONA
Juan.ingresar()
Juan.VerDatos()
Console.ReadLine()
End Sub
End 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",
Dn1 As Integer = 11111)
Nombre = nombre1
DNI = Dn1

Optional

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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 Sub
End Class
Module 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 Sub
End Module
Ejecicio con propiedades

Option Explicit On
Option Strict On
Public 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

- 198 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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 Sub
End Class
Option Explicit On
Option Strict On
Module 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 Sub
End Module
CLASES Y OBJETOS CON ARREGLOS

Public Class PERSONA


Protected Nombre1 As String

- 199 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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 Sub
End Class
Module 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 Sub
End Module
Modificar un elemento del arreglo de objetos

- 200 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 201 -

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 Sub
End Module
Implementacion de eventos

Option Explicit On
Option Strict On

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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 Sub
End 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

- 202 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 203 -

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")

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 204 -

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 Sub
End 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 Sub
End Module
PRACTICA DEL MIERCOLES 28 DE MAYO DEL 2014
CLASE VEHICULOS

Public Class Vehiculo


Protected placa As String
Protected propietario As String
Protected ao As String
Sub IngresarDatos()
Console.Write("Ingrese Placa")
placa = Console.ReadLine
Console.Write("Ingrese Propietario")
propietario = Console.ReadLine

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 205 -

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

Public Class Vehiculo


Protected placa As String
Protected propietario As String
Protected ao As Integer
Public Sub New(Optional ByVal placa2 As String = "sin placa", Optional ByVal pro2
As String = "sin dueo",
Optional ByVal ao2 As Integer = 0)
placa = placa2
propietario = pro2
ao = ao2
End Sub
Sub IngresarDatos()
Console.Write("Ingrese Placa") : placa = Console.ReadLine
Console.Write("Ingrese Propietario") : propietario = Console.ReadLine
Console.Write("Ingrese Ao") : ao = Console.ReadLine
End Sub
Sub VerDatos()
Console.WriteLine("Placa {0} Propietario {1} Ao {2} ", placa, propietario, ao)
End Sub
Sub Encender()

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 206 -

Console.WriteLine(" Carro Encedido")


End Sub
Sub Apagar()
Console.WriteLine(" Carro APAGADO")
End Sub
End Class
Module 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 Sub
End Module
Public Class Vehiculo
Protected placa1 As String
Protected propietario1 As String
Protected ao1 As Integer
Public Sub New(Optional ByVal placa2 As String = "sin placa", Optional ByVal pro2
As String = "sin dueo", _
Optional ByVal ao2 As Integer = 0)
placa1 = placa2
propietario1 = pro2
ao1 = ao2
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 Ao") : ao = Console.ReadLine
End Sub
Sub VerDatos()
Console.WriteLine("Placa {0} Propietario {1} Ao {2} ", placa, propietario, ao)
End Sub
Sub Encender()
Console.WriteLine(" Carro Encedido")
End Sub
Sub Apagar()
Console.WriteLine(" Carro APAGADO")

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

End Sub
End Class
Module Module1
Dim DUEOS(100) As Vehiculo
Sub Main()
Dim n = 100, i As Integer
For i = 0 To n - 1
DUEOS(i) = New Vehiculo("A" & i, "Dueo " & i, 0)
Next
For i = 0 To n - 1
DUEOS(i).VerDatos()
Next
DUEOS(4).propietario = "juan perez"
Console.ReadLine()
End Sub
End 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 Sub
End Class
Module Module1
Dim Objeto1, objeto2 As ESTADISTICA

- 207 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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

Diagrama de clases

SOLUCIONES DE EXAMENES
GRUPO1 Lunes de 16 a 18 horas
Public Class Form1

- 208 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 209 -

Private Sub AgregarEmpleadoToolStripMenuItem_Click(ByVal sender As Object,


ByVal e As EventArgs) Handles AgregarEmpleadoToolStripMenuItem.Click
Form2.ShowDialog()
End Sub
End 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 210 -

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 Sub
End Class

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 211 -

Public Class Form3


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

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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 Property
End 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 Property
End Class

- 212 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 213 -

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 Sub
End 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()

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 214 -

End Sub
End 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 215 -

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 Sub
End Class
Public Class Form3
Private Sub btnCerrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles
btnCerrar.Click
Me.Close()
End Sub
End Class

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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

- 216 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 217 -

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.Ao = 2012
TextBox1.Text = auto1.Propietario
TextBox2.Text = auto2.Propietario
TextBox3.Text = auto2.Modelo
TextBox4.Text = auto2.Ao
End Sub
End 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 Sub
End Class

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 218 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 219 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 220 -

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 Sub
End Class

Public Class Form3


Private Sub btnCerrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles
btnCerrar.Click
Me.Close()
End Sub
End Class
Implemente la clase circulo que se deriva de la clase punto

Public Class Punto

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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 Property
End 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 Property
End Class

Public Class Form1


Dim p1 As Punto
Dim p2 As Circulo

- 221 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 222 -

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 Sub
End Class
PREGUNTA 4 TURNO MIERCOLES DE 11 A13 HORAS
CLASE 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 223 -

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()

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 224 -

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 Sub
End Class

Public Class Form3


Private Sub btnCerrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles
btnCerrar.Click
Me.Close()
End Sub
Clase animal
Seores alumnos de sistemas de informacin 2015A
Se enva material para el curso de SI2015A
En las prcticas de laboratorio de esta semana se revisara los trabajos 1 y 2, se
asignara temas por grupo de prcticas 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
puntos
Tercera prctica 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 225 -

Blog www.incanato.site90.com
Juan Carlos Arcila Daz
Chiclayo - Per
Enero 2014
Se realizar Prcticas para el examen (del primer y segundo trabajo)
Se preguntara sobre recursividad. Solucin de las preguntas del examen tentativo
Como realizar macros en excel
MDI hay 3 formularios hechos (mostrar su modificaciones)
- Preguntas sobre controles button, textbox, cuadros de listas, cuadros
combinados, men strip,menus contextuales, cuadros de dilogos, eventos del
mouse y del teclado, cajas de dialogo (open files dialog,etc )
- Creacin de formularios y controles en tiempo de ejecucin
- Input box, message box, timer animacin sencilla
- Propiedades mtodos eventos
- Grficos
- Procedimientos de eventos
En evaluacin de expresiones hay 2 trabajos
Archivos, escritura lectura, leer una matriz, grabar los Valores de una funcin
Cadenas. Elaborar funciones de cadenas, ejemplo buscar una su cadena, reemplazar
una su cadena ,
Trabajo adicional juego
Matrices mostrar una parte de una matriz,
Preguntas sobre clases y objetos
1. crear una clase con sus propiedades, campos, mtodos, eventos
2. Usar la clase creada en modo consola o formulario
Saludos
Ing. Veliz
SISTEMA EJEMPLO DE CLASES Y OBJETOS ( CLASE VEHICULO)

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 226 -

Public Class VEHICULO


Private nro1 As Integer
Private Ao1 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 ao2 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
Ao1 = ao2
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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

Public Property Nro As Integer


Get
Nro = nro1
End Get
Set(value As Integer)
nro1 = value
End Set
End Property
Public Property Ao As Integer
Get
Ao = Ao1
End Get
Set(value As Integer)
Ao1 = 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

- 227 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 228 -

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 Sub
End Class
' *** CLASE FORMULARIO
Imports System.IO
Public 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.Ao
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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 229 -

' 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
FORD FOTO1
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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 230 -

fila = DataGridView1.CurrentRow.Index
objeto = autos(fila)
txtNro.Text = objeto.Nro
txtAo.Text = objeto.Ao
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 Sub
End Class
PRACTICAS SI 2015 DEL DIA MARTES 09 DE JUNIO DEL 2015
Turno de 5 a 7 pm
Elaborar la siguiente aplicacin

Imports System.IO
Public 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 231 -

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 Sub
End Class
PRACTICAS DE 7-9 PM DEL DIA MARTES 09 DE JUNIO DEL 2015
Creacion de controles en tiempo de ejecucion

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 232 -

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 Sub
End Class
Mostrar la hora cada interval de tiempo en una etiquetay que cambia de color el
formulario s emueve por la pantalla

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 233 -

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 Sub
End Class

Formularios que se mueven

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 234 -

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 Sub
End Class
Mover un control en un contenedor a la vez se mueve el formulario

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 235 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 236 -

If cont Mod 2 = 0 Then


Label1.ForeColor = Color.Red
Else
Label1.ForeColor = Color.Green
End If
cont = cont + 1
End Sub
End 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 237 -

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 Sub
End Class
Practicas miercoles 7 miercoles 10 de junio del 2015
Abrir y grabar un archivo
Imports System.IO
Public 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 238 -

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 Sub
End Class
Ejemplo de cadenas

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 239 -

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 Function
End 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 240 -

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 Sub
End Class
Contar palabras

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 241 -

Se debe lleer de un archive uo aumentar esacio en cadalliena


Module 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)

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 242 -

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 Function
End Module
CODIGO DEL FORMULARIO
Public Class Form1
Function ContarPalabras(cadena() As String, cad1 As String, nf As Integer) As
Integer

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 243 -

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 Sub
End Class
Clases del jueves 11 junio del 20015 9-11
Crear un formulario en tiempo de ejecucion

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 244 -

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 Sub
End 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 Sub
End 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 automtica 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 245 -

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 Sub
End Class
SELECCIONAR TEXTO EN TEXTBOX
Botn textbox
Establecer texto seleccionado en un control textbox
textBox1.Text = "Hello World";
textBox1.Select(6, 5);
MessageBox.Show(textBox1.SelectedText);
Usando con la opcin selectstar

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 246 -

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 Sub
End Class
Seleccione el texto con el mouse y ,muestre

Para seleccionar todo


Private 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 247 -

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 Sub
End Class
Seleccin con el control richt textbox
El RichTextBox control permite al usuario introducir y editar texto mientras que
tambin proporciona caractersticas de formato ms 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 Sub
End Class
Diferencia entre textbox y RichTextBox

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 248 -

Se puede usar tambin la seleccin


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
Tambin funciona con select all
Selecciona 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 Sub
En ritchtextbox se puede pegar graficos
Como grabar un texto enriquecido en recht box
Richt textbox

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 249 -

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 Sub
End Class
EJEMPLO SIMPLIFICADO DE UN CONTROL RichTextBox1

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

CODIGO DEL MODULO


Module 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

- 250 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 251 -

Case 2
For fila = 1 To ne - 1
cadres = cadres + cadena(fila)
Next
cadres = cadres + cadena(0)
End Select
Return cadres
End Function
End Module
CODIGO DEL FORMULARIO
Public 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 252 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 253 -

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 Sub
End Class
Practicas del martes 16 d ejunio del 2015
Turno de 5-7 pm
Clase 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 254 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 255 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 256 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 257 -

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 Sub
End 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("Lnea: {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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

'
'
'

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

'Catch ex As Exception
' MsgBox(ex.Message)
'End Try
End Sub
End Class
Practicas del dia martes 16 de junio del 2015
Turno de 7-9
Clase animal

- 258 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 259 -

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 Function
End Class

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 260 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 261 -

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 Sub
End 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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 262 -

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 Function
End Class
CLASE ESTADISTICA MODO CONSOLA
Clase del miercoles 17 de junio del 2015

Cdigo de la clase

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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)

- 263 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 264 -

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 Function
End 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 Sub
End Module

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

CLASE ESTADISTICA EN MODO FORMULARIO

CODIGO DE LA CLASE MODIFICADO


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

- 265 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

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 Function
End Class
CODIGO DEL FORMULARIO
Imports System.IO
Public 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

- 266 -

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 267 -

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

Plab Si2015A\ 3 Clases y Objetos en Visual Basic / Ismael Vliz Vilca

- 268 -

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 Sub
End Class
CLASE PRODUCTO