You are on page 1of 172

Visual Basic 2012 Tutorial

Visual Basic 2012 is the latest version of Visual Basic launched by Microsoft in 2012. Visual
Basic 2012 is almost similar to Visual Basic Express 2010 and Visual Basic 2008, but it has
added many new features. The most distinct difference is that Visual Basic 2012 no more
comes as a stand alone program, it is now integrated with other Microsoft Programming
languages C# and C++ in a package called Visual Studio 2012. Start learning Visual Basic
2012 by clicking the topics listed under contents:

Visual Basic 2012 es la última versión de Visual Basic lanzado por Microsoft en 2012 Visual Basic 2012 es
casi similar a Visual Basic Express 2010 y Visual Basic 2008 , pero se ha añadido muchas características
nuevas. La diferencia más clara es que Visual Basic 2012 no más se presenta como un programa
independiente , que ahora está integrado con otros lenguajes de Microsoft de programación C # y C ++ en un
paquete llamado Visual Studio 2012 Empieza a aprender Visual Basic 2012 haciendo clic en los temas
enumerados en el contenido :

CONTENTS

Lesson 1- Introduction

Lesson 2-Working with Controls

Lesson 3-Working with Control Properties

Lesson 4 -Object Oriented Programming

Lesson 5-Writing the Code

Lesson 6- Managing Data

Lesson 7- Mathematical Operations

Lesson 8- String Manipulation


Lesson 9- Using If….Then….Else

Lesson 10- Using Select Case

Lesson 11- Looping

Lesson 12- Functions Part 1

Lesson 13- Function Part II

Lesson 14- Functions Part III- Math Functions

Lesson 15 – Functions Part IV- Formatting Functions

Lesson 16 – Functions Part V- Formatting Date and Time

Lesson 17 – Using Check Box

Lesson 18 – Using Radio Button

Lesson 19 – Creating A Simple Web Browser

Lesson 20 – Errors Handling

Lesson 21- Managing Graphics 1-Basic Concepts

Lesson 22 – Managing Graphics -Drawing Rectangle


Lesson 23 – Managing Graphics -Drawing Ellipse and Circle

Lesson 24 – Managing Graphics -Drawing Text

Lesson 25 – Managing Graphics -Drawing Polygon and Pie

Lesson 26 – Managing Graphics-Filling Shapes with Color

Lesson 27 – Using Timer

Lesson 28 – Creating Animation

Lesson 29- Working with Databases Part 1

Lesson 30- Working with Databases Part 2

Lesson 31: Working with Databases Part 3

If you wish to learn more about Visual Basic 2012, you can download our E-Book, Visual Basic 2010 Made

Easy ,written by our webmaster and tutor Dr.Liew . Although it is about Visual Basic 2010, the concepts are nearly

similar to Visual Basic 2012, only with very slight variations. With more than 200 pages of contents and many hands

on examples, you should be able to master the basics of VB2010 and VB2012 quickly. This book can also be used as a

textbook for classroom learning. Click on the book image below for more information.

Si desea obtener más información acerca de Visual Basic 2012, puede descargar nuestro E-Book, Visual Basic 2010

Made Easy, escrito por nuestro webmaster y Dr.Liew tutor. Aunque se trata de Visual Basic 2010, los conceptos son

casi similares a Visual Basic 2012, sólo con variaciones muy leves. Con más de 200 páginas de contenidos y muchas

manos en ejemplos, usted debería ser capaz de dominar los fundamentos de la VB2010 y VB2012 rápidamente. Este
libro también puede ser utilizado como libro de texto para el aprendizaje en el aula. Haga clic en la imagen del libro

a continuación para obtener más información.

ISBN-13: 978-1467975193

Preview the book


Visual Basic 2012 Lesson 1 – Introduction to Visual Basic 2012
[CONTENTS] >>[Lesson 2]

Visual Basic 2012 Lección 1 - Introducción a Visual Basic 2012

[ÍNDICE] >> [Lección 2]

Visual Basic Express 2012 is the latest version of Visual Basic launched by
Microsoft in 2012. Visual Basic Express 2012 is almost similar to Visual Basic
Express 2010 and Visual Basic 2008, but it has added many new features. The
most distinct difference is that Visual Basic Express 2012 no more comes as a
stand alone program, it is now integrated with other Microsoft Programming
languages C# and C++ in a package called Visual Studio 2012. Further, Visual
Studio Express 2012 now come in five editions, they are:

Visual Basic Express 2012 es la última versión de Visual Basic lanzado por Microsoft en 2012
de Visual Basic Express 2012 es casi similar a Visual Basic Express 2010 y Visual Basic 2008,
pero se ha añadido muchas características nuevas. La diferencia más clara es que Visual
Basic Express 2012 no más se presenta como un programa independiente, que ahora está
integrado con otros lenguajes de Microsoft de programación C # y C ++ en un paquete
denominado Además Visual Studio 2012, Visual Studio Express 2012 ahora viene en cinco
ediciones , ellos son:

 Visual Studio Express 2012 for Web


 Visual Studio Express 2012 for Windows 8
 Visual Studio Express 2012 for Windows Desktop
 Visual Studio Express 2012 for Windows Phone
 Visual Studio Team Foundation Server Express 2012

Right now we shall concentrate on learning Visual Basic 2012 Express for Windows Desktop , so you
will need to download the free software from Microsoft site below:

Ahora nos concentraremos en aprender Visual Basic 2012 Express para Windows de escritorio, por lo
que tendrá que descargar el software gratuito de Microsoft en la siguiente lista:
http://www.microsoft.com/en-us/download/details.aspx?id=34673

Like Visual Basic Express 2010 and Visual Basic Express 2008 , Visual Basic Express 2012 is
also a full fledged Object-Oriented Programming(OOP) Language, so it has caught up with
other OOP languages such as C++, Java,C# and others.

The Integrated Development Environment when you launch VB2012 Express is shown in the
diagram below.

Al igual que Visual Basic Express 2010 y Visual Basic 2008 Express, Visual Basic Express
2012 es también una programación completa orientada a objetos hecha y derecha (POO)
Idioma, por lo que ha puesto al día con otros lenguajes de POO como C ++, Java, C # y otros.
El entorno de desarrollo integrado al iniciar VB2012 Express se muestra en el siguiente
diagrama.

Figure 1.1: Visual Studio 2012 Start Page Figura 1.1: Visual Studio 2012 Página de inicio
To start a new Visual Studio Express 2012 project, simply click on New Project to launched
The Visual Studio New Project page as shown below:

Para iniciar un nuevo proyecto de Visual Studio Express 2012, simplemente haga clic en
Nuevo proyecto para lanzar la página Visual Studio Nuevo proyecto, como se muestra a
continuación:

Figure 1.2: Visual Studio 2012 Project Page Figura 1.2: Visual Studio 2012 Página del
proyecto

The New Project Page comprises three templates, Visual Basic, Visual C# and Visual C++.
Since we are going to learn Visual Basic 2012, we shall select Visual Basic. Visual Basic 2012
offers you four types of projects that you can create. As we are going to learn to create
windows Applications, we will select Windows Forms Application.

At the bottom of this dialog box, you can change the default project name
WindowsApplication1 to some other name you like, for example, MyFirstProgram. After you
have renamed the project, click OK to continue. The following IDE Windows will appear, it
is similar to Visual Basic 2010. The Toolbox is not shown until you click on the Toolbox
tab.When you click on the Toolbox tab, the common controls Toolbox will appear.

La página Nuevo proyecto comprende tres plantillas, Visual Basic, Visual C # y Visual C ++.
Ya que vamos a aprender Visual Basic 2012, vamos a seleccionar Visual Basic. Visual Basic
2012 le ofrece cuatro tipos de proyectos que se pueden crear. Como vamos a aprender a
crear aplicaciones de Windows, seleccionaremos Aplicación de Windows Forms.

En la parte inferior de este cuadro de diálogo, puede cambiar el nombre del proyecto por
defecto WindowsApplication1 a algún otro nombre que te gusta, por ejemplo, MyFirstProgram.
Después de haber cambiado el nombre del proyecto, haga clic en Aceptar para continuar.
Aparecerá la siguiente IDE de Windows, que es similar a Visual Basic 2010, no se muestra el
cuadro de herramientas hasta que haga clic en el cuadro de herramientas tab.When hace clic
en la ficha Herramientas, aparecerá el cuadro de herramientas controles comunes.

Figure 1.3:Visual Basic 2012 IDE Figura 1.3: Visual Basic 2012 IDE

Visual Basic Express 2012 IDE comprises a few windows, the Form window , the Solution
Explorer window and the Properties window . It also consists of a toolbox which contains many
useful controls that allows a programmer to develop his or her VB programs. The toolbox is
shown in Figure 1.4.

Basic Express 2012 IDE Visual comprende algunas ventanas, la ventana del formulario, la
ventana Explorador de soluciones y la ventana Propiedades. También consta de una caja de
herramientas que contiene muchos controles útil que permite a un programador para
desarrollar sus programas en VB. La caja de herramientas se muestra en la Figura 1.4.
Figure 1.4: Visual Basic 2012 Toolbox Figura 1.4: 2012 Caja de herramientas
de Visual Basic

Now, we shall proceed to show you how to create your first program. First, change the text of
the form to My First Program in the properties window, it will appear as the title of the program.
Next, insert a button and change its text to OK. The design interface is shown in Figure 1.5

Ahora, procederemos a mostrar cómo crear su primer programa. En primer lugar, cambiar el
texto de la forma a mi primer programa en la ventana de propiedades, aparecerá como el título
del programa. A continuación, inserte un botón y cambiar su texto a Aceptar. La interfaz de
diseño se muestra en la Figura 1.5

Figure 1.5: The Design Interface Figura 1.5: La interfaz de Diseño


Now click on the OK button to bring up the code window and enter the following statement
between Private Sub and End Sub procedure, as shown in Figure 1.6:

MsgBox(“My First Visual Basic 2012 Program”)

Ahora haga clic en el botón OK para que aparezca la ventana de código y escriba el siguiente
comunicado entre Private Sub y End Sub procedimiento, como se muestra en la Figura 1.6:

MsgBox ("Mi primer programa Visual Basic 2012")

Figure 1.6: The Code Window Figura 1.6: La ventana de código


Now click on the Start on the toolbar to run the program then click on the OK button, a dialog
box that displays the “My First Visual Basic 2012 Program″ message will appear,as shown in
Figure 1.7:

Ahora haga clic en el Inicio en la barra de herramientas para ejecutar el programa a


continuación, haga clic en el botón Aceptar, aparecerá un cuadro de diálogo que muestra
aparecerá el mensaje "Mi Primer programa Visual Basic 2012", como se muestra en la Figura
1.7:

Figure 1.7: The Message Box Figura 1.7: El cuadro de mensaje

The function MsgBox is a built-in function of Visual Basic 2012 and it will display the text
enclosed within the brackets.

Now you have created your first program, we shall learn more VB2012 programming
techniques in coming lessons.

El MsgBox función es una función integrada de Visual Basic 2012 y se mostrará el texto
encerrado entre corchetes.

Ahora que ha creado su primer programa, vamos a aprender más técnicas de programación
VB2012 en próximas lecciones.

[CONTENTS] >>[Lesson 2]
Visual Basic 2012 Lesson 2-Working with Controls
[Lesson 1]<< [CONTENTS] >> [Lesson 3]

Controls in Visual Basic 2012 are tools that can be placed in the form to perform various tasks.
We can use them to create all kinds of Windows applications. The diagram below shows the
toolbox that contains the controls of Visual Basic 2012. They are categorized into Common
Controls, Containers, Menus, Toolbars, Data, Components, Printings and Dialogs. At the
moment, we will focus on the common controls. Some of the most used common controls are
Button, Label, ComboBox, ListBox, PictureBox, TextBox etc.

To insert a control into your form in Visual Basic 2012 IDE, you just need to drag the control
from the toolbox and drop it into the form. You can reposition and resize it as you like. Let’s
examine a few programs that made use of Button, Label, TextBox , ListBox and PictureBox .
You don’t have to worry so much about the code yet because we will explain the program
syntax as you progress to later lessons.

Los controles en Visual Basic 2012 son herramientas que se pueden colocar en el formulario
para realizar diversas tareas. Podemos usarlas para crear todo tipo de aplicaciones de
Windows. El siguiente diagrama muestra la caja de herramientas que contiene los controles de
Visual Basic 2012 se clasifican en controles comunes, Contenedores, menús, barras de
herramientas, datos, Componentes, Impresiones y diálogos. Por el momento, nos centraremos
en los controles comunes. Algunos de los controles comunes más utilizados son Button, Label,
ComboBox, ListBox, PictureBox, TextBox etc

Para insertar un control en su forma en 2012 IDE de Visual Basic, sólo tiene que arrastrar el
control desde la caja de herramientas y soltarlo en el formulario. Puede volver a colocar y
cambiar el tamaño a su gusto. Vamos a examinar algunos programas que hacen uso de
Button, Label, TextBox, ListBox y PictureBox. Usted no tiene que preocuparse tanto por el
código todavía, porque vamos a explicar la sintaxis del programa a medida que avanza en
lecciones posteriores.
When you click on the Toolbox tab, the common controls Toolbox will appear.

Al hacer clic en la ficha Herramientas, aparecerá el cuadro de herramientas controles


comunes.

2.1 Creating your first program 2.1 Creación del primer programa
To create your first program in Visual Basic 2012, drag the button control into the form, and
change its default Text Button1 to OK in the properties window, the word OK will appear on the
button in the form, as shown below:

Para crear su primer programa en Visual Basic 2012, arrastre el botón de control en el
formulario y cambie su texto por defecto Button1 a OK en la ventana de propiedades, la
palabra Aceptar aparecerá en el botón en el formulario, como se muestra a continuación:

Now click on the OK button and the code window appears. Enter the code as follows:

Ahora haga clic en el botón OK y aparecerá la ventana de código. Introduzca el código de la


siguiente manera:
When you run the the program and click on the OK button, a dialog box will appear and
displays the “WELCOME TO VISUAL BASIC 2012″ message,as shown in the Figure below.
The argument Title: is to assign the title of the dialog box.:

Al ejecutar el programa y haga clic en el botón Aceptar, aparecerá un cuadro de diálogo


aparecerá y mostrará el "BIENVENIDOS A VISUAL BASIC 2012" mensaje, como se muestra
en la siguiente figura. El argumento Título: consiste en asignar el título del cuadro de diálogo .:

2.2 Using the Text Box 2.2 Cómo utilizar el cuadro de texto

Next I will show you how to create a simple calculator that adds two numbers using the
TextBox control. In this program, you insert two textboxes , three labels and one button. The
two textboxes are for the users to enter two numbers, one label is to display the addition
operator and the other label is to display the equal sign. The last label is to display the answer.

Siguiente te mostraré cómo crear una calculadora simple que suma dos números utilizando el
control TextBox. En este programa, inserte dos cuadros de texto, tres etiquetas y un botón.
Los dos cuadros de texto son para los usuarios introducir dos números, una etiqueta es
mostrar el operador de suma y la otra etiqueta es para mostrar el signo igual. La última
etiqueta es para ver la respuesta.
Now change the label on the button to Calculate,then click on this button and enter the
following code:

Ahora cambie la etiqueta del botón para calcular, a continuación, haga clic en este botón e
introduzca el siguiente código:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim num1, num2, product As Single

num1 = TextBox1.Text

num2 = TextBox2.Text

product = num1 + num2

Label1.Text = product

End Sub

When you run the program and enter two numbers, pressing the calculate button can let you
perform addition of the two numbers.

Cuando se ejecuta el programa y entrar en dos números, al pulsar el botón de calcular se


permitirá realizar, además de los dos números.

[Lesson 1]<< [CONTENTS] >> [Lesson 3]


Visual Basic 2012 Lesson 3-Working with Control Properties
Visual Basic 2012 Lección 3 Trabajar con propiedades de control
[Lesson 2]<< [CONTENTS] >> [Lesson 4]

3.1 The Control Properties in Visual Basic 2012

Before writing an event procedure for a control in Visual Basic 2012 to response to a user’s
input or action, you have to set certain properties for the control to determine its appearance
and how it will work with the event procedure. You can set the properties of the controls in the
properties window of Visual Basic 2012 IDE at design time or at run time. Figure 3.1 is the
typical properties window for a form. It refers particularly to interface of the first program you
have learned in the previous lesson:

3.1 El Propiedades de control en Visual Basic 2012

Antes de escribir un procedimiento de evento para un control en Visual Basic 2012 para
respuesta a la entrada o la acción de un usuario, hay que establecer ciertas propiedades del
control para determinar su aspecto y cómo se va a trabajar con el procedimiento de evento.
Puede establecer las propiedades de los controles en la ventana de propiedades de 2012 IDE
de Visual Basic en tiempo de diseño o en tiempo de ejecución. Figura 3.1 es la ventana de
propiedades típicas de un formulario. Se refiere en particular a la interfaz del primer programa
que has aprendido en la lección anterior:
Figure 3.1

Figure 3.2
The title of the form is defined by the Text property and its default name is Form 1. To change
the form’s title to any name that you like, simple click in the box on the right of the Text
property and type in the new name, in this example, the title is Addition Calculator. Notice that
this title will appear on top of the windows. In the properties window, the item appears at the
top part is the object currently selected (in Figure 3.1, the object selected is Form1). At the
bottom part, the items listed in the left column represent the names of various properties
associated with the selected object while the items listed in the right column represent the
states of the properties. Properties can be set by highlighting the items in the right column then
change them by typing or selecting the options available. You may also alter other properties of
the form such as font, location, size, foreground color, background color ,MaximizeBox,
MinimizeBox and etc. You can also change the properties of the object at runtime to give
special effects such as change of color, shape, animation effect and so on.

For example the following code will change the form color to yellow every time the form is
loaded. Visual Basic 2012 uses RGB(Red, Green, Blue) to determine the colors. The RGB
code for yellow is 255,255,0. Me in the code refer to the current form and Backcolor is the
property of the form’s background color. The formula to assign the RGB color to the form
is Color.FormArbg(RGB code). The event procedure is as follows:

El título del formulario se define mediante la propiedad Text y su nombre por defecto es la
Forma 1 Para cambiar de título del formulario a cualquier nombre que usted quiere, simple clic
en la casilla de la derecha de la propiedad Text y escriba el nuevo nombre, en este ejemplo, el
título es Calculadora de adición. Tenga en cuenta que este título aparecerá en la parte
superior de las ventanas. En la ventana de propiedades, el elemento aparece en la parte
superior es el objeto seleccionado en ese momento (en la Figura 3.1, el objeto seleccionado
es Form1). En la parte inferior, los elementos que aparecen en la columna de la izquierda
representan los nombres de varias propiedades asociadas con el objeto seleccionado,
mientras que los elementos que se enumeran en la columna de la derecha representan los
estados de las propiedades. Las propiedades pueden ser establecidas por destacar los
artículos en la columna de la derecha y luego cambiarlos escribiendo o seleccionando las
opciones disponibles. También puede alterar otras propiedades de la forma como la fuente,
ubicación, tamaño, color de primer plano, color de fondo, MaximizeBox, MinimizeBox y etc
También puede cambiar las propiedades del objeto en tiempo de ejecución para dar efectos
especiales tales como el cambio de color, forma, efecto de animación y así sucesivamente.

Por ejemplo el siguiente código cambiará el color a amarillo forma cada vez que se carga el
formulario. Visual Basic 2012 utiliza RGB (rojo, verde, azul) para determinar los colores. El
código RGB para el amarillo es 255,255,0. Yo en el código refiero a la forma actual y
Backcolor es propiedad de color de fondo del formulario. La fórmula para asignar el color RGB
a la forma es Color.FormArbg (código RGB). El procedimiento de evento es el siguiente:

Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

Me.BackColor = Color.FromArgb(255, 0, 255)

End Sub

End Class

You may also use the follow procedure to assign the color at run time.
También puede utilizar el procedimiento siguiente para asignar el color en tiempo de
ejecución.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load

Me.BackColor = Color.Magenta

End Sub

Both procedures above will load the form with a magenta background as follows:

Ambos procedimientos anteriores se cargue el formulario con un fondo magenta de la


siguiente manera:

Here are some of the common colors and the corresponding RGB codes. You can always
experiment with other combinations, but remember the maximum number for each color is 255
and the minimum number is 0.

Éstos son algunos de los colores comunes y los códigos RGB correspondientes. Siempre se
puede experimentar con otras combinaciones, pero recuerda que el número máximo para
cada color es 255 y el mínimo es 0.
The following is another program that allows the user to enter the RGB codes into three
different textboxes and when he or she clicks the display color button, the background color of
the form will change according to the RGB codes. So, this program allows users to change the
color properties of the form at run time.

El siguiente es otro programa que permite al usuario introducir los códigos RGB en tres
cuadros de texto diferentes y cuando él o ella hace clic en el botón de color de la pantalla, el
color de fondo del formulario cambiará de acuerdo con los códigos RGB. Así, este programa
permite a los usuarios cambiar las propiedades de color de la forma en tiempo de ejecución.

The code el código

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim rgb1, rgb2, rgb3 As Integer


rgb1 = TextBox1.Text
rgb2 = TextBox2.Text
rgb3 = TextBox3.Text
Me.BackColor = Color.FromArgb(rgb1, rgb2, rgb3)

End Sub

[Lesson 2]<< [CONTENTS] >> [Lesson 4]

*This article has been translated to Serbo-Croatian language by Vera Djuraskovic from Webhostinggeeks.com.

* Este artículo ha sido traducido a la lengua serbo-croata Vera Djuraskovic de Webhostinggeeks.com.


Visual Basic 2012 Lesson 4: Object Oriented Programming
Visual 2012 Lección básica 4: Programación Orientada a
Objetos
[Lesson 3] << [CONTENTS] >> [Lesson 5]

In first three lessons, you have learned how to enter the program code and run the sample
Visual Basic 2012 programs but without much understanding about the logics of Visual Basic
2012 programming. Now, let’s get down to learning a few basic rules about writing the Visual
Basic 2012 program code.

En las tres primeras lecciones, has aprendido cómo entrar en el código del programa y
ejecutar el ejemplo de programas de Visual Basic 2012, pero sin mucha comprensión sobre la
lógica de programación Visual Basic 2012. Ahora, vayamos a aprender algunas reglas básicas
sobre cómo escribir el código del programa Visual Basic 2012.

First of all, Visual Basic 2012 is very much similar to Visual Basic 2010 and Visual Basic 2008.

However, it is very different from Visual Basic 6. While they are nearly similar in terms of

Interface and program structure, their underlying concepts are quite different. The main

difference is that Visual Basic 2012 is a full fledged Object Oriented Programming Language

while Visual Basic 6 may have OOP capabilities, it is not fully object oriented. In order to

qualify as a fully object oriented programming language, it must have three core technologies

namely encapsulation, inheritance and polymorphism. These three terms are explained

below:

En primer lugar, Visual Basic 2012 es muy similar a Visual Basic 2010 y Visual Basic 2008 Sin

embargo, es muy diferente de Visual Basic 6 Si bien son casi similares en términos de interfaz

y estructura del programa, sus conceptos subyacentes son bastante diferentes . La principal

diferencia es que Visual Basic 2012 es un hecho y derecho Object Oriented Programming

Language, mientras que Visual Basic 6 puede tener capacidades de programación orientada a

objetos, no está totalmente orientado a objetos. Para calificar como un lenguaje de

programación orientado a objetos completo, debe tener tres tecnologías básicas a saber

encapsulación, herencia y polimorfismo. Estos tres términos se explican a continuación:


Encapsulation La encapsulación

Encapsulation refers to the creation of self-contained modules that bind processing functions to
the data. These user-defined data types are called classes. Each class contains data as well
as a set of methods which manipulate the data. The data components of a class are called
instance variables and one instance of a class is an object. For example, in a library system, a
class could be member, and John and Sharon could be two instances (two objects) of the
library class.

La encapsulación se refiere a la creación de módulos independientes que se unen las


funciones de procesamiento de los datos. Estos tipos de datos definidos por el usuario se
denominan clases. Cada clase contiene datos, así como un conjunto de métodos que
manipulan los datos. Los componentes de datos de una clase se llaman variables de instancia
y una instancia de una clase es un objeto. Por ejemplo, en un sistema de biblioteca, una clase
puede ser miembro, y John y Sharon podría haber dos instancias (dos objetos) de la biblioteca
de clases.

Inheritance Herencia
Classes are created according to hierarchies, and inheritance allows the structure and
methods in one class to be passed down the hierarchy. That means less programming is
required when adding functions to complex systems. If a step is added at the bottom of a
hierarchy, then only the processing and data associated with that unique step needs to be
added. Everything else about that step is inherited. The ability to reuse existing objects is
considered a major advantage of object technology.

Las clases se crean de acuerdo con las jerarquías, y la herencia permite a la estructura y los
métodos de una clase que se deben pasar por la jerarquía. Esto significa que se requiere
menos programación y al añadir funciones a los sistemas complejos. Si se añade un paso en
la parte inferior de una jerarquía entonces sólo necesita, el procesamiento y los datos
asociados con ese paso único que se añade. Todo lo demás en ese paso se hereda. La
capacidad de reutilizar los objetos existentes se considera una de las principales ventajas de
la tecnología de objetos.

Polymorphism El polimorfismo
Object-oriented programming allows procedures about objects to be created whose exact type
is not known until runtime. For example, a screen cursor may change its shape from an arrow
to a line depending on the program mode. The routine to move the cursor on screen in
response to mouse movement would be written for “cursor,” and polymorphism allows that
cursor to take on whatever shape is required at runtime. It also allows new shapes to be easily
integrated.

VB6 is not a full OOP in the sense that it does not have inheritance capabilities although it can
make use of some benefits of inheritance. However, VB2012 is a fully functional Object
Oriented Programming Language, just like other OOP such as C++ and Java. It is focuses
more on the data itself while VB6 and earlier versions focus more on the actions. VB6 and its
predecessors are known as procedural or functional programming language. Some other
procedural programming languages are C, Pascal and Fortran.

Visual Basic 2012 allows users to write programs that break down into modules. These
modules will represent the real-world objects and are knows as classes or types. An object can
be created out of a class and it is known as an instance of the class. A class can also comprise
subclass. For example, apple tree is a subclass of the plant class and the apple in your
backyard is an instance of the apple tree class. Another example is student class is a subclass
of the human class while your son John is an instance of the student class.

A class consists of data members as well as methods. In Visual Basic 2012, the program
structure to define a Human class can be written as follows:

Programación orientada a objetos permite que los procedimientos acerca de los objetos que
se creen cuyo tipo exacto no se conoce hasta el tiempo de ejecución. Por ejemplo, un cursor
de la pantalla puede cambiar su forma de una flecha a una línea según el modo de programa.
La rutina para mover el cursor en la pantalla en respuesta al movimiento del ratón se escribiría
para "cursor", y el polimorfismo permite que el cursor para asumir cualquier forma que se
requiere en tiempo de ejecución. También permite nuevas formas para integrar fácilmente.

VB6 no es un OOP completo en el sentido de que no tiene capacidades de herencia aunque


puede hacer uso de algunos de los beneficios de la herencia. Sin embargo, VB2012 es una
orientada a objetos totalmente funcional lenguaje de programación, al igual que otra
programación orientada a objetos, como C ++ y Java. Se centra más en los datos en sí,
mientras que las versiones anteriores de Visual Basic 6 y se centran más en las acciones. VB6
y sus predecesores se les conoce como lenguaje de programación procedimental o funcional.
Algunos otros lenguajes de programación procedimentales son C, Pascal y Fortran.

Visual Basic 2012 permite a los usuarios escribir programas que se descomponen en
módulos. Estos módulos se representan los objetos del mundo real y son conoce como clases
o tipos. Un objeto puede ser creado a partir de una clase y se le conoce como una instancia
de la clase. Una clase también puede comprender subclase. Por ejemplo, el manzano es una
subclase de la clase de plantas y la manzana en su patio trasero es una instancia de la clase
manzano. Otro ejemplo es la clase del estudiante es una subclase de la clase humana,
mientras que su hijo Juan es una instancia de la clase de los estudiantes.

Una clase se compone de miembros de datos, así como métodos. En Visual Basic 2012, la
estructura del programa para definir una clase de humano se puede escribir de la siguiente
manera:

Public Class Human

‘Data Members

Private Name As String

Private Birthdate As String

Private Gender As String

Private Age As Integer

‘Methods

Overridable Sub ShowInfo( )

MessageBox.Show(Name)
MessageBox.Show(Birthdate)
MessageBox.Show(Gender)
MessageBox.Show(Age)

End Sub
End Class

Another Example:

Public Class Car


‘Data Members
Private Brand As String
Private Model As String
Private Year Made As String
Private Capacity As Integer

‘Methods

Overridable Sub ShowInfo( )

MessageBox.Show(Brand)
MessageBox.Show(Model)
MessageBox.Show(Year Made)
MessageBox.Show(Capacity)

End Sub
End Class

Let’s look at one example on how to create a class. The following example shows you how to
create a class that can calculate your BMI (Body Mass Index).

To create class, start Visual Basic 2012 as usual and choose Windows Applications. In the
Visual Basic 2012 IDE, click on Project on the menu bar and select Add Class, the Add New
Item dialog appears, as shown in the Figure below:

Veamos un ejemplo de cómo crear una clase. El siguiente ejemplo muestra cómo crear una
clase que puede calcular su IMC (Índice de Masa Corporal).

Para crear la clase, iniciar Visual Basic 2012 como de costumbre y elegir aplicaciones de
Windows. En el IDE de Visual Basic 2012, haga clic en Proyecto en la barra de menú y
seleccione Agregar clase, el complemento aparece diálogo Nuevo elemento, como se muestra
en la siguiente figura:
The default class Class1.vb will appear as a new tab with a code window. Rename the class as
MyClass.vb. Rename the form as MyFirstClass.vb.

Now, in the MyClass.vb window, enter the following code

Public Function BMI(ByVal height As Single, ByVal weight As Single)

BMI = Format((weight) / (height ^ 2), “0.00”)

End Function

Now you have created a class (an object) called MyClass with a method known as BMI.

In order to use the BMI class, insert a button into the form and click on the button to enter the
following code:

Private Sub BtnCalBmi_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles BtnCalBmi.Click

Dim MyObject As Object


Dim h, w As Single

MyObject = New MyClass1()

h = InputBox(“What is your height in meter”)

w = InputBox(“What is your weight in kg”)

MessageBox.Show(MyObject.BMI(h, w))

End Sub

When you run this program and click the button, the user will be presented with two input
boxes to enter his or her height and weight subsequently and the value of BMI will be shown in
a pop-up message box.

Al ejecutar este programa y haga clic en el botón, el usuario se le presentará con dos cajas de
entrada para entrar en su altura y peso, posteriormente, y el valor del índice de masa corporal
se mostrará en un cuadro de mensaje emergente.

[Lesson 3] << [CONTENTS] >> [Lesson 5]


Visual Basic 2012 Lesson 5-Writing the Code
2012 Lección Visual Basic 5-Escribir el Código
[Lesson 4]<< [CONTENTS] >> [Lesson 6]

In the previous lesson, you have learned that Visual Basic 2012 is an object oriented
programming language. You have also understood the meanings of class, object,
encapsulation inheritance as well as polymorphism. You have also learned to write some
simple programs without much understanding some underlying foundations and theories. In
this lesson, you will learn some basic theories about Visual Basic 2012 programming but we
will focus more on learning by doing, i.e. learning by writing programs .I will keep the theories
short so that it would not be too difficult for beginners.

En la lección anterior, que ha aprendido que Visual Basic 2012 es un lenguaje de


programación orientado a objetos. También ha entendido el significado de clase, objeto,
herencia encapsulación y polimorfismo. También ha aprendido a escribir algunos programas
simples sin mucho entender algunos fundamentos y teorías subyacentes. En esta lección,
usted aprenderá algunas teorías básicas acerca de programación Visual Basic 2012, pero nos
centraremos más en aprender haciendo, es decir, aprender a escribir programas .I
mantendremos las teorías corto, así que no sería demasiado difícil para los principiantes.

5.1 The event Procedure

Visual Basic 2012 is an object oriented and event driven programming language. In fact, all
windows applications are event driven. Event driven means the user will decide what to do with
the program, whether he or she wants to click the command button,enter text in a text box, or
close the application and etc. An event is related to an object, it is an incident that happens to
the object due to the action of the user , such as a click or pressing a key on the keyboard. A
class has events as it creates an instant of a class or an object. When we start a windows
application in Visual Basic 2012 in previous chapters, we will see a default form with the name
Form1 appears in the IDE, it is actually the Form1 Class that inherits from the Form
class System.Windows.Forms.Form, as shown in the Form1 properties windows in Figure
5.1.

Visual Basic 2012 es un lenguaje de programación orientado a objetos y orientada a eventos.


De hecho, todas las aplicaciones de Windows están evento impulsado. Evento impulsado
significa que el usuario decidirá qué hacer con el programa, si él o ella quiere hacer clic en el
botón de comando, escriba el texto en un cuadro de texto, o cerrar la aplicación, etc Un evento
se relaciona con un objeto, es un incidente que ocurre en el objeto debido a la acción del
usuario, como un clic o pulsar una tecla en el teclado. Una clase tiene eventos ya que crea un
instante de una clase o un objeto. Cuando comenzamos una aplicación de Windows en Visual
Basic 2012 en los capítulos anteriores, vamos a ver una forma predeterminada con el nombre
Form1 aparece en el IDE, en realidad es la clase Form1 que hereda de la clase Form
System.Windows.Forms.Form, como se muestra en los Form1 ventanas de propiedades en la
Figura 5.1.
System.Windows.Forms.Form, como se muestra en los Form1 ventanas de propiedades en la
Figura 5.1.

Figure 5.1

To start writing code in Visual Basic 2012, click on any part of the form to go into the code
window as shown in Figure 5.2. This is the structure of an event procedure. In this case, the

event procedure is to load Form1 and it starts with Private Sub and end with End Sub. This
procedure includes the Form1 class and the event Load, and they are bind together with an

underscore, i.e. Form_Load. It does nothing other than loading an empty form. You don’t have

to worry the rest of the stuff at the moment, they will be explained in later lessons.

Para comenzar a escribir código en Visual Basic 2012, haga clic en cualquier parte de la forma
de entrar en la ventana de código, como se muestra en la Figura 5.2. Esta es la estructura de
un procedimiento de evento. En este caso, el procedimiento de evento es cargar Form1 y
comienza con Private Sub y End With End Sub. Este procedimiento incluye la clase Form1 y la
carga de eventos, y se unen junto con un subrayado, es decir Form_Load. No hace nada que
no sea la carga de una forma vacía. Usted no tiene que preocuparse del resto de las cosas en
este momento, que se explicarán en lecciones posteriores.
Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load

End Sub

End Class

There are other events associated with the Form1 class, such as click, cursorChanged,
DoubleClick, DragDrop, Enter and more, as shown in the diagram Figure 5.2 (It appears when
you click on the upper right pane of the code window)

Hay otros eventos asociados a la clase Form1, como clic, CursorChanged, DoubleClick,
DragDrop, Enter y más, como se muestra en el diagrama de la Figura 5.2 (aparece al hacer
clic en el panel superior derecho de la ventana de código)

Figure 5.2
5.2 Writing the code 5.2 Escritura del código

Now you are ready to write the code for the event procedure so that it will do something more
than loading a blank form. The code must be entered between Private Sub…….End Sub. Let’s
enter the following code :

Ahora ya está listo para escribir el código para el procedimiento de evento para que se va a
hacer algo más que cargar un formulario en blanco. El código debe ser introducido entre
Private Sub ...... .End Sub. Nos adentraremos en el siguiente código:

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load

Me.Text = “My First VB2012 Program”

Me.ForeColor = Color.LightGoldenrodYellow

Me.BackColor = Color.RoyalBlue

End Sub

End Classs

The first line of the code will change the title of the form to My First Visual Basic 2012 Program,
the second line will change the foreground object to LightGoldenrodYellow( in this case, it is a
label that you insert into the form and change its text to Foreground) and the last line changes
the background to RoyalBlue color. The equal operator = in the code is used to assign
something to the object, like assigning yellow color to the foreground of the Form1 object (or an
instance of Form1). Me is the name given to the Form1 class. We can also call those lines as
Statements. So, the actions of the program will depend on the statements entered by
the programmer.

The output is shown Figure 5.3 below:

La primera línea del código va a cambiar el título del formulario a Mi Primer programa Visual
Basic 2012, la segunda línea va a cambiar el objeto en primer plano a LightGoldenrodYellow
(en este caso, es una etiqueta que se inserta en el formulario y cambiar su texto a primer
plano) y la última línea cambia el fondo al color AzulReal. El operador de igualdad = en el
código se utiliza para asignar algo al objeto, al igual que la asignación de color amarillo en el
primer plano del objeto Form1 (o una instancia de Form1). Me es el nombre dado a la clase
Form1. También podemos llamar a estas líneas como declaraciones. Así, las acciones del
programa dependerán de las declaraciones formuladas por el programador.

La salida se muestra la Figura 5.3 a continuación:


Figure 5.3

Here is another example. In this project, you insert one button into the form and change its
label text to “Display Hidden Names”. Click on this button to enter the code window and key-in
the following code:

He aquí otro ejemplo. En este proyecto, se inserta un botón en el formulario y cambie su texto
de la etiqueta de "pantalla oculta de nombres". Haga clic en este botón para entrar en la
ventana de código y clave-en el siguiente código:

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim name1, name2, name3, names As String


name1 = “George”
name2 = “Michael Chan”
name3 = “Norman”
names=name1 & “,”& name2 & “and “& name3
MsgBox(” The hidden names are ” & names,,”Hidden Names”)

End Sub

The keyword Dim is to declare variables name1, name2 and name3 , names as string, which
means they can only handle text. The variable names is to accept the names that are joined
together by the “&” signs as a single string. The function MsgBox is to display the string in a
message box, and the last argument “Hidden Names” is the title of the MsgBox function.
The output is shown in Figure 5.4 below:

La palabra clave es Dim para declarar variables nombre1, nombre2 y name3, nombres como
cadena, lo que significa que sólo pueden manejar texto. Los nombres de las variables es
aceptar los nombres que se unen entre sí por los "y" señales como una única cadena. El
MsgBox función es la de mostrar la cadena en un cuadro de mensaje, y el último argumento
"ocultos nombres" es el título de la función MsgBox. La salida se muestra en la Figura 5.4 a
continuación:

Figure 5.4

[Lesson 4]<< [CONTENTS] >> [Lesson 6]


Visual Basic 2012 Lesson 6- Managing Data
Visual Basic 2012 Lección 6 Administración de los
datos
[Lesson 5] << [CONTENTS] >> [Lesson 7]

We encounter many types of data in our daily life. For example, we need to handle data such
as names, addresses, money, date, stock quotes, statistics and etc everyday. Similarly in
Visual Basic 2012, we have to deal with all sorts of of data, some can be mathematically
calculated while some are in the form of text or other forms. Visual Basic 2012 divides data into
different types so that it is easier to manage when we need to write the code involving those
data.

Nos encontramos con muchos tipos de datos en nuestra vida diaria. Por ejemplo, tenemos que
manejar datos tales como nombres, direcciones, el dinero, la fecha, cotizaciones de bolsa,
estadísticas y etc cotidiana. Del mismo modo, en Visual Basic 2012, tenemos que lidiar con
todo tipo de datos, algunos pueden ser calculados matemáticamente mientras que algunos
son en forma de texto o de otras formas. 2012 divide los datos básicos visuales en diferentes
tipos de modo que sea más fácil de manejar cuando tenemos que escribir el código que
participarán los datos.

6.1 Visual Basic 2012 Data Types

Visual Basic 2012 classifies the aforementioned information into two major data types, they are
the numeric data types and the non-numeric data types.

6.1 Basic 2012 Tipos de datos visuales

Visual Basic 2012 clasifica la información mencionada en dos tipos de datos principales, que
son los tipos de datos numéricos y los tipos de datos no numéricos.

6.1.1 Numeric Data Types

Numeric data types are types of data that consist of numbers, which can be computed
mathematically with various standard operators such as add, minus, multiply, divide and so on.
Examples of numeric data types are your examination marks, your height, your weight, the
number of students in a class, share values, price of goods, monthly bills, fees and etc. In
Visual Basic 2012, numeric data are divided into seven types, depending on the range of
values they can store. Calculations that only involve round figures or data that do not need
precision can use Integer or Long integer in the computation. Programs that require high
precision calculation need to use Single and Double precision data types, they are also called
floating point numbers. For currency calculation , you can use the currency data types. Lastly,
if even more precision is required to perform calculations that involve many decimal points, we
can use the decimal data types. These data types are summarized in Table 6.1

6.1.1 Tipos de datos numéricos

Tipos de datos numéricos son los tipos de datos que consisten en números, que pueden
calcularse matemáticamente con varios operadores de la norma, tales como agregar, menos,
multiplicar, dividir y así sucesivamente. Ejemplos de tipos de datos numéricos son sus
calificaciones de los exámenes, su altura, su peso, el número de alumnos en una clase,
valores de acciones, precio de las mercancías, facturas mensuales, cuotas y etc En Visual
Basic 2012, los datos numéricos se dividen en siete tipos , dependiendo de la gama de valores
que pueden almacenar. Los cálculos que sólo involucran cifras redondas o datos que no
necesitan de precisión puede utilizar entero o entero largo en el cálculo. Los programas que
requieren alta necesidad de cálculo de precisión para utilizar los tipos de datos de precisión
simple y doble, que también se llaman números de punto flotante. Para el cálculo de la
moneda, puede utilizar los tipos de datos de moneda. Por último, si se requiere más precisión
para realizar cálculos que involucran muchos puntos decimales, podemos utilizar los tipos de
datos decimales. Estos tipos de datos se resumen en la Tabla 6.1

6.1.2 Non-numeric Data Types

Nonnumeric data types are data that cannot be manipulated mathematically using standard
arithmetic operators. The non-numeric data comprises text or string data types, the Date data
types, the Boolean data types that store only two values (true or false), Object data type and
Variant data type .They are summarized in Table 6.2

6.1.2 Tipos de datos no numéricos

Tipos de datos no numéricos son datos que no pueden ser manipulados matemáticamente
utilizando operadores aritméticos estándar. Los datos no numérico consta de texto o datos de
cadena tipos, los tipos de datos de fecha, los tipos de datos booleanos que almacenan sólo
dos valores (verdadero o falso), el tipo de datos Object y Variant tipo de datos .They se
resumen en la Tabla 6.2
6.1.3 Suffixes for Literals

Literals are values that you assign to a data. In some cases, we need to add a suffix behind a
literal so that Visual Basic 2012 can handle the calculation more accurately. For example, we
can use num=1.3089# for a Double type data. Some of the suffixes are displayed in Table 6.3.

6.1.3 Los sufijos para literales

Los literales son valores que se asignan a una de datos. En algunos casos, tenemos que
añadir un sufijo detrás de un literal para que Visual Basic 2012 puede manejar el cálculo con
mayor precisión. Por ejemplo, podemos utilizar num = 1.3089 # para un tipo de datos doble.
Algunos de los sufijos se muestran en la Tabla 6.3.

In addition, we need to enclose string literals within two quotations and we enclose date and
time literals within two # sign. Strings can contain any characters, including numbers. The
following are few examples:

Además, tenemos que incluir literales de cadena dentro de dos citas y adjuntamos fecha y
hora literales dentro de dos signo #. Las cadenas pueden contener cualquier carácter,
incluyendo los números. Los siguientes son algunos ejemplos:

memberName=”Turban, John.”
TelNumber=”1800-900-888-777″
LastDay=#31-Dec-00#
ExpTime=#12:00 am#

6.2 Managing Variables

Variables are like mail boxes in the post office. The contents of the variables changes every
now and then, just like the mail boxes. In term of Visual Basic 2012, variables are areas
allocated by the computer memory to hold data. Like the mail boxes, each variable must be
given a name. To name a variable in Visual Basic 2012, you have to follow a set of rules.

6.2 Gestión de variables

Las variables son como cajas de correo en la oficina de correos. El contenido de las variables
cambian de vez en cuando, al igual que los buzones de correo. En término de Visual Basic
2012, las variables son zonas asignadas por la memoria de la computadora para guardar
datos. Al igual que los buzones de correo, cada variable debe tener un nombre. Para nombrar
una variable en Visual Basic 2012, hay que seguir una serie de reglas.

6.2.1 Variable Names

The following are the rules when naming the variables in Visual Basic 2010

6.2.1 Nombres de variables

Las siguientes son las reglas al asignar nombres a las variables en Visual Basic 2010

It must be less than 255 characters

No spacing is allowed

It must not begin with a number

Period is not permitted

Examples of valid and invalid variable names are displayed in Table 6.4

Debe tener menos de 255 caracteres

No se permite el espaciamiento

No debe comenzar con un número

No se permite el Período

Ejemplos de nombres de variables válidos y no válidos se muestran en la Tabla 6.4


6.2.2 Declaring Variables

In Visual Basic 2012, one needs to declare the variables before using them by assigning
names and data types. If you fail to do so, the program will show an error. They are normally
declared in the general section of the codes’ windows using the Dim statement.
The syntax is as follows:

Dim Variable Name As Data Type

Example 6.1

6.2.2 Declaración de variables

En Visual Basic 2012, hay que declarar las variables antes de utilizarlas mediante la
asignación de nombres y tipos de datos. Si no lo hace, el programa mostrará un error. Ellos
normalmente se declaran en la sección general de las ventanas los códigos 'utilizando la
instrucción Dim.

La sintaxis es la siguiente:

Dim Nombre de variable como tipo de datos

ejemplo 6.1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load

Dim password As String


Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date

End Sub

You may also combine them in one line , separating each variable with a comma, as follows:

También puede combinarlos en una sola línea, separando cada variable con una coma, de la
siguiente manera:
Dim password As String, yourName As String, firstnum As Integer,………….

For string declaration, there are two possible forms, one for the variable-length string and
another for the fixed-length string. For the variable-length string, just use the same syntax as
example 6.1 above. However, for the fixed-length string, you have to use the syntax as shown
below:

Por declaración de cuerdas, hay dos formas posibles, uno para la cadena de longitud variable
y otro para la cadena de longitud fija. Para la cadena de longitud variable, sólo tiene que
utilizar la misma sintaxis que en el ejemplo 6.1 anterior. Sin embargo, para la cadena de
longitud fija, usted tiene que utilizar la sintaxis que se muestra a continuación:

Dim VariableName as String * n, where n defines the number of characters the string can hold.

Example 6.2:

Ejemplo 6.2:

Dim yourName as String * 10

yourName can holds no more than 10 Characters.

su nombre puede no tiene más de 10 caracteres.

6.2.3 Assigning Values to Variables

After declaring various variables using the Dim statements, we can assign values to those
variables. The syntx of an assignment is

Variable=Expression

The variable can be a declared variable or a control property value. The expression could be a
mathematical expression, a number, a string, a Boolean value (true or false) and etc. The
following are some examples:

6.2.3 Asignación de valores a las variables

Después de declarar varias variables utilizando las instrucciones Dim, podemos asignar
valores a las variables. El syntx de una asignación es

Variable = Expresión

La variable puede ser una variable declarada o un valor de propiedad de control. La expresión
puede ser una expresión matemática, un número, una cadena, un valor booleano (verdadero o
falso), etc Los siguientes son algunos ejemplos:

firstNumber=100

secondNumber=firstNumber-99
userName=”John Lyan”

userpass.Text = password

Label1.Visible = True

Command1.Visible = false

Label4.Caption = textbox1.Text

ThirdNumber = Val(usernum1.Text)

total = firstNumber + secondNumber+ThirdNumber

6.3 Constants

Constants are different from variables in the sense that their values do not change during the
running of the program.

6.3 Constantes

Las constantes son diferentes de variables en el sentido de que sus valores no cambian
durante la ejecución del programa.

6.3.1 Declaring a Constant

The syntax to declare a constant is

6.3.1 La declaración de una constante

La sintaxis para declarar una constante es

Const Constant Name As Data Type = Value

Example 6.3

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load

Const Pi As Single=3.142

Const Temp As Single=37

Const Score As Single=100

End Sub

[Lesson 5] << [CONTENTS] >> [Lesson 7]


Visual Basic 2012 Lesson 7- Mathematical Operations
Básicos 2012 Lección 7- operaciones matemáticas Visuales
[Lesson 6] >> [CONTENTS] >> [Lesson 8]

Computer can perform mathematical calculations much faster than human beings. However,
computer itself will not be able to perform any mathematical calculations without receiving
instructions from the user. In Visual Basic 2012, we can write code to instruct the computer to
perform mathematical calculations such as addition, subtraction, multiplication, division and
other kinds of arithmetic operations. In order for Visual Basic 2012 to carry out arithmetic
calculations, we need to write code that involve the use of various arithmetic operators. The
Visual Basic 2012 arithmetic operators are very similar to the normal arithmetic operators, only
with slight variations. The plus and minus operators are the same while the multiplication
operator use the * symbol and the division operator use the / symbol. The list of Visual Basic
2012 arithmetic operators are shown in table 7.1 below:

Ordenador puede realizar cálculos matemáticos mucho más rápido que los seres humanos.
Sin embargo, el propio equipo no será capaz de realizar cualquier cálculo matemático, sin
recibir instrucciones por parte del usuario. En Visual Basic 2012, se puede escribir código para
indicar al ordenador para realizar cálculos matemáticos, tales como suma, resta,
multiplicación, división y otros tipos de operaciones aritméticas. Para que Visual Basic 2012
para realizar cálculos aritméticos, tenemos que escribir código que implica el uso de varios
operadores aritméticos. Los Básica 2.012 operadores aritméticos visuales son muy similares a
los operadores aritméticos normales, sólo con ligeras variaciones. El más y el menos
operadores son los mismos, mientras que el operador de multiplicación utilizar el símbolo * y el
operador de división usar el símbolo /. La lista de 2012 los operadores aritméticos de Visual
Basic se muestran en la tabla 7.1 a continuación:
Example 7.1 ejemplo 7.1

In this program, you need to insert two Textboxes, four labels and one button. Click the button and enter the code as

shown below. When you run the program, it will perform the four basic arithmetic operations and displays the results on

the four labels.

En este programa, es necesario insertar dos cuadros de texto, cuatro etiquetas y un botón. Haga clic en el botón e

introduzca el código como se muestra a continuación. Al ejecutar el programa, se llevará a cabo las cuatro operaciones

aritméticas básicas y muestra los resultados en los cuatro etiquetas.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click

Dim num1, num2, difference, product, quotient As Single


num1 = TextBox1.Text
num2 = TextBox2.Text

sum=num1+num2
difference=num1-num2
product = num1 * num2
quotient=num1/num2
Label1.Text=sum
Label2.Text=difference
Label3.Text = product
Label4.Text = quotient

End Sub

Example 7.2 ejemplo 7.2

The program can use Pythagoras Theorem to calculate the length of hypotenuse c given the
length of the adjacent side a and the opposite side b. In case you have forgotten the formula
for the Pythagoras Theorem, it is written as

El programa puede utilizar el teorema de Pitágoras para calcular la longitud de la hipotenusa c


dada la longitud del lado adyacente y un lado opuesto b. En caso de haber olvidado la fórmula
para el Teorema de Pitágoras, que se escribe como
c^2=a^2+b^2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click

Dim a, b, c As Single
a = TextBox1.Text
b = TextBox2.Text
c=(a^2+b^2)^(1/2)
Label3.Text=c

End Sub
Example 7.3: BMI Calculator Ejemplo 7.3: BMI Calculator

A lot of people are obese now and it could affect their health seriously . Obesity has proven by
the medical experts to be a one of the main factors that brings many adverse medical
problems, including the the cardiovascular disease. If your BMI is more than 30, you are
considered obese. You can refer to the following range of BMI values for your weight status.

Una gran cantidad de personas son obesas ahora y que podría afectar seriamente su salud.
La obesidad se ha demostrado por los expertos médicos para ser un uno de los principales
factores que trae muchos problemas médicos adversos, incluyendo la de la enfermedad
cardiovascular. Si su IMC es superior a 30, usted es considerado obeso. Puede hacer
referencia a la siguiente gama de valores del IMC para su estado de peso.

Underweight = <18.5
Normal weight = 18.5-24.9
Overweight = 25-29.9
Obesity = BMI of 30 or greater

In order to calculate your BMI, you do not have to consult your doctor, you can just
use a calculator or a home made computer program, this is exactly what I am
showing you here. The BMI calculator is a Visual Basic program that can calculate
the body mass index, or BMI of a person based on the body weight in kilogram and
the body height in meter. BMI can be calculated using the formula weight/( height
)^2, where weight is measured in kg and height in meter. If you only know your
weight and height in lb and feet, then you need to convert them to the metric
system (you could indeed write a VB program for the conversion).

Para calcular su IMC, usted no tiene que consultar a su médico, que sólo puede usar una
calculadora o un programa de ordenador casero, esto es exactamente lo que te estoy
mostrando aquí. El índice de cálculo es un programa de Visual Basic que puede calcular el
índice de masa corporal, o IMC de una persona basado en el peso corporal en kilogramos y la
altura del cuerpo en metros. BMI se puede calcular mediante la fórmula peso / (estatura) ^ 2,
donde se mide el peso en kilogramos y la altura en metros. Si sólo conoce su peso y altura en
libras y pies, entonces usted necesita para convertir al sistema métrico (que podría de hecho
escribir un programa de VB para la conversión).

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArsgs)


Handles Button1.Click

Dim height, weight, bmi As Single


height = TextBox1.Text
weight = TextBox2.Text
bmi = (weight) / (height ^ 2)
Label4.Text = bmi

End Sub
The output is shown in the figure below. In this example, your height is 1.80m( about 5 foot
11),your weight is 75 kg( about 168Ib), and your BMI is about 23.14815. The reading suggests
that you are healthy. (Note; 1 foot=0.3048, 1 lb=.45359237 kilogram)

La salida se muestra en la siguiente figura. En este ejemplo, su altura es de 1,80 m


(aproximadamente 5 pies 11), su peso es de 75 kg (alrededor de 168Ib), y su IMC es de
23.14815. La lectura sugiere que usted está sano. (Nota; 1 pie = 0,3048, 1 libra = 0,45359237
kilogramos)

From the above examples, you can see that writing code that involve arithmetic operations is
relatively easy. Here are more arithmetic projects you can try to program:

De los ejemplos anteriores, se puede ver que la escritura de código que implican operaciones
aritméticas es relativamente fácil. Éstos son los proyectos más aritméticas usted puede tratar
de programa:

Area of a triangle
Area of a rectangle
Area of a circle
Volume of a cylinder
Volume of a cone
Volume of a sphere
Compound interest
Future value
Mean
Variance
Sum of angles in polygons
Conversion of lb to kg
Conversion of Fahrenheit to Celsius

[Lesson 6] >> [CONTENTS] >> [Lesson 8]


Visual Basic 2012 Lesson 8- String Manipulation
Visual Basic 2012 Lección 8 - Manipulación de
cadenas
[Lesson 7] << [CONTENTS] >> [Lesson 9]

In Visual Basic 2012 , string manipulation is important because it helps to process data that
come in the form of non-numeric types such as names, addresses, gender, cities, book titles
and more.

En Visual Basic 2012, la manipulación de cadenas es importante porque ayuda a procesar los
datos que se presentan en forma de tipos no numéricos tales como nombres, direcciones, el
género, las ciudades, los títulos de libros y más.

8.1 String Manipulation Using + and & signs.

In Visual Basic 2012, strings can be manipulated using the & sign and the + sign, both perform
the string concatenation which means combining two or more smaller strings into larger strings.
For example, we can join “Visual” ,”Basic” and “2012” into “Visual Basic 2012″ using
“Visual”&”Basic” or “Visual “+”Basic”, as shown in the Examples below

8.1 Manipulación de cadena usando + y y signos.

En Visual Basic 2012, las cadenas pueden ser manipulados usando el signo & y el signo +,
ambos realizan la concatenación de cadenas que implica la combinación de dos o más
cadenas más pequeñas en cadenas más grandes. Por ejemplo, podemos unirnos "Visual",
"Basic" y "2012" en "Visual Basic 2012" por medio de "Visual" y "Basic" o "Visual" + "básico",
como se muestra en los siguientes ejemplos

Example 8.1(a)

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim text1, text2, text3, text4 As String
text1 = “Visual”
text2 = “Basic”
text3=”2012″
text4 = text1 + text2+text3
MsgBox(text4)

End Sub
End Class

The line text4=text1+ text2 + text3 can be replaced by text4=text1 & text2 &text3 and produces
the same output. However, if one of the variables is declared as numeric data type, you cannot
use the + sign, you can only use the & sign.
El texto4 línea = texto1 texto2 + + text3 puede ser sustituida por texto4 = texto1 y texto2 y
text3 y produce la misma salida. Sin embargo, si una de las variables se declara como tipo de
datos numéricos, no se puede utilizar el signo +, sólo se puede utilizar el y firmar.

Example 8.1(b)

Dim text1, text3 as string

Dim Text2 As Integer

text1 = “Visual”

text2=22

text3=text1+text2

Label1.Text = text3

This code will produce an error because of data mismatch.However, using & instead of + will
be all right.

Este código producirá un error debido a mismatch.However datos, utilizando y en lugar de +


va a estar bien.

Dim text1, text3 as string

Dim Text2 As Integer

text1 = “Visual”

text2=22

text3=text1 & text2

Label1.Text = text3

You can combine more than two strings to form a larger string, like the following example:

Puede combinar más de dos cadenas para formar una cadena más grande, como el siguiente
ejemplo:

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim text1, text2, text3, text4, text5, text6 As String

text1 = “Welcome”
text2 = ” to”
text3 = ” Visual”
text4 = ” Basic”
text5 = ” 2012″
text6 = text1 + text2 + text3+text4+text5
Label1.Text = text6

End Sub
End Class

Running the above program will produce the following screen shot.

Al ejecutar el programa anterior producirá la siguiente captura de pantalla.

8.2 String Manipulation Using VB2012 Built-in Functions

A function is similar to a normal procedure but the main purpose of the function is to accept a
certain input and return a value which is passed on to the main program to finish the
execution.There are numerous string manipulation functions built into Visual Basic 2012 but I
will only discuss a few here and will explain the rest of them in later lessons.

8.2 Manipulación de cadena utilizando VB2012 Funciones Integradas

Una función es similar a un procedimiento normal pero el propósito principal de la función es la


de aceptar una cierta entrada y devolver un valor que se transmite al programa principal para
terminar la execution.There son numerosas funciones de manipulación de cadenas
incorporadas en Visual Basic 2012 pero sólo voy a hablar de unos pocos aquí y voy a explicar
el resto de ellas en lecciones posteriores.

8.2 (a) The Len Function


The Len function returns an integer value which is the length of a phrase or a sentence,
including the empty spaces. The syntax is

8.2 (a) La función Len

La función Len devuelve un valor entero que es la longitud de una frase o una frase,
incluyendo los espacios vacíos. La sintaxis es
Len (“Phrase”)

For example,
Len (Visual Basic) = 12 and Len (“welcome to VB tutorial”) = 22

Example 8.3

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Label1.Text = Len(TextBox1.Text)

End Sub
End Class
The output:

8.2(b) The Right Function


The Right function extracts the right portion of a phrase. The format for Visual Basic 6 is

8.2 (b) La Función Derecha

La función derecha extrae la porción derecha de una frase. El formato para el 6 de Visual
Basic es

Right (“Phrase”, n)

Where n is the starting position from the right of the phase where the portion of the phrase is
going to be extracted. For example,

Donde n es la posición de partida desde la derecha de la fase en la que la parte de la frase se


va a extraer. Por ejemplo,

Right(“Visual Basic”, 4) = asic

However, this format is not applicable in VB2012. In VB2012, we need use the following format

Sin embargo, este formato no es aplicable en VB2012. En VB2012, necesitamos utilizar el


siguiente formato

Microsoft.VisualBasic.Right(“Phrase”,n)

Example 8.2(a)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim text1 As String

text1 = TextBox1.Text

Label1.Text = Microsoft.VisualBasic.Right(text1, 4)

End Sub

The above program returns four right most characters of the phrase entered into the textbox.

The Output:

El programa anterior devuelve cuatro la mayoría de los caracteres correctos de la frase


introducidos en el cuadro de texto.

La salida:
*The reason of using the full reference is because many objects have the Right properties so
using Right on its own will make it ambiguous to Visual Basic 2012.

* La razón de utilizar la referencia completa se debe a que muchos objetos tienen las
propiedades adecuadas por lo que usar el botón derecho en su propio hará que sea ambigua
a Visual Basic 2012.

8.2(c)The Left Function

The Left function extract the left portion of a phrase. The syntax is

8.2 (c) La Función Izquierda

La función de Izquierda extraer la porción izquierda de una frase. La sintaxis es

Microsoft.VisualBasic.Left(“Phrase”,n)

Where n is the starting position from the left of the phase where the portion of the phrase is
going to be extracted. For example,

Donde n es la posición de partida desde la izquierda de la fase en la que la parte de la frase


se va a extraer. Por ejemplo,

Microsoft.VisualBasic.Left (“Visual Basic”, 4) = Visu .

[Lesson 7] << [CONTENTS] >> [Lesson 9]


Visual Basic 2012 Lesson 9- Using If….Then….Else
Visual Basic 2012 Lección 9 Uso de Si ... .Then ...
.Else
[Lesson 8] << [CONTENTS] >> [Lesson 10]

In the previous lessons, we have learned how to write code that accepts input from the user
and displays the output without controlling the program flow. In this lesson, you will learn how
to write Visual Basic 2012 code that can make decision when it process input from the user,
and control the program flow in the process.

Decision making process is an important part of programming in Visual Basic 2012 because it
can solve practical problems intelligently and provide useful output or feedback to the user. For
example, we can write a Visual Basic 2012 program that can ask the computer to perform
certain task until a certain condition is met, or a program that will reject non-numeric data. In
order to control the program flow and to make decisions, we need to use the conditional
operators and the logical operators together with the If control structure.

En las lecciones anteriores, hemos aprendido cómo escribir código que acepte la entrada por
parte del usuario y muestra la salida sin controlar el flujo del programa. En esta lección, usted
aprenderá cómo escribir código de Visual Basic 2012 que puede tomar la decisión cuando se
procesa la entrada del usuario, y controlar el flujo del programa en el proceso.

Proceso de toma de decisiones es una parte importante de la programación en Visual Basic


2012, ya que puede resolver problemas prácticos de forma inteligente y proporcionar una
salida útil o información al usuario. Por ejemplo, se puede escribir un programa de Visual
Basic 2012 que se puede pedir a la computadora para realizar determinada tarea hasta que se
cumpla una determinada condición, o un programa que rechazar los datos no numéricos. Con
el fin de controlar el flujo del programa y tomar decisiones, tenemos que utilizar los operadores
condicionales y los operadores lógicos junto con la estructura de control If.

9.1 Conditional Operators

The conditional operators are powerful tools that resembles mathematical operators . These
operators allow a Visual Basic 2012 program to compare data values and then decide what
actions to take, whether to execute a program or terminate the program and more. They are
also known as numerical comparison operators. Normally they are used to compare two values
to see whether they are equal or one value is greater or less than the other value. The
comparison will return a true or false result. These operators are shown in Table 9.1.

9.1 Los operadores condicionales

Los operadores condicionales son herramientas poderosas que se asemeja a los operadores
matemáticos. Estos operadores permiten a un programa de Visual Basic 2012 para comparar
valores de datos y luego decidir qué acciones tomar, ya sea para ejecutar un programa o
terminar el programa y más. También se conocen como operadores de comparación
numéricos. Normalmente se utilizan para comparar dos valores para ver si son iguales o un
valor es mayor o menor que el otro valor. La comparación devolverá un resultado verdadero o
falso. Estos operadores se muestran en la Tabla 9.1.

9.2 Logical Operators

Sometimes we might need to make more than one comparisons before a decision can be
made and an action taken. In this case, using numerical comparison operators alone is not
sufficient, we need to use additional operators, and they are the logical operators. These
logical operators are shown in Table 9.2.

9.2 Operadores lógicos

A veces puede ser que necesitemos hacer más de uno comparaciones antes de una decisión
puede ser tomada y la acción tomada. En este caso, el uso de operadores de comparación
numérica por sí sola no es suficiente, tenemos que usar operadores adicionales, y ellos son
los operadores lógicos. Estos operadores lógicos se muestran en la Tabla 9.2.

Normally the above operators are use to compare numerical data. However, you can also compare strings

with the above operators. In making strings comparison, there are certain rules to follows: Upper case

letters are less than lowercase letters, “A”<“B”<“C”<“D”…….<“Z” and number are less than letters.

Normalmente los operadores anteriores son el uso de comparar datos numéricos. Sin embargo, también

puede comparar cadenas con los operadores anteriores. Al hacer la comparación cuerdas, hay ciertas

reglas que sigue:. Las letras mayúsculas son menores que las letras minúsculas, "A" <"B" <"C" <"D" ......
<"Z" y el número es menos que las letras.

9.3 Using the If control structure with the Comparison Operators

To effectively control the Visual Basic 2012 program flow, we shall use the If control structure
together with the conditional operators and logical operators. There are basically three types of
If control structures, namely If….Then statement, If….Then… Else statement
andIf….Then….ElseIf statement.

9.3 Uso de la estructura de control Si con los operadores de comparación

Para controlar eficazmente el flujo del programa Visual Basic 2012, utilizaremos la estructura
de control Si junto con los operadores condicionales y operadores lógicos. Hay básicamente
tres tipos de estructuras de control Si, a saber ... Si la declaración .Then, SI ... .Then ... Else
andif ... .Then ... .ElseIf comunicado.

9.3(a) If….Then Statement


This is the simplest control structure which instructs the computer to perform a certain action
specified by the Visual Basic 2012 expression if the condition is true. However, when the
condition is false, no action will be performed. The syntax for the if…then.. statement is

9.3 (a) Si ... Declaración .Then

Esta es la estructura de control más simple que indica al ordenador para realizar una
determinada acción especificada por la expresión de Visual Basic 2012 si la condición es
verdadera. Sin embargo, cuando la condición es falsa, no se realizará ninguna acción. La
sintaxis de la si ... entonces .. afirmación es

If condition Then

Visual Basic 2012 expression

End If

Example 9.1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim myNumber As Integer
myNumber = TextBox1.Text
If myNumber > 100 Then
Label2.Text = ” You win a lucky prize”
End If
End Sub

* When you run the program and enter a number that is greater than 100, you will see the “You
win a lucky prize” statement. On the other hand, if the number entered is less than or equal to
100, you don’t see any display.
* Cuando se ejecuta el programa y escribe un número que es mayor que 100, verá la
declaración "Usted gana un premio de la suerte". Por otro lado, si el número introducido es
inferior o igual a 100, no ve ninguna pantalla.

9.3(b) If….Then…Else Statement

Using just If….Then statement is not very useful in programming and it does not provide
choices for the users. In order to provide a choice, we can use the If….Then…Else Statement.
This control structure will ask the computer to perform a certain action specified by the Visual
Basic 2012 expression if the condition is met. And when the condition is false ,an alternative
action will be executed. The syntax for the if…then.. Else statement is

9.3 (b) Si ... .Then ... Else

Utilizando sólo si ... .Then declaración no es muy útil en la programación y no ofrece opciones
para los usuarios. Con el fin de proporcionar una opción, podemos utilizar la instrucción If ...
.Then ... Else. Esta estructura de control le pedirá a la computadora para realizar una
determinada acción especificada por la expresión de Visual Basic 2012 si se cumple la
condición. Y cuando la condición es falsa, se ejecutará una acción alternativa. La sintaxis de la
si ... entonces .. Else es

If condition Then

Visual Basic 2012 expression

Else

Visual Basic 2012 expression

End If

Example 9.2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim myNumber As Integer
myNumber = TextBox1.Text
If myNumber > 100 Then
Label2.Text = ” Congratulation! You win a lucky prize”
Else
Label2.Text = ” Sorry, You dif not win any prize”
End If
End Sub

* When you run the program and enter a number that is greater than 100, the statement
“Congratulation! You win a lucky prize” will be shown. On the other hand, if the number entered
is less than or equal to 100, you will see the “Sorry, You dif not win any prize” statement

* Cuando se ejecuta el programa y escribe un número que es mayor que 100, la declaración
"¡Enhorabuena! Usted gana un premio de la suerte "se muestran. Por otro lado, si el número
introducido es menor o igual a 100, verá la declaración "Lo sentimos, usted no DIF ganar
cualquiera de los premios"

Example 9.3

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim myNumber, MyAge As Integer
myNumber = TextBox1.Text
MyAge = TextBox2.Text

If myNumber > 100 And myAge > 60 Then


Label2.Text = ” Congratulation! You win a lucky prize”
Else
Label2.Text = ” Sorry, You did not win any prize”
End If

End Sub

* This program use the logical operator And beside the conditional operators. This means that
both the conditions must be fulfilled in order for the conditions to be true, otherwise the second
block of code will be executed. In this example, the number entered must be more than 100
and the age must be more than 60 in order to win a lucky prize, any one of the above
conditions not fulfilled will disqualify the user from winning a prize.

* Este programa utiliza el operador lógico Y junto a los operadores condicionales. Esto
significa que tanto las condiciones deben cumplirse para que las condiciones sean
verdaderas, de lo contrario se ejecutará el segundo bloque de código. En este ejemplo, el
número introducido debe ser más de 100, y la edad debe ser más de 60 con el fin de ganar un
premio de la suerte, cualquiera de las anteriores condiciones no cumplidas, se descalificará al
usuario de ganar un premio.

9.3(c) If….Then…ElseIf Statement

If there are more than two alternative choices, using just If….Then….Else statement will not be
enough. In order to provide more choices, we can use the If….Then…ElseIf Statement.
executed. The general format for the if…then.. Else statement is

9.3 (c) Si ... .Then ... ElseIf Declaración

Si hay más de dos opciones alternativas, utilizando sólo si ... .Then ... .Else declaración no
será suficiente. Con el fin de ofrecer más opciones, podemos utilizar la instrucción If ... .Then
... ElseIf. ejecutado. El formato general para el si ... entonces .. Else es

If condition Then

Visual Basic 2012 expression

ElseIf condition Then


Visual Basic 2012 expression

ElseIf condition Then

Visual Basic 2012 expression

Else

Visual Basic 2012 expression

End If

Example 9.4

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim Mark As Integer

Dim Grade as String

Mark = TextBox1.Text
If myNumber >=80 Then
Grade=”A”

ElseIf Mark>=60 and Mark<80 then

Grade=”B”

ElseIf Mark>=40 and Mark<60 then

Grade=”C”

Else

Grade=”D”

End If
End Sub

[Lesson 8] << [CONTENTS] >> [Lesson 10]


Visual Basic 2012 Lesson 10- Using Select Case
Visual Basic 2012 Lección 10- Usando Seleccione
caso
[Lesson 9] << [CONTENTS] >> [Lesson 11]

In the previous lesson, we have learned how to control the program flow using the If…ElseIf
control structure. In this lesson, you will learn how to use the Select Case control structure
in Visual Basic 2012 to control the program flow . The Select Case control structure is slightly
different from the If….ElseIf control structure . The difference is that the Select Case control
structure basically only make decision on one expression or dimension (for example the
examination grade) while the If …ElseIf statement control structure may evaluate only one
expression, each If….ElseIf statement may also compute entirely different dimensions. Select
Case is preferred when there exist multiple conditions as using If…Then..ElseIf statements will
become too messy.

En la lección anterior, hemos aprendido a controlar el flujo del programa utilizando la


estructura de control If ... ElseIf. En esta lección, obtendrá información sobre cómo utilizar la
estructura Select casos y controles en Visual Basic 2012 para controlar el flujo del programa.
La estructura de control de selección de casos es ligeramente diferente de la Si ... .ElseIf
estructura de control. La diferencia es que la estructura Select casos y controles, básicamente,
sólo tomar la decisión en una expresión o dimensión (por ejemplo, la calificación del examen),
mientras que la estructura de control de instrucción If ... ElseIf puede evaluar sólo una
expresión, cada uno ... Si .ElseIf declaración puede también calcular totalmente diferente
dimensiones. Se prefiere Select Case cuando existen múltiples condiciones como el uso de Si
... Then..ElseIf declaraciones se harán demasiado sucio.

10.1 The Select Case…End Select Structure

The syntax of the Select Case control structure in Visual Basic 2012 is as follows:

10.1 El Select Case ... End Select Estructura

La sintaxis de la estructura de control de selección de caso en Visual Basic 2012 es el


siguiente:

Select Case test expressionCase expression list 1

Block of one or more Visual Basic 2012 statements

Case expression list 2

Block of one or more Visual Basic 2012 Statements

Case expression list 3

.
.

Case Else

Block of one or more Visual Basic 2012 StatementsEnd Select

Seleccione

Expresión de prueba Caso

Lista de expresiones Caso 1

Bloque de uno o más estados de Visual Basic 2012

Lista de expresiones Caso 2

Bloque de uno o más de Visual Basic 2012 Declaraciones

Lista de expresiones de caso 3

caso

Else

Bloque de uno o más de Visual Basic 2012 StatementsEnd Seleccionar

10.2 The usage of Select Case is shown in the following examples

Example 10.1‘ Example 10.2

Examination Grades In this example, you can use the

Dim grade As String keyword Is together with the

Private Sub Compute_Click( comparison operators.Private Sub

) Button1_Click(ByVal sender As
grade=txtgrade.Text System.Object, ByVal e As

Select Case grade System.EventArgs) Handles

Case “A” Button1.Click’Examination MarksDim

Label1.Text=”High mark As Single

Distinction” mark = mrk.Text

Case “A-” Select Case mark

Label1.Text=”Distinction” Case Is >= 85

Case “B” Label1.Text= “Excellence”

Label1.Text=”Credit” Case Is >= 70

Case “C” Label2.Text= “Good”

Label1.Text=”Pass” Case Is >= 60

Case Else Label3.Text = “Above Average”

Label1.Text=”Fail” Case Is >= 50

End Select Label4.Text= “Average”

Case Else

Label5.Text = “Need to work harder”

End SelectEnd Sub

Example 10.3Example Example 10.4Grades in high school

10.2 can be rewritten as are usually presented with a single

follows: capital letter such as A, B, C, D or E.

The grades can be computed as


Private Sub
follow:
Button1_Click(ByVal
sender As
System.Object, ByVal e
As System.EventArgs) Private Sub
Handles Button1.Click Button1_Click(ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles
‘Examination Marks
Button1.Click
Dim mark As Single
‘Examination Marks
mark = Textbox1.Text
Select Case mark
Case 0 to 49 Dim mark As Single
Label1.Text = “Need to
work harder” mark = TextBox1.Text

Case 50 to 59 Select Case mark


Label1.Text =
“Average” s Case 0 To 49
Label1.Text = “E”
Case 60 to 69
Label1.Text= “Above Case 50 To 59
Average”
Label1.Text = “D”
Case 70 to 84 Case 60 To 69
Label1.Text = “Good”
Label1.Text = “C”
Case 85 to 100 Case 70 To 79
Label1.Text=
“Excellence”
Label1.Text = “B”
Case Else
Case 80 To 100
Label1.Text= “Wrong
Label1.Text = “A”
entry, please reenter the
mark”
Case Else
Label1.Text = “Error, please
End Select
reenter the mark”
End Sub
End Select

End Sub

The output of Example 10.4


[Lesson 9] << [CONTENTS] >> [Lesson 11]
Visual Basic 2012 Lesson 11- Looping
Visual Basic 2012 Lección 11 - Looping
[Lesson 10] << [CONTENTS] >> [Lesson 12]

Visual Basic 2012 allows a procedure to be repeated as many times as long as the processor
and memory could support. This is generally called looping . Looping is required when we need
to process something repetitively until a certain condition is met. For example, we can design a
program that adds a series of numbers until the sum exceeds a certain value, or a program
that asks the user to enter data repeatedly until he/she keys in the word ‘Finish’. In Visual
Basic 2012, we have three types of Loops, they are the For…..Next loop, the Do loop. and the
While…..End while loop

Visual Basic 2012 permite que un procedimiento que se repite tantas veces tan largo como el
procesador y la memoria podrían apoyar. Esto generalmente se llama bucle. Se requiere
Looping cuando necesitamos para procesar algo repetidamente hasta que se cumpla una
determinada condición. Por ejemplo, podemos diseñar un programa que agrega una serie de
números hasta que la suma es superior a un cierto valor, o un programa que pide al usuario
que introduzca los datos varias veces hasta que él / ella las llaves en la palabra 'Finish'. En
Visual Basic 2012, tenemos tres tipos de bucles, que son la For ... ..Next bucle, el bucle Do. y
el tiempo ... ..End while

11.1 For….Next Loop in Visual Basic 2012

The format is:

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next

To exit a For…..Next Loop, you can place the Exit For statement
within the loop; and it is normally used together with the
If….Then…..sstatement. For its application, you can refer to example
11.1 d.

Para salir de un bucle For ... ..Next, se puede colocar la instrucción Exit
For dentro del bucle; y se utiliza normalmente junto con el Si ... .Then
... ..sstatement. Para su aplicación, se puede hacer referencia al ejemplo
11.1 d.
Example 11.1 a Example 11.1b

Dim counter as Integer Dim counter , sum As Integer


For counter=1 to 10 For counter=1 to 100 step 10
ListBox1.Items.Add sum+=counter
(counter) ListBox1.Items.Add (sum)
Next Next
* The program will enter
number 1 to 10 into the list * The program will calculate the sum of the numbers as
box. follows:

sum=0+10+20+30+40+……

Example 11.1c Example 11.1d

Dim counter, sum As Dim n as Integer


Integer For n=1 to 10
sum = 1000 If n>6 then
For counter = 100 To 5 Exit For
Step -5 End If
sum – = counter Else
ListBox1.Items.Add(sum) ListBox1.Items.Add ( n)
Next Next
*Notice that increment can End If
be negative. Next

The program will compute The process will stop when n is greater than 6.
the
subtraction as follow:
1000-100-95-90-……….
11.2 Do Loop

The Do Loop formats are

a) Do While condition
Block of one or more Visual Basic 2012 statements
Loop

b) Do
Block of one or more Visual Basic 2012 statements
Loop While condition

c) Do Until condition
Block of one or more Visual Basic 2012 statements
Loop

d) Do
Block of one or more Visual Basic 2012 statements
Loop Until condition

* Exiting the Loop

Sometime we need exit to exit a loop prematurely because of a


certain
condition is fulfilled. The syntax to use is known as Exit Do. Lets
examine the following examples

* Salir del bucle

En algún momento tenemos que salir para salir de un bucle


prematuramente debido a un cierto

condición se cumple. La sintaxis de uso es conocido como Exit


Do. Vamos a examinar los siguientes ejemplos
Example 11.2(a) Example 11.2(b)

Do while counter Private Sub Button1_Click(ByVal sender As


<=1000 System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
TextBox1.Text=counter
counter +=1 Dim sum, n As Integer

Loop ListBox1.Items.Add(“n” & vbTab & “Sum”)


ListBox1.Items.Add(“———————-“)
* The above example Do
will keep on adding n += 1
until counter >1000. sum += n
ListBox1.Items.Add(n & vbTab & sum)
The above example can If n = 100 Then
be rewritten as Exit Do
End If
Loop
Do
TextBox1.Text=counter
counter+=1 End Sub
Loop until
counter>1000

[Lesson 10] << [CONTENTS] >> [Lesson 12]


Visual Basic 2012 Lesson 12- Functions Part 1
Visual Basic 2012 Lección 12- Funciones Parte 1
[Lesson 11] << [CONTENTS] >> [Lesson 13]

A function in Visual Basic 2012 is similar to a normal procedure but the main purpose of the
function is to accept a certain input and return a value which is passed on to the main program
to finish the execution. There are two types of functions in Visual Basic 2012, the built-in
functions (or internal functions) and the functions created by the programmers.

The general format of a function is

FunctionName (arguments)

The arguments are values that are passed on to the function.In this lesson, we are going to
learn two very basic but useful internal functions of Visual Basic 2012 , i.e. the MsgBox( ) and
InputBox ( ) functions.

Una función en Visual Basic 2012 es similar a un procedimiento normal pero el propósito
principal de la función es la de aceptar una cierta entrada y devolver un valor que se transmite
al programa principal para terminar la ejecución. Hay dos tipos de funciones en Visual Basic
2012, las funciones integradas (o funciones internas) y las funciones creadas por los
programadores.

El formato general de una función es

FunctionName (argumentos)

Los argumentos son los valores que se transmiten a la function.In esta lección, vamos a
aprender dos funciones internas muy básicas pero útiles de Visual Basic 2012, es decir, el
MsgBox () y InputBox () funciones.

12.1 MsgBox ( ) Function

The objective of MsgBox is to produce a pop-up message box and prompt the user to click on
a command button before he /she can continues. This format is as follows:

yourMsg=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, will display the message in the message box. The Style Value will
determine what type of command buttons appear on the message box, please refer to Table
12.1 for types of command button displayed. The Title argument will display the title of the
message board.
12.1 MsgBox () Función

El objetivo de MsgBox es producir un cuadro de mensaje emergente y pedirá al usuario que


haga clic en un botón de comando antes de que él / ella pueda continúa. Este formato es el
siguiente:

yourMsg = MsgBox (Prompt, Estilo Valor, Título)

El primer argumento, Prompt, se mostrará el mensaje en el cuadro de mensaje. El valor de


estilo se determinará qué tipo de botones de comando aparecen en el cuadro de mensaje, por
favor consulte la Tabla 12.1 para los tipos de botón de comando que se muestran. El
argumento Título mostrará el título del panel de mensajes.

We can use named constants in place of integers for the second argument to make the
programs more readable. In fact, Visual Basic 2012 will automatically shows up a list of named
constants where you can select one of them.

Podemos utilizar constantes con nombre en lugar de enteros para el segundo argumento para
hacer los programas más legibles. De hecho, Visual Basic 2012 se muestra automáticamente
una lista de constantes con nombre que se puede seleccionar uno de ellos.

example: yourMsg=MsgBox( “Click OK to Proceed”, 1, “Startup Menu”)

and yourMsg=Msg(“Click OK to Proceed”. vbOkCancel,”Startup Menu”)

are the same.

yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The
values are determined by the type of buttons being clicked by the users. It has to be declared
as Integer data type in the procedure or in the general declaration section. Table 12.2 shows
the values, the corresponding named constant and buttons.
yourMsg es una variable que contiene los valores devueltos por la función MsgBox (). Los
valores se determinan por el tipo de botones que se ha pulsado por los usuarios. Tiene que
ser declarado como tipo de datos de entero en el procedimiento o en la sección de declaración
general. Tabla 12.2 muestra los valores, los correspondientes nombrados botones y
constante.

Example 12.1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim testmsg As Integer

testmsg = MsgBox(“Click to test”, 1, “Test message”)

If testmsg = 1 Then
MessageBox.Show(“You have clicked the OK button”)
Else
MessageBox.Show(“You have clicked the Cancel button”)
End If

End Sub

To make the message box looks more sophisticated, you can add an icon besides the
message. There are four types of icons available in VB2008 as shown in Table 12.3

Para hacer que el cuadro de mensaje parece más sofisticado, puede agregar un icono
además del mensaje. Hay cuatro tipos de iconos disponibles en VB2008 como se muestra en
la Tabla 12.3
Example 12.2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim testMsg As Integer

testMsg = MsgBox(“Click to Test”, vbYesNoCancel + vbExclamation, “Test Message”)

If testMsg = 6 Then
MessageBox.Show(“You have clicked the yes button”)
ElseIf testMsg = 7 Then
MessageBox.Show(“You have clicked the NO button”)
Else
MessageBox.Show(“You have clicked the Cancel button”)
End If

End Sub

The first argument, Prompt, will display the message


12.2 The InputBox( ) Function

An InputBox( ) function will display a message box where the user can enter a value or a
message in the form of text. In VB2005, you can use the following format:

myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)

myMessage is a variant data type but typically it is declared as string, which accept the
message input by the users. The arguments are explained as follows:

Prompt – The message displayed normally as a question asked.


Title – The title of the Input Box.
default-text – The default text that appears in the input field where users can use it as his
intended input or he may change to the message he wish to enter.
x-position and y-position – the position or tthe coordinates of the input box.

However, the format won’t work in Visual Basic 2012 because InputBox is considered a
namespace. So, you need to key in the full reference to the Inputbox namespace, which is

Microsoft.VisualBasic.InputBox(Prompt, Title, default_text, x-position, y-position)

The parameters remain the same.

12.2 El InputBox () Función

Una función InputBox () aparecerá un cuadro de mensaje en el que el usuario puede introducir
un valor o un mensaje en forma de texto. En VB2005, puede utilizar el siguiente formato:

myMessage = InputBox (Prompt, Título, default_text, la posición x, y posición)

myMessage es un tipo de datos variant pero normalmente se declara como cuerdas, que
acepte la entrada de mensajes de los usuarios. Los argumentos se explican como sigue:

Prompt - El mensaje aparece normalmente como una pregunta.

Título - El título de la caja de entrada.

default-texto - El texto predeterminado que aparece en el campo de entrada donde los


usuarios pueden utilizarlo como su entrada prevista o que pueden cambiar al mensaje que
desea entrar.

posición x e y de la posición - la posición o excedía coordenadas del cuadro de entrada.

Sin embargo, el formato no funcionará en Visual Basic 2012, ya InputBox es considerado un


espacio de nombres. Por lo tanto, hay que introducir en la referencia completa para el espacio
de nombres Inputbox, que es

Microsoft.VisualBasic.InputBox (Prompt, Título, default_text, x-posición, y-posición)

Los parámetros siguen siendo los mismos.


Example 12.3

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim userMsg As String

userMsg = Microsoft.VisualBasic.InputBox(“What is your message?”, “Message Entry Form”,


“Enter your messge here”, 500, 700)

If userMsg <> “” Then


MessageBox.Show(userMsg)
Else
MessageBox.Show(“No Message”)
End If
End Sub

The inputbox will appear as shown in the figure below when you press the command button

La caja de texto aparecerá como se muestra en la figura siguiente, cuando se pulsa el botón
de comando

[Lesson 11] << [CONTENTS] >> [Lesson 13]


Visual Basic 2012 Lesson 13- Function Part II
Visual Basic 2012 Lección 13-Función Parte II
[Lesson 12] << [CONTENTS] >> [Lesson 14]

We have learned the basic concept of function in Visual Basic 2012. In particular, we have
shown you how to use the MsgBox function and InputBox function in Lesson 12. In fact, we
have already illustrated a few string manipulation functions in Lesson 8, they are the Len
function, the Left function and the Right Function. In this lesson, we will learn other string
manipulation functions in visual basic 2012.

Hemos aprendido el concepto básico de la función en Visual Basic 2012 En particular, hemos
demostrado cómo utilizar la función MsgBox y la función InputBox en la Lección 12 De hecho,
ya hemos ilustrado algunas funciones de manipulación de cadenas en la lección 8, que son la
función Len, la función de la izquierda y de la función Derecha. En esta lección, aprenderemos
otras funciones de manipulación de cadenas en Visual Basic 2012.

13.1 The Mid Function

The Mid function is used to retrieve a part of text form a given phrase. The format of the Mid
Function is

Mid(phrase, position,n)

where

phrase is the string from which a part of text is to be retrieved.

position is the starting position of the phrase from which the retrieving process begins.

n is the number of characters to retrieve.

unción 13.1 El Mid

La función Mid se utiliza para recuperar una parte de texto forman una frase. El formato de la
función Mid es

Mediados (frase, posición, n)

donde

frase es la cadena de la que una parte de texto se va a recuperar.

posición es la posición inicial de la frase de la cual comienza el proceso de recuperación.


n es el número de caracteres para recuperar.

Example 13.1:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim myPhrase As String
myPhrase = Microsoft.VisualBasic.InputBox(“Enter your phrase”)
Label1.Text = Mid(myPhrase, 2, 6)
End Sub

* In this example, when the user clicks the command button, an inputbox will pop up asking the
user to input a phrase. After a phrase is entered and the OK button is pressed, the label will
show the extracted text starting from position 2 of the phrase and the number of characters
extracted is 6.

* En este ejemplo, cuando el usuario hace clic en el botón de comando, una caja de texto
aparecerá para preguntarle al usuario que introduzca una frase. Después de introducir una
frase y se pulsa el botón OK, la etiqueta mostrará el texto extraído a partir de la posición 2 de
la frase y el número de caracteres extraída es 6.

The figures are shown below:


13.2 The Right Function

The Right function extracts the right portion of a phrase. The format is

Microsoft.Visualbasic.Right (“Phrase”, n)

Where n is the starting position from the right of the phase where the portion of the phrase is
going to be extracted. For example:

13.2 La Función Derecha

La función derecha extrae la porción derecha de una frase. El formato es

Microsoft.Visualbasic.Right ("Frase", n)

Donde n es la posición de partida desde la derecha de la fase en la que la parte de la frase se


va a extraer. Por ejemplo:

Microsoft.Visualbasic.Right (“Visual Basic”, 4) = asic

Example 13.2: The following code extracts the right portion any phrase entered by the user.

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim myword As String

myword = TextBox1.Text
Label1.Text = Microsoft.VisualBasic.Right (myword, 4)

End Sub

13.3 The Left Function

The Left function extracts the left portion of a phrase. The format is

Microsoft.Visualbasic.Right (“Phrase”, n)

Where n is the starting position from the left of the phase where the portion of the phrase is
going to be extracted. For example:

13.3 La Función Izquierda

La función de Izquierda extrae la porción izquierda de una frase. El formato es

Microsoft.Visualbasic.Right ("Frase", n)

Donde n es la posición de partida desde la izquierda de la fase en la que la parte de la frase


se va a extraer. Por ejemplo:

Microsoft.Visualbasic.Left(“Visual Basic”, 4) = asic

Example 13.3: The following code extracts the left portion any phrase entered by the user.

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim myword As String

myword = TextBox1.Text

Label1.Text = Microsoft.VisualBasic.Left (myword, 4)

End Sub

13.4 The Trim Function

The Trim function trims the empty spaces on both side of the phrase. The format is

Trim(“Phrase”)

.For example, Trim (” Visual Basic “) = Visual basic

13.4 La función de ajuste

La función Recortar recorta los espacios vacíos en ambos lados de la frase. El formato es

Trim ("Frase")
.For Ejemplo, Recorte ("Visual Basic") = Visual basic

Example 13.4

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim myPhrase As String
myPhrase = Microsoft.VisualBasic.InputBox(“Enter your phrase”)
Label1.Text = Trim(myPhrase)
End Sub

13.5 The Ltrim Function

The Ltrim function trims the empty spaces of the left portion of the phrase. The format is

Ltrim(“Phrase”)

.For example,

13.5 La función LTrim

La función LTrim recorta los espacios vacíos de la parte izquierda de la frase. El formato es

Ltrim ("Frase")

.For Ejemplo,

Ltrim (” Visual Basic 2012″)= Visual basic 2012

13.6 The Rtrim Function

The Rtrim function trims the empty spaces of the right portion of the phrase. The format is

Rtrim(“Phrase”)

.For example,

Rtrim (“Visual Basic 2012 “) = Visual Basic 2012

13.6 La Función Rtrim

La función de Rtrim recorta los espacios vacíos de la parte derecha de la frase. El formato es

Rtrim ("Frase")

.For Ejemplo,

Rtrim ("Visual Basic 2012") = Visual Basic 2012


13.7 The InStr function

The InStr function looks for a phrase that is embedded within the original phrase and returns
the starting position of the embedded phrase. The format is

Instr (n, original phase, embedded phrase)

Where n is the position where the Instr function will begin to look for the embedded phrase. For
example

Instr(1, “Visual Basic 2012 “,”Basic”)=8

*The function returns a numeric value.

You can write a program code as shown below:

13.7 La función InStr

La función InStr busca una frase que está incrustado dentro de la frase original y devuelve la
posición inicial de la frase embebido. El formato es

Instr (n, fase original, frase embebido)

Donde n es la posición donde la función Instr comenzará a buscar la frase embebido. por
ejemplo

Instr (1, "Visual Basic 2012", "Basic") = 8

* La función devuelve un valor numérico.

Usted puede escribir un código de programa como se muestra a continuación:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Label1.Text = InStr(1, “Visual Basic”, “Basic”)


End Sub

13.8 The Ucase and the Lcase Functions

The Ucase function converts all the characters of a string to capital letters. On the other hand,
the Lcase function converts all the characters of a string to small letters.

The format is

13.8 El Ucase y las Funciones LCASE

La función Ucase convierte todos los caracteres de una cadena a mayúsculas. Por otro lado,
la función de LCASE convierte todos los caracteres de una cadena de letras pequeñas.
El formato es

Microsoft.VisualBasic.UCase(Phrase)

Microsoft.VisualBasic.LCase(Phrase)

For example,

Microsoft.VisualBasic.Ucase(“Visual Basic”) =VISUAL BASIC

Microsoft.VisualBasic.Lcase(“Visual Basic”) =visual basic

13.9 The Chr and the Asc functions

The Chr function returns the string that corresponds to an ASCII code while the Asc function
converts an ASCII character or symbol to the corresponding ASCII code. ASCII stands for
“American Standard Code for Information Interchange”. Altogether there are 255 ASCII codes
and as many ASCII characters. Some of the characters may not be displayed as they may
represent some actions such as the pressing of a key or produce a beep sound. The format of
the Chr function is

13.9 El las funciones Asc y Chr

La función Chr devuelve la cadena que corresponde a un código ASCII mientras que la
función Asc convierte un carácter ASCII o símbolo en el código ASCII correspondiente. ASCII
significa "Código Estándar Americano para Intercambio de Información". En total hay 255
códigos ASCII y tantos caracteres ASCII. Algunos de los caracteres no se muestren, ya que
pueden representar algunas acciones, como la pulsación de una tecla o producir un sonido de
pitido. El formato de la función Chr es

Chr(charcode)

and the format of the Asc function is

Asc(Character)

The following are some examples:

Chr(65)=A, Chr(122)=z, Chr(37)=% ,

Asc(“B”)=66, Asc(“&”)=38

[Lesson 12] <<[CONTENTS] >> [Lesson 14]


Visual Basic 2012 Lesson 14- Functions Part III- Math Functions
Visual Basic 2012 Lección 14- Funciones Funciones Parte III
Matemáticas
[Lesson 13] << [CONTENTS] >> [Lesson 15]

In previous lessons, we have learned how to write codes in Visual Basic 2012 that perform
arithmetic operations using standard mathematical operators. However, in order to perform
more complex mathematical calculations, we need to use the built-in math functions in Visual
Basic 2012. There are numerous built-in mathematical functions in Visual Basic 2012 which we
will introduce them one by one in this lesson.

En las lecciones anteriores, hemos aprendido cómo escribir códigos en Visual Basic 2012 que
realizan operaciones aritméticas mediante operadores matemáticos estándar. Sin embargo,
con el fin de realizar cálculos matemáticos más complejos, tenemos que utilizar las funciones
matemáticas incorporadas en Visual Basic 2012 Hay numerosas funciones integradas de
matemáticas en Visual Basic 2012 que vamos a introducirlos uno a uno en esta lección.

14.1 The Abs function

The Abs function returns the absolute value of a given number.

The syntax is

Math. Abs (number)

* The Math keyword here indicates that the Abs function


belong to the Math class. However, not all mathematical
functions belong to the Math class.

La función Abs devuelve el valor absoluto de un número


dado.

La sintaxis es

Matemáticas. Abs (número)

* La palabra clave de Matemáticas aquí indica que la función


Abs pertenecen a la clase de matemáticas. Sin embargo, no
todas las funciones matemáticas pertenecen a la clase de
matemáticas.

14.2 The Exp function

The Exp of a number x is the exponential value of x, i.e. ex . For example,


Exp(1)=e=2.71828182
The syntax is Math.Exp (number)

14.2 La función Exp

El Exp de un número x es el valor exponencial de x, es decir, ex. Por ejemplo, Exp (1) = e =
2,71828182

La sintaxis es math.exp (número)

Example:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles Button1.Click

Dim num1, num2 As Single


num1 = TextBox1.Text
num2 = Math.Exp(num1)
Label1.Text = num2

End Sub

14.3 The Fix Function

The Fix function truncates the decimal part of a positive number and returns the largest integer
smaller than the number. However, when the number is negative, it will return smallest integer
larger than the number. For example, Fix(9.2)=9 but Fix(-9.4)=-9

Example:

14.3 La función Fix

La función de corrección trunca la parte decimal de un número positivo y devuelve el mayor


entero menor que el número. Sin embargo, cuando el número es negativo, volverá número
entero más pequeño mayor que el número. Por ejemplo, Fix (9,2) = 9 pero Fix (-9,4) = - 9

ejemplo:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim num1, num2 As Single


num1 = TextBox1.Text
num2 = Fix(num1)
Label1.Text = num2

End Sub
14.4 The Int Function

The Int is a function that converts a number into an integer by truncating its decimal part and
the resulting integer is the largest integer that is smaller than he number. For example

14.4 La función Int

La Int es una función que convierte un número en un entero truncando su parte decimal y el
entero resultante es el mayor entero que es menor que él número. por ejemplo

Int(2.4)=2, Int(6.9)=6 , Int(-5.7)=-6, Int(-99.8)=-100

14.5 The Log Function

The Log function is the function that returns the natural logarithm of a number. For example,
Log(10)=2.302585

Example:

14.5 La función de registro

La función de registro es la función que devuelve el logaritmo natural de un número. Por


ejemplo, Log (10) = 2,302585

ejemplo:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim num1, num2 As Single


num1 = TextBox1.Text
num2 = Math.Log(num1)
Label1.Text = num2

End Sub

* The logarithm of num1 will be displayed on label1

* El logaritmo de num1 se mostrará en label1

14.6 The Rnd( ) Function

Rnd is a very useful function in Visual Basic 2012 . We use the Rnd funciton to write code that
involves chance and probability. The Rnd function returns a random value between 0 and 1.
Random numbers in their original form are not very useful in programming until we convert
them to integers. For example, if we need to obtain a random output of 6 integers ranging from
1 to 6, which makes the program behave like a virtual dice, we need to convert the random
numbers to integers using the formula Int(Rnd*6)+1.

Example:
14.6 El Rnd () Función

Vta es una función muy útil en Visual Basic 2012. Usamos el funciton Vta escribir código que
involucra el azar y probabilidad. La función Rnd devuelve un valor aleatorio entre 0 y 1.
números aleatorios en su forma original no son muy útiles en la programación hasta que los
convertimos a enteros. Por ejemplo, si tenemos que obtener una salida aleatoria de 6 números
enteros de 1 a 6, lo que hace que el programa se comporte como un dado virtuales,
necesitamos convertir los números al azar a números enteros utilizando la fórmula Int (Rnd *
6) +1 .

ejemplo:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim num as integer

Randomize( )

Num=Int(Rnd()*6)+1

Label1.Text=Num

End Sub

In this example, Int(Rnd*6) will generate a random integer between 0 and 5 because the
function Int truncates the decimal part of the random number and returns an integer. After
adding 1, you will get a random number between 1 and 6 every time you click the command
button. For example, let say the random number generated is 0.98, after multiplying it by 6, it
becomes 5.88, and using the integer function Int(5.88) will convert the number to 5; and after
adding 1 you will get 6.

En este ejemplo, Int (Rnd * 6) va a generar un entero aleatorio entre 0 y 5 porque la función Int
trunca la parte decimal del número aleatorio y devuelve un entero. Después de añadir 1,
obtendrá un número aleatorio entre 1 y 6 cada vez que hace clic en el botón de comando. Por
ejemplo, vamos a decir que el número aleatorio generado es de 0,98, después de multiplicar
por 6, se convierte en 5,88, y el uso de la función Int número entero (5.88) se convertirá el
número a 5; y después de la adición de 1 obtendrá 6.

14.7 The Round Function

The Round function is the function that rounds up a number to a certain number of decimal
places. The Format is Round (n, m) which means to round a number n to m decimal places.
For example, Math.Round (7.2567, 2) =7.26

Example

14.7 La función de Ronda

La función de Ronda es la función que redondea un número a un número determinado de


decimales. El formato es redonda (n, m) lo que significa para redondear un número n de m
lugares decimales. Por ejemplo, Math.Round (7,2567, 2) = 7,26
Ejemplo

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Math.Round(num1, 2)
Label1.Text = num2

End Sub

* The Math keyword here indicates that the Round function belong to the Math class.

* La palabra clave matemáticas aquí indica que la función Round pertenecen a la clase Math.

[Lesson 13] << [CONTENTS] >> [Lesson 15]


Visual Basic 2012 Lesson 15– Functions Part IV- Formatting
Functions
Visual Basic 2012 Lección 15 a Funciones Funciones Parte IV de
formato
[Lesson 14] << [CONTENTS] >> [Lesson 16]

The Format function in Visual Basic 2012 is a very powerful formatting function. It is used to
display the numeric values in various forms. There are two types of Format functions, one of
them is the built-in or predefined format while another one can be defined by the users.

(i) The format of the predefined Format function is

Format (n, “style argument”)

where n is a number.

The list of style arguments in Visual Basic 2012 is given in Table 15.1.

La función de formato en Visual Basic 2012 es una función de formato muy potente. Se utiliza
para mostrar los valores numéricos de varias formas. Hay dos tipos de funciones de formato,
uno de ellos es el incorporado o formato predefinido mientras que otro puede ser definido por
los usuarios.

(i) El formato de la función de formato predefinido se

Formato (n, "el argumento de estilo")

donde n es un número.

La lista de argumentos de estilo en Visual Basic 2012 figura en el cuadro 15.1.

Table 15.1 List of style arguments Tabla 15.1 Lista de argumentos del estilo

Style Explanation Example

argument

General To display the number Format(8972.234,

Number without having separators “General

between thousands. Number”)=8972.234


Fixed To display the number Format(8972.2,

without having separators “Fixed”)=8972.23

between thousands and

rounds it up to two decimal

places.

Standard To display the number with Format(6648972.265,

separators or separators “Standard”)=

between thousands and 6,648,972.27

rounds it up to two decimal

places.

Currency To display the number with Format(6648972.265,

the dollar sign in front, has “Currency”)=

separators between $6,648,972.27

thousands as well as rounding

it up to two decimal places.

Percent Converts the number to the Format(0.56324,

percentage form and displays “Percent”)=56.32 %

a % sign and rounds it up to

two decimal places.

Example 15.1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click, Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format(8972.234, “General Number”)
Label2.Text = Format(8972.2, “Fixed”)
Label3.Text = Format(6648972.265, “Standard”)
Label4.Text = Format(6648972.265, “Currency”)
Label5.Text = Format(0.56324, “Percent”)
End Sub

The Output window is shown below:

(ii) The format of the user-defined Format function is

Format (n, “user’s format”)

Although it is known as user-defined format, we still need to follows certain formatting styles.
Examples of user-defined formatting style are listed in Table 15.2

(ii) El formato de la función de formato definido por el usuario es

Formato (n, "el formato de usuario")

A pesar de que se conoce como formato definido por el usuario, todavía tenemos que sigue
ciertos estilos de formato. Los ejemplos de estilo de formato definido por el usuario se
enumeran en la Tabla 15.2
Example 15.2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click, Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format(8972.234, “0.0”)
Label2.Text = Format(8972.2345, “0.00”)
Label3.Text = Format(6648972.265, “#,##0.00″)
Label4.Text = Format(6648972.265, “$#,##0.00″)
Label5.Text = Format(0.56324, “0%”)
End Sub

The Output window is shown below:


[Lesson 14] [CONTENTS] >> [Lesson 16]
Visual Basic 2012 Lesson 16-Formatting Date and Time
Visual Basic 2012 Lección 16-Formato de fecha y hora
[Lesson 15] << [CONTENTS] >> [Lesson 17]

16.1 Formatting Date and time using predefined formats in Visual Basic 2012

In Visual Basic 2012 , we can format date and time using predefined formats or user-defined
formats. The predefined formats of date and time are shown in Table 16.1.

16.1 Formato de fecha y hora utilizando formatos predefinidos en Visual Basic 2012

En Visual Basic 2012, se puede dar formato a la fecha y la hora utilizando formatos
predefinidos o formatos definidos por el usuario. Los formatos predefinidos de fecha y hora se
muestran en la Tabla 16.1.

* Instead of “General date”, you can also use the abbreviated format “G” , i.e. Format (Now,
“G”). For “Long Time”, you can use the abbreviated format “T” and for “Short Time”, you may
use the abbreviated format “t”

Example 16.1

* En lugar de "fecha general", también se puede utilizar el formato abreviado "G", es decir,
Formato (Ahora, "G"). Para "Long Time", puede utilizar el formato abreviado de "T" y de "poco
tiempo", puede utilizar el formato "t" abreviado

Ejemplo 16.1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Label1.Text = Format(Now, “General Date”)
Label2.Text = Format(Now, “Long Date”)
Label3.Text = Format(Now, “short Date”)
Label4.Text = Format(Now, “Long Time”)
Label5.Text = Format(Now, “Short Time”)
End Sub

The output is shown in the figure below:

La salida se muestra en la siguiente figura:

16.2 Formatting Date and time using user-defined formats

Besides using the predefined formats, you can also use the user-defined formatting functions.
The general syntax of a user-defined for date/time is

Format (expression,style)

16.2 Formato de fecha y hora utilizando formatos definidos por el usuario

Además de utilizar los formatos predefinidos, también puede utilizar las funciones de formato
definidas por el usuario. La sintaxis general de una fecha para la definida por el usuario / hora

Format (expresión, estilo)


Example 16.2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click, Button2.Click, Button3.Click

Label1.Text = Format(Now, “M”)


Label2.Text = Format(Now, “MM”)
Label3.Text = Format(Now, “MMM”)
Label4.Text = Format(Now, “MMMM”)
Label5.Text = Format(Now, “dd/MM/yyyy”)
Label6.Text = Format(Now, “MMM,d,yyyy”)
Label7.Text = Format(Now, “h:mm:ss tt”)
Label8.Text = Format(Now, “MM/dd/yyyy h:mm:ss tt”)

End Sub

The output is shown in the figure below:


[Lesson 15] << [CONTENTS] >> [Lesson 17]
Visual Basic 2012 Lesson 17- Using Check Box
Básica 2012 Lección 17-Uso de casilla de verificación
Visual
[Lesson 16] << [CONTENTS] >> [Lesson 18]

Check box is a very useful control in Visual Basic 2012. It allows the user to select one or more
items by checking the check box or check boxes concerned. For example, in the Font dialog
box of any Microsoft Text editor like FrontPage, there are many check boxes under the Effects
section such as that shown in the diagram below. The user can choose underline, subscript,
small caps, superscript, blink and etc. In Visual Basic 2012, you may create a shopping cart
where the user can click on check boxes that correspond to the items they intend to buy, and
the total payment can be computed at the same time as shown in Example 17.1.

Casilla de verificación es un control muy útil en Visual Basic 2012 Permite al usuario
seleccionar uno o más elementos marcando la casilla de verificación o casillas de verificación
de que se trate. Por ejemplo, en el cuadro de diálogo Fuente de cualquier editor de texto de
Microsoft como FrontPage, hay muchas casillas de verificación en la sección de efectos, tales
como la que se muestra en el siguiente diagrama. El usuario puede elegir subrayado,
subíndice, versalitas, superíndice, parpadeo, etc En Visual Basic 2012, puede crear un carrito
de compras en el que el usuario puede hacer clic en las casillas de verificación
correspondientes a los elementos que tengan la intención de comprar, y el pago total se puede
calcular al mismo tiempo, como se muestra en el Ejemplo 17.1.
Example 17.1:Shopping Cart Ejemplo 17.1: Compras

The program code for shopping cart is as follows: El código de programa para cesta de la
compra es el siguiente:

Private Sub BtnCalculate_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles BtnCalculate.Click

Const LX As Integer = 100

Const BN As Integer = 500

Const SD As Integer = 200

Const HD As Integer = 80

Const HM As Integer = 300

Const AM As Integer = 150

Dim sum As Integer

If CheckBox1.Checked = True Then


sum += LX
End If

If CheckBox2.Checked = True Then


sum += BN
End If
If CheckBox3.Checked = True Then
sum += SD
End If
If CheckBox4.Checked = True Then
sum += HD
End If

If CheckBox5.Checked = True Then


sum += HM
End If

If CheckBox6.Checked = True Then


sum += AM
End If
Label5.Text = sum.ToString(“c”)

Here is another example

Example 17.2
He aquí otro ejemplo

Ejemplo 17.2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Const large As Integer = 10.0
Const medium As Integer = 8
Const small As Integer = 5
Dim sum As Integer

If CheckBox1.Checked = True Then


sum += large
End If

If CheckBox2.Checked = True Then


sum += medium
End If

If CheckBox3.Checked = True Then


sum += small
End If
Label5.Text = sum.ToString(“c”)

Example 17.3

In this example, the user can enter text into a text box and format the font using the three
check boxes that represent bold, italic and underline.
Ejemplo 17.3

En este ejemplo, el usuario puede introducir texto en un cuadro de texto y formato a la fuente
usando las tres casillas que representan en negrita, cursiva y subrayado.

The code is as follow: El código es el siguiente:

Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Bold)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Bold)

End If
End Sub

Private Sub CheckBox2_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CheckBox2.CheckedChanged
If CheckBox2.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Italic)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Italic)

End If
End Sub

Private Sub CheckBox3_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CheckBox3.CheckedChanged
If CheckBox2.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Underline)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Underline)
End If
End Sub

* The above program uses the CheckedChanged event to respond to the user selection by
checking a particular check box, it is similar to the click event. The statement

TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Italic)

will retain the original font type but change it to italic font style.

TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Italic)

will also retain the original font type but change it to regular font style. (The other statements
employ the same logic)

* El programa anterior utiliza el evento CheckedChanged para responder a la selección del


usuario al marcar la casilla de verificación particular, es similar al evento clic. la declaración

TextBox1.Font = Nuevo Fuente (TextBox1.Font, TextBox1.Font.Style O FontStyle.Italic)

conservará el tipo de fuente original, pero cambiarlo a estilo de fuente cursiva.

TextBox1.Font = Nuevo Fuente (TextBox1.Font, TextBox1.Font.Style Y No FontStyle.Italic)

También mantendrá el tipo de fuente original, pero cambiar a caracteres normales. (Los otros
estados emplean la misma lógica)
* Instead of “General date”, you can also use the abbreviated format “G” , i.e. Format (Now,
“G”). And for “Long Time”, you can use the abbreviated format “T”. As for “Short Time”, you
may use the abbreviated format “t”

* En lugar de "fecha general", también se puede utilizar el formato abreviado "G", es decir,
Formato (Ahora, "G"). Y para "Long Time", puede utilizar el formato abreviado de "T". En
cuanto a "Short Time", usted puede utilizar el formato abreviado "t"

[Lesson 16] <<[CONTENTS] >> [Lesson 18]


Visual Basic 2012 Lesson 18 – Using Radio Button
Visual Basic 2012 Lección 18 - El uso del botón de radio
[Lesson 17] << [CONTENTS] >> [Lesson 19]

Radio button is also a very useful control in Visual Basic 2012. It operates differently from the
check boxes. While the check boxes work independently and allow the user to select one or
more items , radio buttons are mutually exclusive, which means the user can only choose one
item only out of a number of choices. Here is an example which allows the user to select one
color only.

Botón de radio es también un control muy útil en Visual Basic 2012. funciona de forma
diferente a partir de las casillas de verificación. Mientras que las casillas de verificación
trabajar de forma independiente y permiten al usuario seleccionar uno o más elementos,
botones de radio son mutuamente excluyentes, lo que significa que el usuario sólo puede
elegir una opción sólo de una serie de opciones. He aquí un ejemplo que permite al usuario
seleccionar un solo color.

The Code: El código

Dim strColor As String

Private Sub RadioButton8_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioButton8.CheckedChanged
strColor = “Red”
End Sub

Private Sub RadioButton7_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioButton7.CheckedChanged
strColor = “Green”
End Sub

Private Sub RadioYellow_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioYellow.CheckedChanged
strColor = “Yellow”
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Label2.Text = strColor
End Sub

Although the user may only select one item at a time, he may make more than one selection if
those items belong to different categories. For example, the user wishes to choose T-shirt size
and color, he needs to select one color and one size, which means one selection in each
category. This is easily achieved in Visual Basic 2012 by using the Groupbox control under the
containers categories.

Under the Visual Basic 2012 IDE, after inserting the Groupbox from the tool box into the form,
you can proceed to insert the radio buttons into the Groupbox. Only the radio buttons inside the
Groupbox are mutually exclusive, they are not mutually exclusive with the radio buttons outside
the Groupbox. In Example 18.2, the user can select one color and one size of the T-shirt.

Example 18.2

Aunque el usuario sólo puede seleccionar un elemento a la vez, se puede hacer más de una
selección, si esos elementos pertenecen a diferentes categorías. Por ejemplo, el usuario
desea elegir la camiseta tamaño y color, que necesita para seleccionar un color y una talla, lo
que significa una selección en cada categoría. Esto se consigue fácilmente en Visual Basic
2012 utilizando el control Cuadro de grupo en las categorías contenedores.

Bajo el básico 2012 IDE Visual, después de insertar el Cuadro de grupo de la caja de
herramientas en la forma, se puede proceder a insertar los botones de radio en el Cuadro de
grupo. Sólo los botones de opción dentro del Cuadro de grupo son mutuamente excluyentes,
no son mutuamente excluyentes con los botones de radio fuera del Cuadro de grupo. En el
Ejemplo 18.2, el usuario puede seleccionar un color y una talla de la camiseta.
The code: El código

Dim strColor As String


Dim strSize As String

Private Sub RadioButton8_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioButton8.CheckedChanged
strColor = “Red”
End Sub

Private Sub RadioButton7_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioButton7.CheckedChanged
strColor = “Green”
End Sub

Private Sub RadioYellow_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioYellow.CheckedChanged
strColor = “Yellow”
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Label2.Text = strColor
Label4.Text = strSize
End Sub

Private Sub RadioXL_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioXL.CheckedChanged
strSize = “XL”
End Sub
Private Sub RadioL_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RadioL.CheckedChanged
strSize = “L”
End Sub

Private Sub RadioM_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioM.CheckedChanged
strSize = “M”
End Sub

Private Sub RadioS_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioS.CheckedChanged
strSize = “S”
End Sub

[Lesson 17] << [CONTENTS] >> [Lesson 19]


Visual Basic 2012 Lesson 19 – Creating A Simple Web Browser
Visual Basic 2012 Lección 19 - Creación de un simple navegador
web

[Lesson 18] << [CONTENTS] >> [Lesson 20]

Basically everyone likes to navigate the Internet using commercially produced web browsers
such the Internet Explorer produced by Microsoft or those open source browsers designed by
the experts such FireFox , Opera and the latest Chrome created by Google. However, isn’t it
cool that if you can create your very own web browser that you can customize to your own
taste ? Yes, you can do that in Visual Basic 2012, and pretty easy too. In this chapter, I will
show you how to create a simple web browser and get it running in a few minutes.

Básicamente todo el mundo le gusta navegar por Internet utilizando navegadores web
producidos comercialmente como el Internet Explorer producida por Microsoft o los
navegadores de código abierto diseñado por los expertos como Firefox, Opera y el más
reciente de Chrome creado por Google. Sin embargo, no es que se enfríe que si usted puede
crear su propio navegador web que se puede personalizar a su gusto? Sí, usted puede
hacerlo en Visual Basic 2012, y bastante fácil también. En este capítulo, te voy a mostrar
cómo crear un simple navegador web y ponerlo en marcha en pocos minutos.

First of all, start a new project in Visual Basic 2012 and name it with any name you like. Here I am just

using the name Web Browser. Change the name of Form1 to MyWebBrowser and the text property to

Web Browser and set its size property to 640,480. Next, you need to add an engine so that your web

browser can connect to the Internet, and this very engine is the WebBrowser control, located on the

Toolbox on the left side, set the size property to 600,400. Next, drag a text box and place it at the top
of the WebBrowser control, this will be the address bar where the user can enter the URL. Lastly,

place a command button beside the text box and label it as Go and change its name to Go as well.
The design interface is shown below:

En primer lugar, iniciar un nuevo proyecto en Visual Basic 2012 y el nombre con el nombre que desee.

Aquí sólo estoy usando el navegador Web nombre. Cambie el nombre de Form1 a MyWebBrowser y

la propiedad de texto a Navegador Web y establezca su propiedad tamaño a 640.480. Después, usted

necesita para añadir un motor para que su navegador puede conectarse a Internet, y este mismo

motor es el control WebBrowser, se encuentra en la caja de herramientas en la parte izquierda,


establece la propiedad tamaño a 600.400. A continuación, arrastre un cuadro de texto y colóquelo en
la parte superior del control WebBrowser, esta será la barra de direcciones, donde el usuario puede

introducir la URL. Por último, coloque un botón de comando al lado del cuadro de texto y etiquetarlo
como Go y cambiar su nombre para ir también. El diseño de la interfaz se muestra a continuación:

The code for the web browser is surprisingly simple, it is only a single line code! Double click
on the Go button and key in the following code:

El código para el navegador web es sorprendentemente simple, sólo es una sola línea de
código! Haga doble clic en el botón Ir y escriba el siguiente código:

Public Class Form1

Private Sub Go_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
MyWebBrowser.Navigate(TextBox1.Text)

End Sub

End Class

Now run the the program , type in any URL and click the Go button. You will be able to browse
any web page you want.

Figure 19.2: The Runtime Interface

Ahora ejecuta el programa, escriba cualquier URL y haga clic en el botón Go. Usted será
capaz de navegar por cualquier página web que desee.

Figura 19.2: La interfaz en tiempo de ejecución


Visual Basic 2012 Lesson 20– Errors Handling
Visual Basic 2012Lección 20- Gestión de errores
[Lesson 19] << [CONTENTS] >> [Lesson 21]

20.1 Introduction to Error Handling in Visual basic 2012

Error handling is an essential procedure in Visual Basic 2012 programming because it helps
make a program error-free. Error-free code not only enables the programs to run smoothly and
efficiently, it can also prevent all sorts of problems from happening like program crashes or
system hangs.

Errors often occur due to incorrect input from the user. For example, the user might make the
mistake of attempting to enter text (string) to a box that is designed to handle only numeric
values such as the weight of a person, the computer will not be able to perform arithmetic
calculation for text therefore will create an error. These errors are known as synchronous
errors.

Therefore a good programmer should be more alert to the parts of program that could trigger
errors and should write errors handling code to help the user in managing the errors. Writing
errors handling code is a good practice for Visual Basic 2012 programmers, so do not try to
finish a program fast by omitting the errors handling code. However, there should not be too
many errors handling code in the program as it create problems for the programmer to
maintain and troubleshoot the program later.

Visual Basic 2012 has improved a lot in its built-in errors handling capabilities compared to
Visual Basic 6. For example, when the user attempts to divide a number by zero, Vb2012 will
not return an error message but gives the ‘infinity’ as the answer (although this is
mathematically incorrect, because it should be undefined)

20.1 Introducción a la gestión de errores en Visual Basic 2012

El manejo de errores es un procedimiento esencial en la programación de Visual Basic 2012,


ya que ayuda a hacer sin errores de un programa. Código libre de errores, no sólo permite a
los programas para funcionar sin problemas y eficientemente, sino que también puede
prevenir todo tipo de problemas suceda como errores en el programa o sistema se cuelga.

Errores menudo se producen debido a la entrada incorrecta del usuario. Por ejemplo, el
usuario podría cometer el error de tratar de introducir texto (string) a una caja que está
diseñado para manejar sólo valores numéricos tales como el peso de una persona, el equipo
no será capaz de realizar cálculo aritmético para el texto, por lo tanto lo hará crear un error.
Estos errores se conocen como errores síncronos.

Por lo tanto un buen programador debe estar más alerta a las partes del programa que
podrían provocar errores y debe escribir los errores de manipulación de código para ayudar al
usuario en el manejo de los errores. Escribir los errores de manipulación de código es una
buena práctica para los programadores de Visual Basic 2012, así que no trate de terminar un
programa rápido al omitir los errores de manejo de código. Sin embargo, no debería haber
demasiados errores de manipulación de código en el programa, ya que crea problemas para el
programador para mantener y solucionar problemas del programa más adelante.

Visual Basic 2012 ha mejorado mucho en su base de errores capacidades de manejo en


comparación con Visual Basic 6 Por ejemplo, cuando el usuario intenta dividir un número por
cero, Vb2012 no devolverá un mensaje de error, pero da el 'infinito' como el contestar (aunque
esto es matemáticamente incorrecta, ya que debe ser definido)

20.2 Using On Error GoTo Syntax

Visual Basic 2012 still supports the VB6 errors handling syntax, that is the On Error GoTo
program_label structure. Although it has a more advanced error handling method, we shall
deal with that later.We shall now learn how to write errors handling code in Visual Basic 2012.
The syntax for errors handling is

On Error GoTo program_label

where program_label is the section of code that is designed by the programmer to handle the
error committed by the user. Once an error is detected, the program will jump to the
program_label section for error handling.

20.2 Uso de los errores de sintaxis GoTo

Visual Basic 2012 todavía admite los errores VB6 manejo de la sintaxis, que es el On Error
GoTo estructura program_label. Aunque tiene un método más avanzado de manejo de
errores, nos ocuparemos de que later.We ahora deberá aprender a escribir los errores de
manipulación de código en Visual Basic 2012 La sintaxis de los errores de manipulación es

On Error GoTo program_label

donde program_label es la sección del código que está diseñado por el programador para
gestionar el error cometido por el usuario. Una vez que se detecta un error, el programa
saltará a la sección program_label para el tratamiento de errores.

Example 20.1: Division by Zero

In this example, we will deal with the error of entering non-numeric data into the textboxes that
suppose to hold numeric values. The program_label here is error_hanldler. when the user
enter a non-numeric values into the textboxes, the error message will display the text”One of
the entries is not a number! Try again!”. If no error occurs, it will display the correct answer. Try
it out yourself.

Ejemplo 20.1: División por cero

En este ejemplo, vamos a tratar con el error de introducir datos no numéricos en los cuadros
de texto que suponen para contener valores numéricos. El program_label aquí es
error_hanldler. cuando el usuario introduce un valor no numérico en los cuadros de texto, el
mensaje de error se mostrará el texto "Una de las entradas no es un número! Inténtalo de
nuevo! ". Si no se produce ningún error, se mostrará la respuesta correcta. Pruébelo usted
mismo.
The Code El código

Public Class Form1

Private Sub CmdCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles CmdCalculate.Click

Lbl_ErrorMsg.Visible = False

Dim firstNum, secondNum As Double

On Error GoTo error_handler

firstNum = Txt_FirstNumber.Text

secondNum = Txt_SecondNumber.Text

Lbl_Answer.Text = firstNum / secondNum

Exit Sub ‘To prevent error handling even the inputs are valid

error_handler:

Lbl_Answer.Text = “Error”

Lbl_ErrorMsg.Visible = True

Lbl_ErrorMsg.Text = ” One of the entries is not a number! Try again!”

End Sub

End Class
The Output la salida

20.3 Errors Handling using Try…..Catch….End Try Structure

VB2012 has adopted a new approach in handling errors, or rather exceptions handling. It is
supposed to be more efficient than the old On Error Goto method, where it can handles various
types of errors within the Try…Catch…End Try structure.

The structure looks like this

20.3 Errores de manipulación utilizando Try ... ..Catch ... .End Trate Estructura

VB2012 ha adoptado un nuevo enfoque en el manejo de errores, o más bien el manejo de


excepciones. Se supone que es más eficiente que el viejo método Goto On Error, donde
puede maneja varios tipos de errores dentro de la estructura Try ... Catch ... Try End.

La estructura se parece a esto

Try

statements

Catch exception_variable as Exception

statements to deal with exceptions

End Try
Example 20.2

This is a modification of Example 20.1. Instead of using On Error GoTo method, we use the
Try…Catch…End Try method. In this example, the Catch statement will catch the exception
when the user enters a non-numeric data and return the error message. If there is no
exception, there will not any action from the Catch statement and the program returns the
correct answer.

The code

Ejemplo 20.2

Esta es una modificación del Ejemplo 20.1. En lugar de utilizar On Error GoTo método, se
utiliza el método Try Try ... Catch ... End. En este ejemplo, la instrucción Catch se captura la
excepción cuando el usuario introduce un conjunto de datos no numéricos y devolver el
mensaje de error. Si no hay excepción, no habrá ninguna acción de la declaración de capturas
y el programa devuelve la respuesta correcta.

el código

Public Class Form1

Private Sub CmdCalculate_Click(ByVal sender As System.Object, ByVal eAs


System.EventArgs) Handles CmdCalculate.Click

Lbl_ErrorMsg.Visible = False

Dim firstNum, secondNum, answer As Double

Try

firstNum = Txt_FirstNumber.Text

secondNum = Txt_SecondNumber.Text

answer = firstNum / secondNum

Lbl_Answer.Text = answer

Catch ex As Exception

Lbl_Answer.Text = “Error”

Lbl_ErrorMsg.Visible = True

Lbl_ErrorMsg.Text = ” One of the entries is not a number! Try again!”

End Try

End Sub
End Class

The output la salida

[Lesson 19] << [CONTENTS] >> [Lesson 21]


Visual Basic 2012 Lesson 21- Managing Graphics 1-Basic Concepts

Visual Basic 2012 Lección 21- Gráficos Gestión Conceptos básicos


1-
[Lesson 20] << [CONTENTS] >> [Lesson 22]

21.1 Introduction

Managing graphics is easy in earlier versions of Visual Basic as they have built-in drawing
tools. For example, In Visual Basic 6, the drawing tools are included in the toolbox where the
programmer just need to drag the shape controls into the form to create rectangle, square,
ellipse,circle and more. However, its simplicity has the shortcomings, you don’t have much
choices in creating customized drawings.

21.1 Introducción

La gestión de gráficos es fácil en las versiones anteriores de Visual Basic, ya que han
incorporado en las herramientas de dibujo. Por ejemplo, en Visual Basic 6, las herramientas
de dibujo se incluyen en la caja de herramientas donde el programador sólo tiene que arrastrar
los controles de la forma en la forma de crear rectángulo, cuadrado, elipse, círculo y más. Sin
embargo, su simplicidad tiene las deficiencias, no tienes muchas opciones en la creación de
dibujos personalizados.

Since Visual Basic evolved into a fully OOP language under the VB.net framework, shape controls are no longer available. Now the programmer needs to

write code to create various shapes and drawings. Even though the learning curve is steeper, the programmer can write powerful code to create all kinds

of graphics. You can even design your own controls

Desde Visual Basic evolucionó a un lenguaje plenamente programación orientada a objetos en el marco VB.net, forma a los controles ya no están

disponibles. Ahora el programador necesita escribir código para crear diferentes formas y dibujos. A pesar de que la curva de aprendizaje es empinada,

el programador puede escribir poderoso código para crear todo tipo de gráficos. Usted puede incluso diseñar sus propios controles

Visual Basic 2012 offers various graphics capabilities that enable programmers to write code that can draw all kinds of shapes and
even fonts. In this lesson,you will learn how to write code to draw lines and shapes on the Visual Basic 2012 interface.

Visual Basic 2012 ofrece varias capacidades gráficas que permiten a los programadores a escribir código que puede dibujar todo tipo
de formas e incluso fuentes. En esta lección, usted aprenderá cómo escribir código para dibujar líneas y formas en la interfaz de
Visual Basic 2012.
21.1 Creating the Graphics Object

Before you can draw anything on a form, you need to create the Graphics object in Visual
Basic 2012. A graphics object is created using a CreateGraphics() method. You can create a
graphics object that draw to the form itself or a control. For example, if you wish to draw to the
form, you can use the following statement:

21.1 Creación de un objeto de Gráficos

Antes de que pueda dibujar cualquier cosa en un formulario, es necesario crear el objeto
Graphics en Básico 2012. Un objeto gráfico visual se crea usando un método ()
CreateGraphics. Puede crear un objeto gráfico que dibuja a la forma en sí o un control. Por
ejemplo, si desea llamar a la forma, puede utilizar la siguiente declaración:

Dim myGraphics As Graphics =me.CreateGraphics

*Always use Dim to define the object. Using me instead of Form1 because it is not allow in
Visual Basic 2012.

Or if you want the graphics object to draw to a picturebox, you can write the following
statement:

* Siempre use Dim para definir el objeto. El uso de mí en lugar de Form1 ya que no se permite
en Visual Basic 2012.

O si usted quiere el objeto gráfico para dibujar a un PictureBox, puede escribir la siguiente
declaración:

Dim myGraphics As Graphics = PictureBox1.CreateGraphics

You can also use the textbox as a drawing surface, the statement is:

También puede utilizar el cuadro de texto como superficie de dibujo, la declaración es:

Dim myGraphics As Graphics = TextBox1.CreateGraphics

The Graphics object that is created does not draw anything on the screen until you call the
methods of the Graphics object. In addition,you need to create the Pen object as the drawing
tool. We will examine the code that can create a pen in the following section.

El objeto Graphics que se crea no saca nada en la pantalla hasta que llame a los métodos del
objeto Graphics. Además, es necesario crear el objeto Pen como la herramienta de dibujo.
Vamos a examinar el código que puede crear una pluma en la siguiente sección.
21.2 Creating a Pen

A Pen can be created using the following code:

21.2 Creación de una pluma

Una pluma puede ser creado usando el siguiente código:

myPen = New Pen(Brushes.DarkMagenta, 10)

where myPen is a Pen variable. You can use any variable name instead of myPen. The first
argument of the pen object define the color of the drawing line and the second argument define
the width of the drawing line.

You can also create a Pen using the following statement:

donde myPen es una variable Pen. Puede utilizar cualquier nombre de variable en lugar de
myPen. El primer argumento del objeto pluma definir el color de la línea de dibujo y el segundo
argumento define el ancho de la línea de dibujo.

También puede crear un Pen con la siguiente declaración:

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Where the first argument define the color(here is blue, you can change that to red or whatever
color you want) and the second argument is the width of the drawing line.

Having created the Graphics and the Pen objects, you are now ready to draw graphics on the
screen which we will show you in the following section.s

Donde el primer argumento define el color (en este caso es azul, usted puede cambiar eso a
rojo o lo que quieras) y el segundo argumento es el ancho de la línea de dibujo.

Después de haber creado los gráficos y los objetos Pen, que ahora está listo para dibujar
gráficos en la pantalla que le mostramos en las siguientes secciones

21.3 Drawing a Line

In this section, we will show you how to draw a straight line on the Form.

First of all, launch Visual basic 2012 Express. In the start up page, drag a button into the form.
Double click on the button and key in the following code.

21.3 Dibujo de una recta

En esta sección, le mostraremos cómo dibujar una línea recta en el formulario.


En primer lugar, iniciar Visual basic 2012 Express. En la página de inicio, arrastre un botón en
el formulario. Haga doble clic en el botón e introduzca el siguiente código.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim myGraphics As Graphics = me.CreateGraphics

Dim myPen As Pen

myPen = New Pen(Brushes.DarkMagenta, 10)

myGraphics.DrawLine(myPen, 10, 10, 100, 10)

End Sub

The second created the Graphics object and the third and fourth line create the Pen object.
The fifth draw a line on the Form using the DrawLine method. The first argument use the Pen
object created by you, the second argument and the third arguments define the coordinate the
starting point of the line, the fourth and the last arguments define the ending coordinate of the
line. The general syntax of the Drawline argument is

La segunda crea el objeto Graphics y la tercera y cuarta línea de crear el objeto Pen. El quinto
dibujar una línea en el formulario utilizando el método DrawLine. El primer argumento de
utilizar el objeto Pen creado por usted, el segundo argumento y el tercer argumento a definir el
punto inicial de la línea de coordenadas, la cuarta y los últimos argumentos definen el fin de
coordinar de la línea. La sintaxis general del argumento es drawLine

object.DrawLine(Pen, x1, y1, x2, y2)


The output of the program is shown below:

La salida del programa se muestra a continuación:

[Lesson 20] << [CONTENTS] >> [Lesson 22]


Visual Basic 2012 Lesson 22– Managing Graphics -Drawing Rectangle

Visual Basic 2012 Lección 22-Manejo de Gráficos-Dibujo Rectangle


[Lesson 21] << [CONTENTS] >> [Lesson 23]

We have learned how to create the Graphics and the Pen objects to draw straight lines in
Visual Basic 2012 in the previous lesson. Now we shall learn how to draw various shapes such
as rectangle, square,ellipse and circle.

Hemos aprendido cómo crear los gráficos y la pluma objetos para dibujar líneas rectas en
Visual Basic 2012 en la lección anterior. Ahora vamos a aprender a dibujar diferentes formas,
tales como rectángulo, cuadrado, elipse y el círculo.

22.1 Creating Rectangles

To draw a rectangle on the screen in Visual Basic 2012, there are two ways:

(i)The first way is to draw a rectangle directly using the DrawRectangle method by specifying
its upper-left corner’s coordinate and it width and height. You also need to create a Graphics
and a Pen object to handle the actual drawing. The method to draw the rectangle is
DrawRectangle .

The syntax is:

22.1 Creación de rectángulos

Para dibujar un rectángulo en la pantalla en Visual Basic 2012, hay dos maneras:

(i) La primera manera es dibujar un rectángulo directamente utilizando el método


DrawRectangle especificando coordenadas de su esquina superior izquierda y anchura y
altura. También es necesario crear una gráfica y un objeto Pen para manejar el dibujo actual.
El método para dibujar el rectángulo es DrawRectangle.

La sintaxis es la siguiente:

myGrapphics.DrawRectangle(myPen, X, Y, width, height)

Where myGraphics is the variable name of the Graphics object and myPen is the variable
name of the Pen object created by you. You can use any valid and meaningful variable names.
X, Y is the coordinate of the upper left corner of the rectangle while width and height are self-
explanatory, i.e, the width and height of the rectangle.

Dónde myGraphics es el nombre de la variable del objeto Graphics y myPen es el nombre de


la variable del objeto Pen creado por usted. Puede utilizar cualquier nombre de variable
válidos y significativos. X, Y es la coordenada de la esquina superior izquierda del rectángulo
mientras que la anchura y altura son autoexplicativo, es decir, la anchura y la altura del
rectángulo.
The sample code is shown below:

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawRectangle(myPen, 0, 0, 100, 50)

(ii) The second way is to create a rectangle object first and then draw this triangle using the
DrawRectangle method. The syntax is as shown below:

(ii) La segunda manera es crear un objeto rectangular primero y luego dibujar este triángulo
usando el método DrawRectangle. La sintaxis es como se muestra a continuación:

myGraphics.DrawRectangle(myPen,myRectangle) where myRectangle is the rectangle object


created by you, the user.

The code to create a rectangtle object is as shown below:

El código para crear un objeto rectangtle es como se muestra a continuación:

Dim myRectangle As New Rectangle

myRect.X = 10

myRect.Y = 10

myRect.Width = 100

myRect.Height = 50

You can also create a rectangle object using a one-line code as follows:

También puede crear un objeto de rectángulo con un código de una línea de la siguiente
manera:

Dim myRectangle As New Rectangle(X,Y,width, height)

and the code to draw the above rectange is

y el código para dibujar la rectange anterior es

myGraphics.DrawRectangle(myPen, myRectangle)

The sample code is shown below:


A continuación se muestra el código de ejemplo:

22.2 Customizing Line Style of the Pen Object

The shape we draw so far are drawn with solid line, we can actually customize the line style of
the Pen object so that we have dotted line, line consisting of dashes and more. For example,
the syntax to draw with dotted line is shown below:

22.2 Personalización de Estilo de línea del objeto Pen

La forma nos acercamos hasta ahora se dibujan con línea continua, en realidad podemos
personalizar el estilo de línea del objeto Pen para que hemos salpicado línea, la línea que
consiste en guiones y más. Por ejemplo, a continuación se muestra la sintaxis para llamar a la
línea de puntos:

myPen.DashStyle=Drawing.Drawing2D.DashStyle.Dot

Where the last argument Dot specifies a particular line DashStyle value, a line that makes up
of dots here. The following code draws a rectangle with red dotted line.

Si el último argumento Dot especifica un valor DashStyle línea en particular, una línea que
compone de puntos aquí. El siguiente código dibuja un rectángulo con línea punteada roja.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Red, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myPen.DashStyle = Drawing.Drawing2D.DashStyle.Dot

myGraphics.DrawRectangle(myPen, 10, 10, 100, 50)

End Sub

The output image is shown below:


The possible values of the line DashStyle of the Pen are listed in the table below:

Los valores posibles de la DashStyle línea de la pluma se enumeran en la tabla siguiente:

[Lesson 21] << [CONTENTS] >> [Lesson 23]


Visual Basic 2012 Lesson 23– Managing Graphics -Drawing Ellipse
and Circle
Visual Basic 2012 Lección 23 al Gerente Gráficos -Dibujo Elipse y
círculo
[Lesson 22] << [CONTENTS] >> [Lesson 24]

We have learned how to draw rectangles with various line styles in Visual Basic 2012 in the
previous lesson. Now we shall learn how to draw ellipse and circle.

Hemos aprendido cómo dibujar rectángulos con diferentes estilos de línea en Visual Basic
2012 en la lección anterior. Ahora vamos a aprender a dibujar elipse y el círculo.

23.1 Drawing Ellipse

First of all we need to understand the principle behind drawing an ellipse in Visual Basic 2012.
The basic structure of most shapes is a rectangle, ellipse is no exception. Ellipse is an oval
shape that is bounded by a rectangle, as shown below:

23.1 Dibujo Elipse

En primer lugar tenemos que entender el principio detrás de dibujar una elipse en Visual Basic
2012 La estructura básica de la mayoría de las formas es un rectángulo, elipse no es una
excepción. Elipse es una forma oval que está delimitado por un rectángulo, como se muestra a
continuación:

Therefore, we need to create a Rectangle object before we can draw an ellipse. This
rectangle serves as a bounding rectangle for the ellipse. We still need to use the
DrawEllipse method to finish the job. On the other hand, we can also draw an ellipse
with the DrawEllipse method without first creating a rectangle. We shall show you
both ways.

Por lo tanto, tenemos que crear un objeto Rectangle antes de que podamos dibujar
una elipse. Este rectángulo sirve como un rectángulo de delimitación de la elipse.
Todavía tenemos que utilizar el método drawEllipse para terminar el trabajo. Por otro
lado, también podemos dibujar una elipse con el método drawEllipse sin crear
primero un rectángulo. Le mostraremos dos formas.
In the first method, let say you have created a rectangle object known as myRectangle and a
pen object as myPen, then you can draw an ellipse using the following statement:

En el primer método, Digamos que usted ha creado un objeto rectangular conocida como
myRectangle y un objeto lápiz como myPen, a continuación, se puede dibujar una elipse con
la siguiente declaración:

myGraphics.DrawEllipse(myPen, myRectangle)

* Assume you have also already created the Graphics object myGraphics.

The following is an example of the full code:

Example 23.1(a)

* Supongamos que haya también ya creado el objeto Graphics myGraphics.

El siguiente es un ejemplo del código completo:

Ejemplo 23.1 (a)

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myRectangle As New Rectangle

myRectangle.X = 10

myRectangle.Y = 10

myRectangle.Width = 200

myRectangle.Height = 100

myGraphics.DrawEllipse(myPen, myRectangle)

The output image is shown in the following diagram:

La imagen de salida se muestra en el siguiente diagrama:


The second method is using the DrawEllipse method without creating a rectangle object.
Offcourse you still have to create the Graphics and the Pen objects. The syntax is:

El segundo método utiliza el método drawEllipse sin crear un objeto de rectángulo. Offcourse
usted todavía tiene que crear los gráficos y los objetos Pen. La sintaxis es la siguiente:

myGraphics.DrawEllipse(myPen, X,Y,Width, Height)

Where (X,Y) are the coordinates of the upper left corner of the bounding rectangle, width is the
width of the ellipse and height is the height of the ellipse.

Donde (X, Y) son las coordenadas de la esquina superior izquierda del rectángulo delimitador,
ancho es el ancho de la elipse y la altura es la altura de la elipse.

The following is an example of the full code:

El siguiente es un ejemplo del código completo:

Example 23.1(b)

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawEllipse(myPen, 10, 10, 200, 100)

23.2 Drawing a Circle


After you have learned how to draw an ellipse, drawing a circle becomes very simple. We use
exactly the same methods used in the preceding section but modify the width and height so
that they are of the same values.

The following examples draw the same circle.

Example 23.2(a)

Después de haber aprendido a dibujar una elipse, dibujando un círculo se hace muy simple.
Utilizamos exactamente los mismos métodos utilizados en la sección anterior, pero modificar
la anchura y altura de modo que sean de los mismos valores.

Los siguientes ejemplos se basan en el mismo círculo.

Ejemplo 23.2 (a)

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myRectangle As New Rectangle

myRectangle.X = 10

myRectangle.Y = 10

myRectangle.Width = 100

myRectangle.Height = 100

myGraphics.DrawEllipse(myPen, myRectangle)

Example 23.2(b)

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawEllipse(myPen, 10, 10, 100, 100)

The output image is show below:


[Lesson 22] << [CONTENTS] >> [Lesson 24]
Visual Basic 2012 Lesson 24– Managing Graphics -Drawing Text

Visual Basic 2012 Lección 24 Managing Gráficos -Dibujo texto


[Lesson 23] << [CONTENTS] >> [Lesson 25]

We have learned how to draw rectangle, ellipse and circle in visual basic 2012 in the preceding
chapters, now let’s learn how to draw text on the screen. Yes, instead of using the Print
command, you can also draw text on the screen.

Hemos aprendido cómo dibujar rectángulo, elipse y el círculo en visual basic 2012 en los
capítulos anteriores, ahora vamos a aprender a dibujar texto en la pantalla. Sí, en lugar de
utilizar el comando de impresión, también puede dibujar texto en la pantalla.

24.1 Drawing Text

In order to draw text on the screen, we can use the DrawString method. The format is as
follows:

myGraphics.DrawString(myText, myFont, mybrush, X , Y)

Where myGraphics is the Graphics object, myText is the text you wish to display on the
screen, myFont is the font object created by you, myBrush is the brush style created by you
and X, Y are the coordinates of upper left corner of the Text.

You can create the Font object in visual basic 2012 using the following statement:

myFont = New System.Drawing.Font(“Verdana”, 20)

Where the first argument of the font is the font typeface, and the second argument is the font
size. You can add a third argument as font style, either bold, italic, underline. Here are the
examples:

24.1 Dibujo texto

Para dibujar texto en la pantalla, podemos utilizar el método DrawString. El formato es el


siguiente:

myGraphics.DrawString (myText, myFont, MyBrush, X, Y)

Dónde myGraphics se oponen los gráficos, myText es el texto que desea mostrar en la
pantalla, myFont es el objeto de fuente creado por usted, MyBrush es el estilo de pincel
creado por usted y X, Y son las coordenadas de la esquina superior izquierda del texto .

Usted puede crear el objeto de fuente en visual basic 2012 mediante la siguiente declaración:

myFont = Nuevo System.Drawing.Font ("Verdana", 20)


Donde el primer argumento de la fuente es el tipo de letra, y el segundo argumento es el
tamaño de la fuente. Usted puede agregar un tercer argumento como estilo de fuente, ya sea
negrita, cursiva, subrayado. Aquí están los ejemplos:

myFont = New System.Drawing.Font(“Verdana”, 20, FontStyle.Bold)myFont = New

System.Drawing.Font(“Verdana”, 20, FontStyle.Underline)

myFont = New System.Drawing.Font(“Verdana”, 20, FontStyle.Italic)

myFont = New System.Drawing.Font(“Verdana”, 20, FontStyle.Regular)

To create your Brush object, you can use the following statement:

Dim myBrush As Brush

myBrush = New Drawing.SolidBrush(Color.BrushColor)

Besides the seven colors, some of the common Brush Colors are AliceBlue, AquaMarine
Beige, DarkMagenta, DrarkOliveGreen, SkyBlue and more. You don’t have to remember the
names of all the colors, the intelliSense will let you browse through the colors in a drop-down
menu once you type the dot after the word Color.

Now we shall proceed to draw the font using the sample code below:

Además de los siete colores, algunas de las Cepillo Colores comunes son Aliceblue,
AquaMarine Beige, DarkMagenta, DrarkOliveGreen, SkyBlue y más. Usted no tiene que
recordar los nombres de todos los colores, el IntelliSense le permitirá navegar a través de los
colores en un menú desplegable, una vez que escribe el punto después de la palabra en color.

Ahora procederemos a dibujar el tipo de letra utilizando el código de ejemplo siguiente:

Example 24.1

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myFont As Font

Dim myBrush As Brush

myBrush = New Drawing.SolidBrush(Color.DarkOrchid)

myFont = New System.Drawing.Font(“Verdana”, 20, FontStyle.Underline)

myGraphics.DrawString(“Visual Basic 2012″, myFont, myBrush, 10, 10)

Run the program above and you can see the following output:
Ejecute el programa anterior y se puede ver el siguiente resultado:

The preceding can be modified if you don’t want to create the Font and the Brush objects. You
can use the font of an existing object such as the Form and the System Colors. Replace the
last line in the preceding example with this line(you need to delete the lines that create the
Brush and the Font objects as well)

Lo anterior puede ser modificada si no desea crear la fuente y los objetos Brush. Usted puede
utilizar la fuente de un objeto existente, como la forma y los colores del sistema. Vuelva a
colocar la última línea en el ejemplo anterior con esta línea (tendrá que borrar las líneas que
crean el cepillo y objetos de la fuente también)

myGraphics.DrawString(“Visual Basic 2012″, me.Font, System.Drawing.Brushes.DarkOrchid,


10, 10)

You can also add a InputBox which let the user enter his or her message then display the
message on the screen.

This is shown in Example 24.2

También puede agregar un InputBox que dejar que el usuario introduzca su mensaje a
continuación, mostrar el mensaje en la pantalla.

Esto se muestra en el Ejemplo 24.2

Example 24.2

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myFont As Font


Dim myBrush As Brush

Dim userMsg As String

userMsg = InputBox(“What is your message?”, “Message Entry Form”, “Enter your message
here”, 100, 200)

myBrush = New Drawing.SolidBrush(Color.DarkOrchid)

myFont = New System.Drawing.Font(“Verdana”, 20, FontStyle.Underline)

myGraphics.DrawString(userMsg, myFont, myBrush, 10, 10)

[Lesson 23] << [CONTENTS] >> [Lesson 25]


Visual Basic 2012 Lesson 25– Managing Graphics -Drawing
Polygon and Pie
Visual Basic 2012 Lección 25-Gerente Gráficos -Dibujo
Polígono y Pie
[Lesson 24] << [CONTENTS] >> [Lesson 26]

We have learned how to draw rectangle, ellipse ,circle and text in the preceding chapters, now
let’s learn how to draw polygons on the screen. Besides that, we shall also learn how to draw
pie.

Hemos aprendido cómo dibujar rectángulo, elipse, círculo y el texto en los capítulos anteriores,
ahora vamos a aprender a dibujar polígonos en la pantalla. Además de eso, vamos a aprender
también cómo dibujar pastel.

25.1: Drawing Polygons

Polygon is a closed plane figure bounded by three or more straight sides. In order to draw a
polygon on the screen, we need to define the coordinates of all the points (also known as
vertices) that joined up to form the pollygon.

The syntax to defines the points of a polygon with vertices A1,A2,A3,A4…….An is as follows;

25,1: Dibujo de polígonos

Polígono es una figura plana cerrada delimitada por tres o más lados rectos. Para dibujar un
polígono en la pantalla, tenemos que definir las coordenadas de todos los puntos (también
conocidos como vértices) que se unieron para formar la pollygon.

La sintaxis para define los puntos de un polígono con vértices A1, A2, A3, A4 ...... .An es como
sigue;

Dim A1 As New Point(X1,Y1)

Dim A2 As New Point(X2,Y2)

Dim A3 As New Point(X3,Y3)

Dim A4 As New Point(X4,Y4)

Dim An as New Point(Xn,Yn)


After declaring the points, we need to define a point structure that group all the points together
using the following syntax:
Dim myPoints As Point() = {A1, A2, A3,….,An}

.Finally, create the graphics object and use the DrawPolygon method to draw the polygon
using the following syntax:

Después de declarar los puntos, tenemos que definir una estructura de puntos que agrupan
todos los puntos juntos utilizando la siguiente sintaxis:

Dim myPoints Como Point () = {A1, A2, A3, ...., An}

.Finalmente, Crear el objeto gráfico y utilizar el método drawPolygon para dibujar el polígono
con la siguiente sintaxis:

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPolygon(myPen, myPoints)

where myPen is the Pen object created using the following syntax:

myPen = New Pen(Drawing.Color.Blue, 5)

Example 25.1 :Drawing a Triangle

A triangle is a polygon with three vertices. Here is the sample code:

Ejemplo 25.1: Dibujar un triángulo

Un triángulo es un polígono con tres vértices. Aquí está el código de ejemplo:

Dim myPen As Pen

Dim A As New Point(10, 10)

Dim B As New Point(100, 50)

Dim C As New Point(60, 150)

Dim myPoints As Point() = {A, B, C}

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPolygon(myPen, myPoints)

Running the program produces the image below:


Ejecutar el programa produce la imagen de abajo:

Example 25.2: Drawing a Quadrilateral

A quadrilateral is a polygon consists of four sides,so you need to define four vertices. The
following is the code:

Ejemplo 25.2: Dibujar un cuadrilátero

Un cuadrilátero es un polígono formado por cuatro lados, por lo que necesita para definir
cuatro vértices. El siguiente es el código:

Dim myPen As Pen

Dim A As New Point(10, 10)

Dim B As New Point(100, 50)

Dim C As New Point(120, 150)

Dim D As New Point(60, 200)

Dim myPoints As Point() = {A, B, C, D}

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPolygon(myPen, myPoints)
The output image is as shown below:

La imagen de salida es como se muestra a continuación:

25.2: Drawing Pie

In order to draw a pie, you can use the DrawPie method of the graphics object. As usual, you
need to create the Graphics and the Pen objects. The syntax for drawing a pie is:

myGraphics.DrawPie(myPen, X, Y, width,height, StartAngle, SweepAngle)

Where X and Y are the coordinates the bounding rectangle, other arguments are self-
explanatory. Both StartAngle and SweepAngle are measured in degree. SweepAngle can take
possible or negative values. If the value is positive, it sweep through clockwise direction while
negative means it sweep through anticlockwise direction.

Example 25.3: Drawing a pie that starts with 0 degree and sweep clockwise through 60
degree.

25,2: Dibujo Pie

Para dibujar un sector, puede utilizar el método DrawPie del objeto gráfico. Como siempre, es
necesario crear los gráficos y los objetos Pen. La sintaxis para trazar un pastel es:

myGraphics.DrawPie (myPen, X, Y, ancho, alto, startAngle, SweepAngle)

Donde X e Y son las coordenadas del rectángulo delimitador, otros argumentos son fáciles de
entender. Tanto startAngle y SweepAngle se miden en grados. SweepAngle puede tener
posibles o negativos valores. Si el valor es positivo, barrer a través de las agujas del reloj
mientras negativo significa que barren a través de dirección hacia la izquierda.
Ejemplo 25.3: Dibujar un pastel que se inicia con 0 grados y barrer las agujas del reloj a través
de 60 grados.

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPie(myPen, 50,50, 150,150,0,60)

The output image is as shown below:

La imagen de salida es como se muestra a continuación:

[Lesson 24] << [CONTENTS] >> [Lesson 26]


Visual Basic 2012 Lesson 26– Managing Graphics-Filling
Shapes with Color
Visual Basic 2012 Lección 26- Formas Gestión de Gráficos-
Relleno con color
[Lesson 25] << [CONTENTS] >> [Lesson 27]

In previous lessons, we have learned how to draw rectangle, ellipse ,circle ,polygon and pie
with outlines only. In this lesson, we will show you how to fill the shapes with color, or simply
solid shapes. Three methods that are used to fill shapes are FillRectangle, FillEllipse ,
FillPolygon and FillPie.

In order to fill the above shapes with color, we need to create the Brush object using the
following syntax:

myBrush = New SolidBrush(Color.myColor)

Where myColor can be any color such as red,blue, yellow and more. You don’t have to worry
about the names of the colors because the intellisense will display the colors and enter the
period after the Color key word.

En las lecciones anteriores, hemos aprendido cómo dibujar rectángulo, elipse, círculo,
polígono y pastel con sólo esbozos. En esta lección, vamos a mostrarle cómo llenar las formas
con el color, o simplemente formas sólidas. Tres métodos que se utilizan para rellenar formas
son FillRectangle, FillEllipse, FillPolygon y FillPie.

Con el fin de llenar las formas anteriores con el color, tenemos que crear el objeto Brush
utilizando la siguiente sintaxis:

MyBrush = Nuevo SolidBrush (Color.myColor)

Dónde myColor puede ser de cualquier color como el rojo, azul, amarillo y más. Usted no tiene
que preocuparse acerca de los nombres de los colores porque el IntelliSense mostrará los
colores y entrar en el período después de la palabra clave de color.

26.1 Drawing and Filling a Rectangle

The syntax to fill a rectangle with the color defined by the brush object is:

myGraphics.FillRectangle (myBrush, 0, 0, 150, 150)

The complete code is shown in the example below:

26.1 de relleno y dibujo un rectángulo

La sintaxis para llenar un rectángulo con el color definido por el objeto cepillo es:
myGraphics.FillRectangle (MyBrush, 0, 0, 150, 150)

El código completo se muestra en el ejemplo siguiente:

Example 26.1

Dim myPen As Pen

Dim myBrush As Brush

Dim myGraphics As Graphics = Me.CreateGraphics

myPen = New Pen(Drawing.Color.Blue, 5)

myBrush = New SolidBrush(Color.Coral)

myGraphics.DrawRectangle(myPen, 0, 0, 150, 150)

myGraphics.FillRectangle(myBrush, 0, 0, 150, 150)

The Output is shown below: La salida se muestra a continuación:

26.2 Drawing and Filling an Ellipse

The syntax to fill a ellipse with the color defined by the brush object is:

myGraphics.FillEllipse (myBrush, 0, 0, 150, 150)

The complete code is shown in the example below:


26.2 de relleno y dibujo una elipse

La sintaxis para llenar una elipse con el color definido por el objeto cepillo es:

myGraphics.FillEllipse (MyBrush, 0, 0, 150, 150)

El código completo se muestra en el ejemplo siguiente:

Example 26.2

Dim myPen As Pen

Dim myBrush As Brush

Dim myGraphics As Graphics = Me.CreateGraphics

myPen = New Pen(Drawing.Color.Blue, 5)

myBrush = New SolidBrush(Color.Coral)

myGraphics.DrawEllipse(myPen, 0, 0, 150, 180)

myGraphics.FillEllipse(myBrush, 0, 0, 150, 180)

The output is shown below: La salida se muestra a continuación:

26.3 Drawing and Filling a Polygon

The syntax to fill a polygon with the color defined by the brush object is:
myGraphics.FillPolygon(myBrush, myPoints)

The complete code is shown in the example below:

26.3 de relleno y dibujo un polígono

La sintaxis para llenar un polígono con el color definido por el objeto cepillo es:

myGraphics.FillPolygon (MyBrush, myPoints)

El código completo se muestra en el ejemplo siguiente:

Dim myPen As Pen

Dim myBrush As Brush

Dim A As New Point(10, 10)

Dim B As New Point(100, 50)

Dim C As New Point(120, 150)

Dim D As New Point(60, 200)

Dim myPoints As Point() = {A, B, C, D}

myPen = New Pen(Drawing.Color.Blue, 5)

myBrush = New SolidBrush(Color.Coral)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPolygon(myPen, myPoints)

myGraphics.FillPolygon(myBrush, myPoints)

Running the code produces the image below:


26.4 Drawing and Filling a Pie

The syntax to fill a pie with the color defined by the brush object is:

myGraphics.FillPie(myBrush, X, Y, width, height, StartAngle, SweepAngle)

The complete code is shown in the example below:

26.4 de relleno y dibujo a Pie

La sintaxis para rellenar un pastel con el color definido por el objeto pincel es:

myGraphics.FillPie (MyBrush, X, Y, ancho, alto, startAngle, SweepAngle)

El código completo se muestra en el ejemplo siguiente:

Dim myPen As Pen

Dim myBrush As Brush

myPen = New Pen(Drawing.Color.Blue, 5)

myBrush = New SolidBrush(Color.Coral)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPie(myPen, 30, 40, 150, 150, 0, 60)

myGraphics.FillPie(myBrush, 30, 40, 150, 150, 0, 60)

The output is shown below:


[Lesson 25] << [CONTENTS] >> [Lesson 27]
Visual Basic 2012 Lesson 27– Using Timer
Visual Basic 2012 Lección 27-Utilización del temporizador
[Lesson 26] << [CONTENTS] >> [Lesson 28]

In this lesson, we shall show you how to use timer in VB2012. Timer is used to control and
manage events that are time related. For example, you need timer to create a clock, a stop
watch, a dice, animation and more.

En esta lección, vamos a mostrarle cómo utilizar el temporizador en VB2012. Timer se usa
para controlar y gestionar los eventos que son el tiempo correspondiente. Por ejemplo, usted
necesita temporizador para crear un reloj, un cronómetro, un dado, animación y mucho más.

27.1 Creating a Clock

In order to create a clock, you need to use the Timer control that comes with Visual Basic
2012. The Timer control is a control object that is only used by the developer, it is invisible
during runtime and it does not allow the user to interact with it.

To create the clock, first of all start a new project in Visual Basic 2012 Express and select a
new Windows Application. You can give the project any name you wish, but we will name it
MyClock. Change the caption of the Form1 to MyClock in the properties window. Now add the
Timer control to the form by dragging it from the ToolBox. Next, insert a label control into the
form. Change the Font size of the label to 14 or any size you wish, and set the Font alignment
to be middle center. Before we forget, you shall also set the Interval property of the Timer
control to 1000, which reflects a one second interval(1 unit is 1 millisecond).

Now, you are ready for the coding. Actually you would be surprise that what you need to create
a clock is only a one-line code, that is:

Label1.Text = TimeOfDay

To actually create the clock, click on the Timer control and insert the code above ,as shown
below:

27.1 Creación de un reloj

Con el fin de crear un reloj, es necesario utilizar el control Timer que viene con Basic 2012.
Control visual El temporizador es un objeto de control que sólo es utilizado por el
desarrollador, es invisible en tiempo de ejecución y que no permite al usuario interactuar con
ella.

Para crear el reloj, en primer lugar iniciar un nuevo proyecto en Visual Basic 2012 Express y
seleccione una nueva aplicación para Windows. Puede dar al proyecto cualquier nombre que
desee, pero vamos a nombrarla MyClock. Cambie el título del Form1 para MyClock en la
ventana de propiedades. Ahora agregue el control Timer al formulario arrastrándolo desde la
caja de herramientas. A continuación, inserte un control de etiqueta en el formulario. Cambiar
el tamaño de fuente de la etiqueta a 14 o cualquier tamaño que quieran, y establecer la
alineación de fuente para ser centro medio. Antes de que nos olvidemos, pondrás también la
propiedad Interval del control Timer a 1000, lo que refleja un segundo intervalo de un (1
unidad es 1 milisegundo).

Ahora, usted está listo para la codificación. En realidad sería una sorpresa que lo que usted
necesita para crear un reloj es sólo un código de una sola línea, es decir:

Label1.Text = TimeOfDay

Para realmente crear el reloj, haga clic en el control Timer e introduzca el código de seguridad,
como se muestra a continuación:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Timer1.Tick

Label1.Text = TimeOfDay

End Sub

The Clock is shown below: El reloj se muestra a continuación:

27.2 Creating a Stopwatch

We can create a simple stopwatch using the Timer control. Start a new project and name it
stopwatch. Change the Form1 caption to Stopwatch. Insert the Timer control into the form and
set its interval to 1000 which is equal to one second. Also set the timer Enabled property to
False so that it will not start ticking when the program is started. Insert three command buttons
and change their names to StartBtn, StopBtn and ResetBtn respectively. Change their text to
“Start”, “Stop” and “Reset” accordingly. Now,key in the code as follows:

27.2 Creación de un cronómetro

Podemos crear un cronómetro simple utilizando el control Timer. Inicie un nuevo proyecto y el
nombre del cronómetro. Cambie el título Form1 para Cronómetro. Inserte el control Timer en el
formulario y establezca su intervalo de 1000 que es igual a un segundo. También establecer la
propiedad Enabled del temporizador en false para que no se iniciará marcando cuando se
inicia el programa. Inserte tres botones de comando y cambiar sus nombres a StartBtn,
StopBtn y ResetBtn respectivamente. Cambie su texto a "Inicio", "Stop" y "Reset" en
consecuencia. Ahora, introduzca el código de la siguiente manera:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Timer1.Tick

‘To increase one unit per second

Label1.Text = Val(Label1.Text) + 1

End Sub

Private Sub StopBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles StopBtn.Click

‘To stop the Timer

Timer1.Enabled = False

End Sub

Private Sub StartBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles StartBtn.Click

‘To start the Timer

Timer1.Enabled = True

End Sub

Private Sub ResetBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles ResetBtn.Click

‘To reset the Timer to 0

Label1.Text = 0

End Sub

The Interface of the Stopwatch is as shown below:

La interfaz del cronómetro es como se muestra a continuación:


27.3 Creating a Digital Dice

We can create a digital dice easily using the Timer Control. To create a dice, you need to
generate random numbers using the Rnd function. Rnd generates numbers between 0 and 1.
The statement

n = Int(1 + Rnd() * 6)

generates integers from 1 to 6 randomly.

In the code, we introduce the variable m to control the length of time of the rolling process. If m
is more than 1000, then the rolling process will stop by setting the timer enabled property to
False.

The compete is shown below:

27.3 Creación de un Dice digital

Podemos crear un dado digitales fácilmente utilizando el control Timer. Para crear un dado,
que necesita para generar números al azar utilizando la función Rnd. Vta genera números
entre 0 y 1 La declaración

n = Int (1 + Rnd () * 6)

genera números enteros de 1 a 6 azar.

En el código, se introduce la variable m para controlar la longitud de tiempo del proceso de


laminación. Si m es mayor que 1000, entonces el proceso de laminado se detendrá
estableciendo la propiedad con temporizador activada a Falso.
La competencia se muestra a continuación:

Public Class Form1

Dim n, m As Integer

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Timer1.Tick

m = m + 10

If m < 1000 Then

n = Int(1 + Rnd() * 6)

LblDice.Text = n

Else

Timer1.Enabled = False

m=0

End If

End Sub

Private Sub RollDiceBtn_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RollDiceBtn.Click

Timer1.Enabled = True

End Sub

End Class

Running the program produces a dice with fast changing numbers which stop at a certain
number. The interface is shown below:

Ejecutar el programa produce un dado con los números cambiando rápidamente que paran en
un número determinado. La interfaz se muestra a continuación:
[Lesson 26] << [CONTENTS] >> [Lesson 28]
Visual Basic 2012 Lesson 28– Creating Animation
Visual Basic 2012 Lección 28- Creación de animaciones
[Lesson 27] << [CONTENTS] >> [Lesson 29]

Although Visual Basic 2012 is generally a programming language designed for creating
business and other industrial applications and not for creating animation, it can be used to
create animation. In this lesson, we will show you just that.

Aunque Visual Basic 2012 es en general un lenguaje de programación diseñado para la


creación de otras aplicaciones comerciales e industriales y no para la creación de animación,
que puede ser utilizado para crear la animación. En esta lección, vamos a mostrarle
exactamente eso.

28.1 Moving an object

In this section, we will show you how to move an object by pressing a command button. You
need to make use of the Top and Left properties of an object to create animation. The Top
property defines the distance of the object from the top most border of the screen while the Left
property defines the distance of the object from leftmost border of the screen. By adding or
subtracting the distance of the object we can create the animated effect of moving an object.

Start a new project and name it as Movable Object, or any name you wish. Now insert a
PictureBox and in its Image property import a picture from your hard drive or other sources.
Next, insert four command buttons, change their captions to Move Up, Move Down, Move Left
and Move Right. Name them as MoveUpBtn, MoveDowbBtn, MoveLeftBtn and MoveRightBtn.

Now, click on the buttons and key in the following code:

28.1 Mover un objeto

En esta sección, le mostraremos cómo mover un objeto pulsando un botón de comando. Es


necesario hacer uso de las propiedades Top y Left de un objeto para crear la animación. La
propiedad Top define la distancia del objeto desde la frontera más superior de la pantalla,
mientras que la propiedad Left define la distancia del objeto desde la izquierda borde de la
pantalla. Mediante la adición o sustracción de la distancia del objeto podemos crear el efecto
animado de un objeto en movimiento.

Inicie un nuevo proyecto y el nombre como objeto móvil, o cualquier nombre que desee. Ahora
insertar un cuadro de imagen y en su importación Propiedad de la imagen de una imagen de
su disco duro u otras fuentes. Luego, inserte cuatro botones de comando, cambiar sus títulos
a Subir, Bajar, Mover a la izquierda y Mover a la derecha. Nombre de ellos como MoveUpBtn,
MoveDowbBtn, MoveLeftBtn y MoveRightBtn.

Ahora, haga clic en los botones y clave en el siguiente código:

Private Sub MoveDownBtn_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MoveDownBtn.Click
PictureBox1.Top = PictureBox1.Top + 10

End Sub

Private Sub MoveLeftBtn_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MoveLeftBtn.Click

PictureBox1.Left = PictureBox1.Left – 10

End Sub

Private Sub MoveRightBtn_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MoveRightBtn.Click

PictureBox1.Left = PictureBox1.Left + 10

End Sub

Explanation:

Each time the user clicks on the Move Down button, the distance of the PictureBox increases
by 10 pixels from the top border, creating a downward motion. On the other hand, each time
the user clicks on the Move Up button, the distance of the PictureBox decreases by 10 pixels
from the top borders, thus creating an upward motion. In addition, each time the user clicks on
the Move Left button, the distance of the PictureBox decreases by 10 pixels from the left
border, thus creating a leftward motion. Lastly, each time the user clicks on the Move Right
button, the distance of the PictureBox increases by 10 pixels from the left border, thus creating
an rightward motion.

explicación:

Cada vez que el usuario hace clic en el botón Mover hacia abajo, la distancia de los
PictureBox se incrementa en 10 píxeles desde el borde superior, la creación de un movimiento
hacia abajo. Por otro lado, cada vez que el usuario hace clic en el botón Mover hacia arriba, la
distancia de la PictureBox disminuye por 10 píxeles desde la parte superior de las fronteras,
creando así un movimiento hacia arriba. Además, cada vez que el usuario hace clic en el
botón Mover Izquierda, la distancia de la PictureBox disminuye por 10 píxeles desde el borde
izquierdo, creando así un movimiento hacia la izquierda. Por último, cada vez que el usuario
hace clic en el botón Mover a la derecha, la distancia de los PictureBox se incrementa en 10
píxeles desde el borde izquierdo, creando así un movimiento hacia la derecha.
The interface is shown below: La interfaz se muestra a continuación:

28.2 Creating Animation using Timer

We can create continuous animation using timer without the need to manually clicking a
command button. We can create left to right or top to bottom motion by writing the necessary
code.

First of all, insert a PictureBox into the form. In the PictureBox properties window,select the
image property and click to import an image file from your external sources such as your hard
drive, your Pendrive or DVD. We have inserted an image of a bunch of grapes.Next, insert a
Timer control into the form set its interval property to 100, which is equivalent to 0.1 second.
Finally, add two command button to the form, name one of them as AnimateBtn and the other
one as StopBtn, and change to caption to Animate and Stop respectively.

We make use of the Left property of the PictureBox to create the motion. PictureBox.Left
means the distance of the PictureBox from the left border of the Form . Now click on the Timer
control and type in the following code:

28.2 Creación de animaciones utilizando Timer

Podemos crear animación continua usando temporizador sin necesidad de hacer clic
manualmente un botón de comando. Podemos crear izquierda a derecha o de arriba a abajo el
movimiento al escribir el código necesario.

En primer lugar, inserte un cuadro de imagen en el formulario. En la ventana de propiedades


de PictureBox, seleccione la propiedad y haga clic en la imagen para importar un archivo de
imagen de sus fuentes externas, tales como el disco duro, su Pendrive o DVD. Hemos
insertado una imagen de un montón de grapes.Next, inserte un control Timer en la forma
establezca su propiedad intervalo a 100, lo que equivale a 0,1 segundos. Por último, agregue
dos botones de comando al formulario, el nombre de uno de ellos como AnimateBtn y el otro
como StopBtn, y cambiar al título a Animate y Stop respectivamente.

Hacemos uso de la propiedad Left del PictureBox para crear el movimiento. PictureBox.Left
significa la distancia de PictureBox desde el borde izquierdo del formulario. Ahora haga clic en
el control Timer y escriba el siguiente código:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Timer1.Tick

If PictureBox1.Left < Me.Width Then

PictureBox1.Left = PictureBox1.Left + 10

Else

PictureBox1.Left = 0

End If

End Sub

In the code above, Me.Width represents the width of the Form. If the distance of the PictureBox
from the left is less than the width of the Form, a value of 10 is added to the distance of the
PictureBox from the left border each time the Timer tick, or every 0.1 second in this example.
When the distance of the PictureBox from the left border is equal to the width of the form, the
distance from the left border is set to 0, which move the PictureBox object to the left border and
then move left again, thus creates an oscillating motion from left to right. We need to insert a
button to stop motion. The code is:

En el código anterior, Me.Width representa el ancho del formulario. Si la distancia del cuadro
de imagen de la izquierda es menor que el ancho del formulario, se añade un valor de 10 a la
distancia del cuadro de imagen desde el borde izquierdo cada vez que la señal de
temporizador, o cada 0,1 segundos en este ejemplo. Cuando la distancia de PictureBox desde
el borde izquierdo es igual a la anchura de la forma, la distancia desde el borde izquierdo se
establece en 0, el cual se mueve el objeto PictureBox a la frontera izquierda y luego moverse
a la izquierda de nuevo, por lo que crea un movimiento oscilante de izquierda a derecha.
Tenemos que insertar un botón para detener el movimiento. El código es:

Timer1.Enabled = False

To animate the PictureBox object, we insert a command button and key in the following code:

Para animar el objeto PictureBox, insertamos un botón de comando e introduzca el siguiente


código:

Timer1.Enabled = True
The Image of the Animation program is shown below: La imagen del programa de animación se muestra a continuación:

[Lesson 27] << [CONTENTS] >> [Lesson 29]


Visual Basic 2012 Lesson 29- Working with Databases Part 1

Visual Basic 2012 Lección 29-Trabajar con bases de datos de la


parte 1
[Lesson 28] << [CONTENTS] >> [Lesson 30]

29.1 Introduction to Database in Visual Basic 2012

In our daily life, we deal with many types of information or data such as names, addresses,
money, date, stock quotes, statistics and more. If you are in business or working as a
professional, you have to handle even more data. For example, a doctor need to keep track of
patients’ personal and medical information such as names, addresses, phone numbers as well
as blood pressure readings, blood sugar readings,surgical history, medicines prescribed in the
past and more. On the other hand, businesses usually have to manage large amount of data
pertaining to products and customers. All these data need to be organized into a database for
the ease of data management.

In the past , people usually deal with data manually like using cards and folders. However, in
present day fast pace global environment and Information age, it is no longer feasible to
manage data manually. Most data are now managed using computer-based database
management systems. Computer-based Database management systems can handle data
much faster and more efficient than human beings do. With the advent of the network and the
Internet technologies, data can now be managed locally and remotely. Companies usually
invest heavily in database management systems in order to run the organizations efficiently
and effectively. Database management systems are usually used in running payroll system,
inventory system, accounting system, payment system, order handling system, customer
relationship management system(CRM) and more. Some of the commercial database
management system(DBMS) are Oracle, Microsoft SQL server and Microsoft Access

29.1 Introducción a la base de datos en Visual Basic 2012

En nuestra vida diaria, nos ocupamos de muchos tipos de información o datos tales como
nombres, direcciones, el dinero, la fecha, cotizaciones de bolsa, estadísticas y mucho más. Si
estás en el negocio o trabajar como un profesional, usted tiene que manejar más datos. Por
ejemplo, un médico tiene que realizar un seguimiento de la información personal y médica de
los pacientes, tales como nombres, direcciones, números de teléfono, así como lecturas de la
presión arterial, las lecturas de azúcar en la sangre, antecedentes quirúrgicos, medicamentos
prescritos en el pasado y más. Por otro lado, las empresas normalmente tienen que gestionar
gran cantidad de datos relativos a los productos y clientes. Todos estos datos deben ser
organizados en una base de datos para la facilidad de gestión de datos.

En el pasado, la gente por lo general se refieren a los datos de forma manual, como el uso de
tarjetas y carpetas. Sin embargo, en la actual ritmo rápido medio ambiente mundial y la edad
de la información, ya no es viable para gestionar los datos de forma manual. La mayoría de los
datos ahora se gestionan mediante sistemas de gestión de bases de datos basadas en la
informática. Sistemas de gestión de bases de datos basados en computadoras pueden
manejar datos mucho más rápidas y más eficientes que los seres humanos hacen. Con la
llegada de la red y las tecnologías de Internet, los datos se pueden gestionar de forma local y
remota. Las empresas suelen invertir fuertemente en sistemas de gestión de bases de datos
con el fin de ejecutar las organizaciones de manera eficiente y eficaz. Sistemas de gestión de
bases de datos se utilizan por lo general en el funcionamiento de sistema de nómina, sistema
de inventarios, sistema, sistema de pago, sistema de gestión de órdenes, sistema de gestión
de relaciones con clientes (CRM) y más que representan. Algunos de los sistema de gestión
de bases de datos comerciales (DBMS) son Oracle, Microsoft SQL Server y Microsoft Access

29.2 Creating a Database Application in Visual Basic 2012

A database management system typically deals with storing, modifying, and extracting
information from a database. It can also add, edit and delete records from the database.
However, a DBMS can be very difficult to handle by ordinary people or business men who
have no technological backgrounds. Fortunately, we can create user friendly database
applications to handle the aforementioned jobs with the DBMS running in the background. One
of the best programs that can create such database application is none other than Visual Basic
2012.

29.2 Creación de una aplicación de base de datos en Visual Basic 2012

Un sistema de gestión de base de datos se ocupa típicamente con almacenar, modificar y


extraer información de una base de datos. También puede agregar, editar y eliminar registros
de la base de datos. Sin embargo, un DBMS puede ser muy difícil de manejar por la gente
común o los hombres de negocios que no tienen antecedentes tecnológicos.
Afortunadamente, podemos crear aplicaciones de bases de usuario amigable para manejar los
trabajos antes mencionados con el DBMS que se ejecutan en segundo plano. Uno de los
mejores programas que pueden crear estas aplicaciones de base de datos no es otro que
Visual Basic 2012.

Visual Basic 2012 uses ADO.NET to handle databases. ADO.NET is Microsoft’s latest database technology which can

works with many other advanced database management system such as Microsoft SQL server. In this lesson, we

will develop codes that make use of Microsoft SQL Server 2012, therefore you need to have Microsoft SQL Server

2012 installed in your PC, you can download Microsoft SQL Server 2012 Express for

free from http://www.microsoft.com/en-us/download/details.aspx?id=29062.

Visual Basic 2012 utiliza ADO.NET para manejar bases de datos. ADO.NET es la última tecnología de base de datos

de Microsoft que puede trabaja con muchos otros sistemas de gestión de bases de datos avanzadas, como

Microsoft SQL Server. En esta lección, vamos a desarrollar códigos que hacen uso de Microsoft SQL Server 2012,

por lo tanto, es necesario tener Microsoft SQL Server 2012 instalado en su PC, puede descargar Microsoft SQL

Server 2012 Express para conexión de http://www.microsoft.com/en-

us/download/details.aspx?id=29062
To begin building the database project in Visual Basic 2012, launch Visual Basic 2012. You
can name your project as Database Project 1 or what ever name you wish to call it. Next,
change the default form’s Text property to Contacts as we will be building a database of
contact list. There are a few objects in ADO.NET that are required to build the database. There
are:

 SqlConnection- to connect to a data source in SQL Server


 DataTable -to store data for navigation and manipulation
 DataAdapter- to populate a DataReader

The aforementioned objects belongs to the System.Data and the System.Xml


namespace. Therefore, we need to reference them in the beginning before we can
work with them. To reference the ADO.NET object, choose project from the menu
then select Database Project 1 properties to display the project properties. Next
click the References tab to show the active references for the project, as shown in
Figure 29.1

Para comenzar a construir el proyecto de base de datos en Visual Basic 2012, Visual Basic
inicia 2012. Usted puede nombrar su proyecto como Project Database 1 o lo que sea el
nombre que desea llamar. A continuación, cambie la propiedad Text del formulario
predeterminado a Contactos ya que estaremos construyendo una base de datos de la lista de
contactos. Hay unos cuantos objetos de ADO.NET que se requieren para construir la base de
datos. Hay:

• SqlConnection- para conectarse a una fuente de datos en SQL Server

• almacenar datos DataTable: para para la navegación y la manipulación

• DataAdapter- para rellenar un DataReader

Los objetivos mencionados anteriormente pertenecen al System.Data y el espacio de nombres


System.Xml. Por lo tanto, tenemos que hacer referencia a ellos en el principio antes de que
podamos trabajar con ellos. Para hacer referencia al objeto ADO.NET, seleccione Proyecto en
el menú a continuación, seleccione Proyecto de base de datos 1 propiedades para mostrar las
propiedades del proyecto. Siguiente, haga clic en la pestaña Referencias para mostrar las
referencias activas para el proyecto, como se muestra en la Figura 29.1
Under imported namespaces, make sure system.data, System.Data.Sqlclient are selected,
otherwise check them. Having done that you need to click the Save All button on the toolbar
and then return to the Visual Basic 2012 IDE.

We shall proceed to create connection to the database source file in the next lesson.

Bajo los espacios de nombres importados, asegúrese system.data, System.Data.SQLClient se


seleccionan, de lo contrario los revise. Habiendo hecho esto usted necesita hacer clic en el
botón Guardar todo en la barra de herramientas y luego regresar a la base 2012 IDE Visual.

Se procede a crear la conexión con el archivo de origen de base de datos en la siguiente


lección.

[Lesson 28] << [CONTENTS] >> [Lesson 30]


Visual Basic 2012 Lesson 30- Working with Databases Part 2

Visual Basic 2012 Lección 30 Cómo trabajar con bases de datos de


la parte 2
[Lesson 29] << [CONTENTS] >>[Lesson 31]

30.1 Creating Connection to a Database using ADO.NET

In Visual Basic 2012, we need to create connection to a database before we can access its
data. Before we begin, let’s create a new database. Since we are using SQL Server 2012 as
the database engine, we will use Microsoft Studio Management Express to create a
database with the mdf extension. We shall name this database file as test.mdf. After creating
the database, build a table called Contacts and create two fields and name them ContactName
and State respectively. Enter a few data in the table and click Save All to save the data. Now
we are ready to connect to this new database.

ADO.NET offers a number of connection objects such as OleDbConnection,


SqlConnection and more. OleDbConnection is used to access OLEDB data such as
Microsoft Access whilst SqlCOnnection is used to access data provided by Microsoft SQL
server. Since we will work with SQL database in our example, we will use the SqlConnection
object. To initialize the variable to a new SqlConnection object, we use the following syntax:

Private MyCn As New SqlConnection

Having created the instance of the SqlConnecton object, the next step is to establish a
connection to the data source using the SQL ConnectionString property. The syntax is:

MyCn.ConnectionString = “Data Source=TOSHIBA-PC\SQL2012;


AttachDbFilename=C:\Program Files\Microsoft SQL
Server\MSSQL11.SQL2012\MSSQL\DATA\Test.mdf; ” & _
“User Instance=True;Integrated Security=SSPI”

* You need to change the reference to the SQL server (TOSHIBA-PC\SQL2012) as well as the
path to database file Test.mdf .
After establishing connection to the database, you can open the database using the following
syntax:

MyCn.Open()

30.1 Creación de la conexión a una base de datos usando ADO.NET

En Visual Basic 2012, tenemos que crear la conexión a una base de datos antes de poder
acceder a sus datos. Antes de empezar, vamos a crear una nueva base de datos. Ya que
estamos usando SQL Server 2012 como el motor de base de datos, vamos a utilizar Microsoft
Management Studio Express para crear una base de datos con la extensión mdf. Vamos a
llamar a este archivo de base de datos como test.mdf. Después de crear la base de datos,
crear una tabla llamada Contactos y crear dos campos y nombrarlos ContactName y el
Estado, respectivamente. Introduzca unas pocas de datos en la tabla y haga clic en Guardar
todo para guardar los datos. Ahora estamos listos para conectarse a esta nueva base de
datos.

ADO.NET ofrece una serie de objetos de conexión como OleDbConnection, SqlConnection y


más. OleDbConnection se utiliza para acceder a los datos OLEDB como Microsoft Access
mientras SqlConnection se utiliza para acceder a los datos proporcionados por el servidor
Microsoft SQL. Desde vamos a trabajar con base de datos SQL en nuestro ejemplo, vamos a
utilizar el objeto SqlConnection. Para inicializar la variable a un nuevo objeto SqlConnection,
se utiliza la siguiente sintaxis:

Mi CN privados como nuevo SqlConnection

Después de haber creado la instancia del objeto SqlConnecton, el siguiente paso es


establecer una conexión con la fuente de datos utilizando la propiedad ConnectionString SQL.
La sintaxis es la siguiente:
MyCn.ConnectionString = "Data Source = TOSHIBA-PC \ SQL2012; AttachDBFileName = C: \
Archivos de programa \ Microsoft SQL Server \ MSSQL11.SQL2012 \ MSSQL \ DATA \
Test.mdf; "& _

"La instancia de usuario = True; Integrado de Seguridad = SSPI"

* Es necesario cambiar la referencia al servidor SQL (TOSHIBA-PC \ SQL2012), así como la


ruta de acceso al archivo de base de datos Test.mdf.

Después de establecer la conexión a la base de datos, se puede abrir la base de datos con la
siguiente sintaxis:

MyCn.Open ()

30.2 Populating Data in ADO.NET

Establishing connection to a database in Visual Basic 2010 using SqlConnection alone will not
present anything tangible things to the user to manipulate the data until we add more relevant
objects and write relevant codes to the project.

The next step is to create an instance of the SqlDataAdpater in our code so that we can
populate the DataTable with data from the data source. Besides, you also need to create an
instance of the DataTable. Other than that, you should also create an instance of
theSqlCommandBuilder which is used to manipulate data such as updating and deleting data
in the Datatable and send the changes back to the data source. The statements are:

30.2 Poblando datos en ADO.NET

El establecimiento de la conexión a una base de datos en Visual Basic 2010 utilizando


SqlConnection por sí sola no presenta nada cosas tangibles al usuario manipular los datos
hasta que añadimos objetos más relevantes y escribir los códigos pertinentes para el proyecto.

El siguiente paso es crear una instancia de la SqlDataAdpater en nuestro código para que
podamos llenar el DataTable con los datos del origen de datos. Además, también es necesario
para crear una instancia de la DataTable. Aparte de eso, también se debe crear una instancia
de theSqlCommandBuilder que se utiliza para manipular los datos, tales como la actualización
y supresión de datos en el Datatable y enviar los cambios a la fuente de datos. Los estados
son:

Private MyDatAdp As New SqlDataAdapter


Private MyCmdBld As New SqlCommandBuilder
Private MyDataTbl As New DataTable

Besides that, we need to declare a variable to keep track of the user’s current row within the
data table. The statement is

Además de eso, tenemos que declarar una variable para realizar un seguimiento de la fila
actual del usuario dentro de la tabla de datos. La declaración es

Private MyRowPosition As Integer = 0

Having created the above of objects, you need to include the following statements in the Sub
Form_Load event to start filling the DataTable with data from the data source. The statements
are as follows:

Después de haber creado las anteriores de los objetos, es necesario incluir las siguientes
declaraciones en el evento Form_Load Sub para comenzar a llenar el DataTable con los datos
del origen de datos. Los estados son los siguientes:

MyDatAdp = New SqlDataAdapter(“Select* from Contacts”, MyCn)


MyCmdBld = New SqlCommandBuilder(MyDatAdp)
MyDatAdp.Fill(MyDataTbl)

After filling up the DataTable , we need to write code to access the data. To access data in the
DataTable means that we need to access the rows in the table. We can achieve this by using
the DataRow object. For example, we can write the following to access the first row of the table
and present the data via two text boxes with the name txtName and txtState respectively:

Después de llenar el DataTable, tenemos que escribir código para acceder a los datos. Para
acceder a los datos en el DataTable significa que tenemos que acceder a las filas de la tabla.
Podemos lograr esto mediante el uso del objeto DataRow. Por ejemplo, podemos escribir lo
siguiente para acceder a la primera fila de la tabla y presentar los datos a través de dos
cuadros de texto con el nombre txtName y txtState respectivamente:

Dim MyDataRow As DataRow = MyDataTbl.Rows(0)

Dim strName As String

Dim strState As String

strName = MyDataRow(“ContactName”)

strState = MyDataRow(“State”)

txtName.Text = strName.ToString
txtState.Text = strState.ToStringMe.showRecords()

* The two fields being referenced here are ContactName and State. Note Index 0 means first
row.

showRecords() is a sub procedure created to show data in the text boxes. The code is as
follows:

* Los dos campos que se hace referencia aquí son ContactName y Estado. Nota Índice 0
significa primera fila.

showRecords () es un procedimiento sub creado para mostrar los datos en los cuadros de
texto. El código es el siguiente:

Private Sub showRecords()

If MyDataTbl.Rows.Count = 0 Then
txtName.Text = “”
txtState.Text = “”
Exit Sub
End If

txtName.Text = MyDataTbl.Rows(MyRowPosition)(“ContactName”).ToString
txtState.Text = MyDataTbl.Rows(MyRowPosition)(“State”).ToString

End Sub

Take a look at the output interface:

Echa un vistazo a la interfaz de salida:


We will discuss how to manipulate data in the next lesson.

Vamos a discutir cómo manipular los datos en la siguiente lección.

[Lesson 29] << [CONTENTS]>> [Lesson 31]


Visual Basic 2012 Lesson 31: Working with Databases Part 3
Visual Basic 2012 Lección 31: Cómo trabajar con bases de
datos de la parte 3
[Lesson 30] << [CONTENTS]>>[Next]

In previous lessons, you have learned how to connect to a database as well as filling up the
table with data in Visual Basic 2012, now you shall learn how to manipulate data in the
database. Manipulating data means adding news records, editing records, deleting records,
browsing records and more.

En las lecciones anteriores, usted ha aprendido cómo conectarse a una base de datos, así
como llenar la tabla con datos en Visual Basic 2012, ahora usted deberá aprender a manipular
los datos en la base de datos. La manipulación de los datos significa añadir registros de
usuarios, la edición de registros, eliminar registros, registros de navegación y mucho más.

31.1 Browsing Records 31.1 Buscar Registros


In previous lesson, we have learned how to display the first record using the showRecords sub procedure. In

this lesson, we will create command buttons and write relevant codes to allow the user to browse the records

forward and backward as well as fast forward to the last record and back to the first record.The first button

we need to create is for the user to browse the first record. We can use button’s text << to indicate to the

user that it is the button to move to the first record and button’s text >> to move to the last record. Besides

we can use button’s text < for moving to previous record and button’s text > for moving to next record.

En la lección anterior, hemos aprendido cómo mostrar el primer registro, usando el procedimiento

showRecords sub. En esta lección, vamos a crear botones de comando y escribir códigos pertinentes para

permitir al usuario navegar por los registros hacia adelante y hacia atrás, así como el avance rápido hasta el

último registro y volver al primer botón record.The primero tenemos que crear es para el usuario navegar por

el primer registro. Podemos utilizar el texto del botón << para indicar al usuario que es el botón para

desplazarse al primer registro y el texto del botón >> para mover al último registro. Además podemos utilizar

el texto del botón <para mover al registro anterior y el texto del botón> para mover al siguiente registro.

The code for moving to the first record is: El código para moverse al primer

registro es:

MyRowPosition = 0
Me.showRecords()

The code for moving to previous record is: El código para mover al récord

anterior es:

If MyRowPosition > 0 Then

MyRowPosition = MyRowPosition – 1

Me.showRecords()

End If

The code for moving to next record is: El código para mover al siguiente registro es:

If MyRowPosition < (MyDataTbl.Rows.Count – 1) Then


MyRowPosition = MyRowPosition + 1
Me.showRecords()
End If

The code for moving to last record is: El código para mover al último registro es:

If MyDataTbl.Rows.Count > 0 Then


MyRowPosition = MyDataTbl.Rows.Count – 1
Me.showRecords()
End If

31.2 Editing, Saving, Adding and Deleting Records

You can edit any record by navigating to the record and change the data values. However, you
need to save the data after editing them. You need to use the update method of the
SqlDataAdapter to save the data. The code is:

31.2 Edición, guardar, añadir y eliminar registros

Puede editar cualquier registro, vaya hasta el registro y cambiar los valores de los datos. Sin
embargo, es necesario guardar los datos después de la edición de ellos. Es necesario utilizar
el método de actualización del SqlDataAdapter para guardar los datos. El código es:

If MyDataTbl.Rows.Count <> 0 Then


MyDataTbl.Rows(MyRowPosition)(“ContactName”) = txtName.Text
MyDataTbl.Rows(MyRowPosition)(“state”) = txtState.Text
MyDatAdp.Update(MyDataTbl)
End If
You can also add new record or new row to the table using the following code :

También puede agregar nuevo registro o una nueva fila a la tabla usando el siguiente código:

Dim MyNewRow As DataRow = MyDataTbl.NewRow()


MyDataTbl.Rows.Add(MyNewRow)
MyRowPosition = MyDataTbl.Rows.Count – 1
Me.showRecords()

The code above will present a new record with blank fields for the user to enter the new data.
After entering the data, he or she can then click the save button to save the data.

El código anterior presentará un nuevo registro con campos en blanco para que el usuario
introduzca los nuevos datos. Una vez introducidos los datos, él o ella puede hacer clic en el
botón Guardar para guardar los datos.

Lastly, the user might want to delete the data. The code to delete the data is:

Por último, el usuario podría querer borrar los datos. El código para eliminar los datos es:

If MyDataTbl.Rows.Count <> 0 Then


MyDataTbl.Rows(MyRowPosition).Delete()
MyDatAdp.Update(MyDataTbl)
MyRowPosition = 0
Me.showRecords()
End If

The Visual Basic 2012 database program interface is shown below:

La interfaz del programa Visual Básico base de datos de 2012 se muestra a continuación:
Finally, you have learned how to create a database application in Visual Basic 2012. Please try
to create your very own database applications in Visual Basic 2012 from now on.

Por último, usted ha aprendido cómo crear una aplicación de base de datos en Visual Basic
2012 Por favor, intente crear sus propias aplicaciones de base de datos en Visual Basic 2012
a partir de ahora.

[Lesson 30] << [CONTENTS]>>[Next]


VB2010ME
Congratulation for mastering all the lessons. Now
is the time to grab a copy of Visual Basic 2010
Made Easy.
ENHORABUENA para dominar todas las lecciones.
Ahora es el momento de tomar una copia de Visual
Basic 2010 Made Easy.

Visual Basic 2010 Made Easy

Price: $25.00

AUTHOR: DR. LIEW VOON KIONG

Dear Friend,

Visual Basic 2010 Made Easy is an eBook written by the webmaster of our
Visual Basic 2010 Tutorial , Dr.Liew. With more than 200 pages of
contents,it complements our free online tutorial by providing a complete tutorial
for beginners.
Estimado amigo,

Visual Basic 2010 Made Easy es un libro electrónico escrito por el webmaster de nuestro
Tutorial de Visual Basic 2010, Dr.Liew. Con más de 200 páginas de contenido, que
complementa nuestro tutorial en línea gratis, proporcionando un completo tutorial para
principiantes.

Preview the Book

By reading this book ,you can:

 Understand the basic concepts of Visual Basic 2010 programming


 Create your own VB2010 programs right from the beginning
 Get programming ideas from many interesting sample programs.
 Modify the codes easily to suit your needs.
 Learn how to package and distribute your applications.

Vista previa del libro

Al leer este libro, usted puede:

• Comprender los conceptos básicos de programación Visual Basic 2010

• Crear sus propios programas VB2010 desde el principio

• Obtener la programación de las ideas de muchos programas de ejemplo interesantes.

• Modificar los códigos fácilmente para adaptarse a sus necesidades.

• Aprenda cómo empaquetar y distribuir sus aplicaciones.

*Please wait for 10 seconds for PayPal to redirect you to E-book


Download Page after ordering and making payment. If you have
problem downloading the book, please email admin@vbtutor.net
* Por favor, espere 10 segundos para que PayPal le redirigirá a E-book Descarga de la página
después de ordenar y hacer el pago. Si usted tiene problema al descargar el libro, por favor escriba
admin@vbtutor.net
Mode of Delivery: Download

Warmest Regards

Modo de entrega: Descargar

Saludos cordiales

(Dr.Liew)

Disclaimer

This site and the products and services offered on this site are not associated,
affiliated, endorsed, or sponsored by Microsoft, nor have they been reviewed tested or
certified by Microsoft.

Contact Information

If you require assistant and technical support, please email

admin@vbtutor.net

Descargo de responsabilidad

Este sitio y los productos y servicios ofrecidos en este sitio no están asociados, afiliados,
avalados o patrocinados por Microsoft, ni han sido revisados probado o certificado por
Microsoft.

Información del contacto

Si usted requiere asistente y soporte técnico, por favor correo electrónico

admin@vbtutor.net

You might also like