Ejercicio Nº 6
Desarrollar la sumadora de dos sumandos mostrada a continuación:
Pasos:
1. Insertar siete etiquetas, dos cajas de texto y un botón
2. Diseñar el formulario a satisfacción con el menú de propiedades
haciendo click con el botón derecho en cada control.
3. Generar el código que se muestra a continuación
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Dim num1, num2, product As Single
On Error GoTo corrector
num1 = TextBox1.Text
num2 = TextBox2.Text
product = num1 + num2
Label7.Text = Format(product, "FIXED")
Exit Sub 'Para no ingresar a la rutina de error cuando los datos _
'son(válidos)
corrector:
Label7.Text = "Dato no numérico"
End Sub
Function s1() As String
s1 = System.Globalization.CultureInfo.CurrentCulture.NumberFormat._
CurrencyDecimalSeparator()
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
Label3.Text = "99999" & s1() & "99"
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress
Dim h As Integer
Dim cadena As String
If InStr(1, "0123456789-" & Chr(8) & s1(), e.KeyChar) = 0 Then
e.KeyChar = ""
Else
h = Len(TextBox1.Text) ' Longitud de cadena
cadena = TextBox1.Text ' Almacena lo escrito en el textbox,
' sin incluir el último caracter
For p = 1 To h
If Mid(cadena, p, 1) = s1() Then ' Si ya hay UN SEPARADOR
'DECIMAL en la cadena...
If e.KeyChar = s1() Then
e.KeyChar = ""
Exit For
End If
End If
Next p
For p = 1 To h
If Mid(cadena, p, 1) = "-" Then ' Si ya hay un signo -
'en la cadena...
If e.KeyChar = "-" Then
e.KeyChar = ""
Exit For
End If
End If
Next p
End If
End Sub
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox2.KeyPress
Dim h As Integer
Dim cadena As String
If InStr(1, "0123456789-" & Chr(8) & s1(), e.KeyChar) = 0 Then
e.KeyChar = ""
Else
h = Len(TextBox2.Text) ' Longitud de cadena
cadena = TextBox2.Text ' Almacena lo escrito en el textbox,
'sin incluir el último caracter
For p = 1 To h
If Mid(cadena, p, 1) = s1() Then ' Si ya hay UN SEPARADOR
'DECIMAL en la cadena...
If e.KeyChar = s1() Then
e.KeyChar = ""
Exit For
End If
End If
Next p
For p = 1 To h
If Mid(cadena, p, 1) = "-" Then ' Si ya hay un signo -
'en la cadena...
If e.KeyChar = "-" Then
e.KeyChar = ""
Exit For
End If
End If
Next p
End If
End Sub
End Class
Observaciones:
1. Se usó una función para obtener el separador de decimales
Function s1() As String
2. Se validó el ingreso de texto a la caja de texto Nº 2.
Ejercicio Nº 7
Desarrollar utilizando solamente un textbox y con todos los casos posibles de evaluación, la sumadora que se muestra a continuación:
Observación:
Únicamente se aceptará un solo signo + (de la suma) en la línea.
Pasos:
1. Crear el formulario con una caja de texto
2. Crear el módulo de variables públicas con Proyecto/Agregar Nuevo Elemento/Módulo
'**********
Module variablesGLOBALES
Public cadena As String ' Cadena que se ingresará en la caja de texto
' y que variará continuamente.
Public signo As String = "+" 'Alternará a = para el segundo sumando
Public menos As String = "-" ' Para chequear que los sumandos tengan
' signo - solamente a la izquierda
Public posicion_mas As Integer = 0 'Posición que separa los sumandos
End Module
'*********
3. Generar el código
Public Class Form1
Function s1() As String
' Obtención del separador de decimales de la cultura corriente
s1 = System.Globalization.CultureInfo.CurrentCulture.NumberFormat._
CurrencyDecimalSeparator()
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
TextBox1.Text = "" 'Coloca el cursor en el inicio de la
' caja de texto
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress
Dim h As Integer
Dim num1, num2, product As Single
If signo = "+" Then
cadena = TextBox1.Text 'Significa que estamos ingresando
' el primer sumando
Else '0
cadena = Mid(TextBox1.Text, posicion_mas)
' Representa el segundo sumando incluyendo el signo +
End If
If UCase(e.KeyChar) <> "C" And e.KeyChar <> Chr(8) Then
' Si la tecla pulsada es distinta de C para borrar ó
' backspace
If InStr(1, "0123456789" & menos & s1() & signo, e.KeyChar) = 0 Then
e.KeyChar = "" ' solo e permiten caracters válidos
Else '1
h = Len(cadena) ' Longitud de cadena (no incluye el último CHAR
' ingresado
If e.KeyChar <> "=" Then 'Si es = se procede a sumar
If e.KeyChar = "-" Then
menos = "" 'Permitir un solo - al inicio del sumando
If (h > 0 And posicion_mas = 0) Then
e.KeyChar = ""
End If
If (h > 1 And posicion_mas > 0) Then
e.KeyChar = ""
End If
End If
If e.KeyChar = "+" Then
signo = "="
menos = "-"
posicion_mas = h + 1
Else
For p = 1 To h
If Mid(cadena, p, 1) = s1() Then ' Si ya hay UN
' SEPARADOR DECIMAL en la cadena...
If e.KeyChar = s1() Then
e.KeyChar = "" ' anula el ingreso segundo
' separador de decimales
Exit For
End If
End If
Next p
For p = 1 To h
If Mid(cadena, p, 1) = "-" Then ' Si ya hay un signo -
'en la cadena...
If e.KeyChar = "-" Then
e.KeyChar = "" 'anula el ingreso del segundo -
Exit For
End If
End If
Next p
End If
Else
cadena = TextBox1.Text
' Obtención del primer sumando
If posicion_mas - 1 >= 2 Then
If Mid(TextBox1.Text, posicion_mas - 1, 1) = "-" Then
num1 = Mid(TextBox1.Text, 1, posicion_mas - 2)
Else
num1 = Mid(TextBox1.Text, 1, posicion_mas - 1)
End If
Else
If Mid(TextBox1.Text, 1, 1) = "-" Then
num1 = 0
Else
If Mid(TextBox1.Text, 1, 1) = "+" Then
num1 = 0
Else
num1 = Mid(TextBox1.Text, 1, 1)
End If
End If
End If
e.Handled = True 'para que no ingrese el =
h = Len(TextBox1.Text) + 1
'Obtención del segundo sumando
If h - posicion_mas >= 3 Then
If Mid(TextBox1.Text, Len(TextBox1.Text), 1) = "-" Then
num2 = Mid(TextBox1.Text, posicion_mas + 1, _
h - posicion_mas - 2)
Else
num2 = Mid(TextBox1.Text, posicion_mas + 1)
End If
Else
If h - posicion_mas = 2 Then
If Mid(TextBox1.Text, posicion_mas + 1, 1) = "-" Then
num2 = 0
Else
num2 = Mid(TextBox1.Text, posicion_mas + 1, 1)
End If
Else
num2 = 0
End If
End If
product = num1 + num2
TextBox1.Text = cadena + " = " + Format(product, "FIXED") + _
" Pulse c para borrar"
End If
End If '
Else
If UCase(e.KeyChar) = "C" Then
e.KeyChar = ""
signo = "+"
menos = "-"
TextBox1.Text = ""
Else
If signo = "=" Then
If Mid(TextBox1.Text, Len(TextBox1.Text), 1) = "+" Then
signo = "+"
menos = "-"
e.Handled = False
End If
Else
End If
End If
End If
End Sub
End Class
Ejercicio Nº 8
Obtener el máximo de cuatro números dados
1. Colocar en el formulario:
2 labels
4 cajas de texto
1 botón
2. Configurar el textbox1 para que el cursor se coloque en posición de edición
Colocar 0 enTabIndex
3. Ingresar el código
Public Class Form1
Function s2() As Single
' Devuelve 0 si la tecla pulsada no es numérica
s2 = InStr(1, "0123456789", teclado)
End Function
Function Maximo(ByVal ParamArray arreglo() As Object) As Object
'Devuelve el número máximo de entre una lista
Dim indice As Integer
Dim temporal As Object
temporal = arreglo(LBound(arreglo))
For indice = LBound(arreglo) + 1 To UBound(arreglo)
If arreglo(indice) > temporal Then
temporal = arreglo(indice)
End If
Next indice
Maximo = temporal
End Function
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress
teclado = e.KeyChar
If s2() = 0 Then
e.KeyChar = ""
End If
End Sub
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox2.KeyPress
'*******
teclado = e.KeyChar
If s2() = 0 Then
e.KeyChar = ""
End If
End Sub
Private Sub TextBox3_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox3.KeyPress
teclado = e.KeyChar
If s2() = 0 Then
e.KeyChar = ""
End If
End Sub
Private Sub TextBox4_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox4.KeyPress
teclado = e.KeyChar
If s2() = 0 Then
e.KeyChar = ""
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Dim num1 As Single, num2 As Single, num3 As Single, num4 As Single
Dim respuesta As Single
num1 = TextBox1.Text
num2 = TextBox2.Text
num3 = TextBox3.Text
num4 = TextBox4.Text
respuesta = Maximo(num1, num2, num3, num4)
Label2.Text = respuesta
End Sub
End Class
Ejercicio Nº 9
Desarrollar la carta de pago que se muestra a continuación:
Código
Module Module1
Public luz As Integer = 100
Public agua As Integer = 200
Public telefono As Integer = 300
End Module
Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
Label1.Text = luz
Label2.Text = agua
Label3.Text = telefono
Label5.Text = "Agua"
Label6.Text = "Luz"
Label7.Text = "Teléfono"
Label8.Text = "Total"
Label9.Text = "Relación de gastos"
Button1.Text = "Sumar"
CheckBox1.Text = ""
CheckBox2.Text = ""
CheckBox3.Text = ""
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button1.Click
Dim sum As Integer = 0
If CheckBox1.Checked = True Then
sum += luz
End If
If CheckBox2.Checked = True Then
sum += agua
End If
If CheckBox3.Checked = True Then
sum += telefono
End If
Label4.Text = sum.ToString("n")
'Label4.Text = Format(sum, "FIXED")
End Sub
End Class
Ejercicio Nº 10
Agregar un botón "Cancelar" para eliminar los checkings.
Código
Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
Label1.Text = luz
Label2.Text = agua
Label3.Text = telefono
Label4.Text = ""
Label5.Text = "Agua"
Label6.Text = "Luz"
Label7.Text = "Teléfono"
Label8.Text = "Total"
Label9.Text = "Relación de gastos"
Button1.Text = "Sumar"
Button2.Text = "Cancelar"
CheckBox1.Text = ""
CheckBox2.Text = ""
CheckBox3.Text = ""
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button1.Click
Dim sum As Integer = 0
If CheckBox1.Checked = True Then
sum += luz
End If
If CheckBox2.Checked = True Then
sum += agua
End If
If CheckBox3.Checked = True Then
sum += telefono
End If
Label4.Text = sum.ToString("n")
'Label4.Text = Format(sum, "FIXED")
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button2.Click
Label4.Text = ""
CheckBox1.Checked = False
CheckBox2.Checked = False
CheckBox3.Checked = False
End Sub
End Class
Ejercicio Nº 11
Implementar el formulario siguiente:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
Label1.Text = "Datos equipo: Vuelta al Cotopaxi"
Label2.Text = ""
Button1.Text = "Confirmar"
GroupBox1.Text = "Categoría"
GroupBox2.Text = "Color"
GroupBox3.Text = "Carpa para dormir"
RadioButton1.Text = "Novato"
RadioButton2.Text = "Élite"
RadioButton3.Text = "Master"
RadioButton4.Text = "Amarillo"
RadioButton5.Text = "Azul"
RadioButton6.Text = "Rojo"
RadioButton7.Text = "Individual"
RadioButton8.Text = "Doble"
RadioButton9.Text = "Colectiva"
End Sub
'***************************
Dim Dato_equipo As String
Dim Dato_color As String
Dim dato_carpa As String
Private Sub RadioButton1_CheckedChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles RadioButton1.CheckedChanged
Dato_equipo = "Equipo Novato"
End Sub
Private Sub RadioButton2_CheckedChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles RadioButton2.CheckedChanged
Dato_equipo = "Equipo Élite"
End Sub
Private Sub RadioButton3_CheckedChanged(ByVal sender As _
System.Object, ByVal e _
As System.EventArgs) Handles RadioButton3.CheckedChanged
Dato_equipo = "Equipo Master"
End Sub
Private Sub RadioButton4_CheckedChanged(ByVal sender As _
System.Object, ByVal e _
As System.EventArgs) Handles RadioButton4.CheckedChanged
Dato_color = "Amarillo"
End Sub
Private Sub RadioButton5_CheckedChanged(ByVal sender As _
System.Object, ByVal e _
As System.EventArgs) Handles RadioButton5.CheckedChanged
Dato_color = "Azul"
End Sub
Private Sub RadioButtom6_CheckedChanged(ByVal sender As _
System.Object, ByVal e _
As System.EventArgs) Handles RadioButton6.CheckedChanged
Dato_color = "Rojo"
End Sub
'**********************
Private Sub RadioButton7_CheckedChanged(ByVal sender As _
System.Object, ByVal e _
As System.EventArgs) Handles RadioButton7.CheckedChanged
dato_carpa = "Individual"
End Sub
Private Sub RadioButton8_CheckedChanged(ByVal sender As _
System.Object, ByVal e As _
System.EventArgs) Handles RadioButton8.CheckedChanged
dato_carpa = "Doble"
End Sub
Private Sub RadioButtom9_CheckedChanged(ByVal sender As _
System.Object, ByVal e _
As System.EventArgs) Handles RadioButton9.CheckedChanged
dato_carpa = "Colectiva"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button1.Click
If Len(Dato_equipo) > 0 And Len(Dato_color) And _
Len(dato_carpa) > 0 Then
Label2.Text = "Equipo: " & Dato_equipo + " " + "Color: " + _
Dato_color + " " + "Carpa: " + dato_carpa
Else
Label2.Text = "Datos incompletos"
End If
End Sub
End Class
Ejercicio Nº 12
Implementar el formulario siguiente:
Con las funcionalidades siguientes:
1. Cada vez que pulse "Anexar registros" se anexe una fila (HOLA, mi, amor)
2. Cada vez que pulse "Celda corriente" responda con:
Número de filas
Número de columnas
Coordenadas de la celda corriente
3. Al pulsar "Salir", salga de la ejecución
PASOS:
1. Ingresar en el formulario
8 etiquetas
3 botones
1 datagridview
2. Con "propiedades" anexar las columas (click con el botón derecho sobre el grid)
columna0
columna1
columna2
3. Ingresar el código siguiente:
Public Class Form1
Dim dato_01 As String = "HOLA"
Dim dato_02 As String = "mi"
Dim dato_03 As String = "amor"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
Label1.Text = "Total columnas"
Label2.Text = "Total filas"
Label3.Text = "Columna corriente"
Label4.Text = "Fila corriente"
Button1.Text = "Anexar registros"
Button2.Text = "Celda corriente"
Button3.Text = "Salir"
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button1.Click
' Para agregar una fila
DataGridView1.Rows.Add(New String() {Me.dato_01, Me.dato_02, Me.dato_03})
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button2.Click
' para conocer el número de filas y columnas
Label5.Text = DataGridView1.ColumnCount
Label6.Text = DataGridView1.RowCount
' para conocer las coordenadas de la celda corriente
Label7.Text = DataGridView1.CurrentCellAddress.X
Label8.Text = DataGridView1.CurrentCellAddress.Y
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button3.Click
' paara salir
End
' Application.Exit() 'cierra ventanas y todo
' Me.Close() 'cierra el formulario actual
End Sub
End Class
Ir a Parte III
Hola Juan
ResponderEliminarGracias por el comentario
Un poco de historia: En mi empresa tuve un sistema administrativo con contabilidad integrada. Comencé con DBase y terminé en VisualFoxpro, luego me pasó tanto como a tí. Conozco de la incertidumbre y angustia de migrar y es la razón de este blog. Para tomar la decisión de si migrar al ambiente de VS debes hacer un pequeño estudio de mercado en tu ámbito de trabajo. Este blog te ayuda con VisualBasic Express de la suite de VisualStudio y te lleva de la mano (comenzando por la parte 1) para el manejo de VisualBasic (componente de VS). Si te vas por VisualBasic instálalo y con los ejercicios vas bien. Gran parte aprendí con Visual 5.0. y fíjate hasta donde llegué.
Buen camino