Sie sind auf Seite 1von 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 versin 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 aadido muchas caractersticas
nuevas. La diferencia ms clara es que Visual Basic 2012 no ms se presenta como un programa
independiente , que ahora est integrado con otros lenguajes de Microsoft de programacin 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 ms informacin 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, slo con variaciones muy leves. Con ms de 200 pginas de contenidos y muchas
manos en ejemplos, usted debera ser capaz de dominar los fundamentos de la VB2010 y VB2012 rpidamente. Este
libro tambin puede ser utilizado como libro de texto para el aprendizaje en el aula. Haga clic en la imagen del libro
a continuacin para obtener ms informacin.

ISBN-13: 978-1467975193
Preview the book


Visual Basic 2012 Lesson 1 Introduction to Visual Basic 2012
[CONTENTS] >>[Lesson 2]
Visual Basic 2012 Leccin 1 - Introduccin a Visual Basic 2012
[NDICE] >> [Leccin 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 versin 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 aadido muchas caractersticas nuevas. La diferencia ms clara es que Visual
Basic Express 2012 no ms se presenta como un programa independiente, que ahora est
integrado con otros lenguajes de Microsoft de programacin C # y C ++ en un paquete
denominado Adems 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 tambin una programacin completa orientada a objetos hecha y derecha (POO)
Idioma, por lo que ha puesto al da 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 Pgina 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 pgina Visual Studio Nuevo proyecto, como se muestra a
continuacin:

Figure 1.2: Visual Studio 2012 Project Page Figura 1.2: Visual Studio 2012 Pgina 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 pgina 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 Aplicacin de Windows Forms.
En la parte inferior de este cuadro de dilogo, puede cambiar el nombre del proyecto por
defecto WindowsApplication1 a algn otro nombre que te gusta, por ejemplo, MyFirstProgram.
Despus 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. Tambin 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 cmo 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 ttulo
del programa. A continuacin, inserte un botn y cambiar su texto a Aceptar. La interfaz de
diseo se muestra en la Figura 1.5

Figure 1.5: The Design Interface Figura 1.5: La interfaz de Diseo
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 botn OK para que aparezca la ventana de cdigo 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 cdigo
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
continuacin, haga clic en el botn Aceptar, aparecer un cuadro de dilogo 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 funcin es una funcin integrada de Visual Basic 2012 y se mostrar el texto
encerrado entre corchetes.
Ahora que ha creado su primer programa, vamos a aprender ms tcnicas de programacin
VB2012 en prximas 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. Lets
examine a few programs that made use of Button, Label, TextBox , ListBox and PictureBox .
You dont 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, mens, barras de
herramientas, datos, Componentes, Impresiones y dilogos. Por el momento, nos centraremos
en los controles comunes. Algunos de los controles comunes ms utilizados son Button, Label,
ComboBox, ListBox, PictureBox, TextBox etc
Para insertar un control en su forma en 2012 IDE de Visual Basic, slo tiene que arrastrar el
control desde la caja de herramientas y soltarlo en el formulario. Puede volver a colocar y
cambiar el tamao 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
cdigo todava, 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 Creacin 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 botn 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 botn en el formulario, como se muestra a continuacin:

Now click on the OK button and the code window appears. Enter the code as follows:
Ahora haga clic en el botn OK y aparecer la ventana de cdigo. Introduzca el cdigo 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 botn Aceptar, aparecer un cuadro de dilogo
aparecer y mostrar el "BIENVENIDOS A VISUAL BASIC 2012" mensaje, como se muestra
en la siguiente figura. El argumento Ttulo: consiste en asignar el ttulo del cuadro de dilogo .:



2.2 Using the Text Box 2.2 Cmo 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 cmo crear una calculadora simple que suma dos nmeros utilizando el
control TextBox. En este programa, inserte dos cuadros de texto, tres etiquetas y un botn.
Los dos cuadros de texto son para los usuarios introducir dos nmeros, 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 botn para calcular, a continuacin, haga clic en este botn e
introduzca el siguiente cdigo:
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 nmeros, al pulsar el botn de calcular se
permitir realizar, adems de los dos nmeros.

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

Visual Basic 2012 Lesson 3-Working with Control Properties
Visual Basic 2012 Leccin 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 users
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 accin de un usuario, hay que establecer ciertas propiedades del
control para determinar su aspecto y cmo 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 diseo o en tiempo de ejecucin. Figura 3.1 es la ventana de
propiedades tpicas de un formulario. Se refiere en particular a la interfaz del primer programa
que has aprendido en la leccin 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 forms 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 forms background color. The formula to assign the RGB color to the form
is Color.FormArbg(RGB code). The event procedure is as follows:
El ttulo del formulario se define mediante la propiedad Text y su nombre por defecto es la
Forma 1 Para cambiar de ttulo 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
ttulo es Calculadora de adicin. Tenga en cuenta que este ttulo 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
artculos en la columna de la derecha y luego cambiarlos escribiendo o seleccionando las
opciones disponibles. Tambin puede alterar otras propiedades de la forma como la fuente,
ubicacin, tamao, color de primer plano, color de fondo, MaximizeBox, MinimizeBox y etc
Tambin puede cambiar las propiedades del objeto en tiempo de ejecucin para dar efectos
especiales tales como el cambio de color, forma, efecto de animacin y as sucesivamente.
Por ejemplo el siguiente cdigo 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
cdigo RGB para el amarillo es 255,255,0. Yo en el cdigo refiero a la forma actual y
Backcolor es propiedad de color de fondo del formulario. La frmula para asignar el color RGB
a la forma es Color.FormArbg (cdigo 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.
Tambin puede utilizar el procedimiento siguiente para asignar el color en tiempo de
ejecucin.
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 cdigos RGB correspondientes. Siempre se
puede experimentar con otras combinaciones, pero recuerda que el nmero mximo para
cada color es 255 y el mnimo 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 cdigos RGB en tres
cuadros de texto diferentes y cuando l o ella hace clic en el botn de color de la pantalla, el
color de fondo del formulario cambiar de acuerdo con los cdigos RGB. As, este programa
permite a los usuarios cambiar las propiedades de color de la forma en tiempo de ejecucin.



The code el cdigo
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 artculo ha sido traducido a la lengua serbo-croata Vera Djuraskovic de Webhostinggeeks.com.

Visual Basic 2012 Lesson 4: Object Oriented Programming
Visual 2012 Leccin bsica 4: Programacin 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, lets get down to learning a few basic rules about writing the Visual
Basic 2012 program code.
En las tres primeras lecciones, has aprendido cmo entrar en el cdigo del programa y
ejecutar el ejemplo de programas de Visual Basic 2012, pero sin mucha comprensin sobre la
lgica de programacin Visual Basic 2012. Ahora, vayamos a aprender algunas reglas bsicas
sobre cmo escribir el cdigo 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 trminos 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 programacin orientada a
objetos, no est totalmente orientado a objetos. Para calificar como un lenguaje de
programacin orientado a objetos completo, debe tener tres tecnologas bsicas a saber
encapsulacin, herencia y polimorfismo. Estos tres trminos se explican a continuacin:



Encapsulation La encapsulacin
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 encapsulacin se refiere a la creacin de mdulos 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 mtodos 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 podra 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 jerarquas, y la herencia permite a la estructura y los
mtodos de una clase que se deben pasar por la jerarqua. Esto significa que se requiere
menos programacin y al aadir funciones a los sistemas complejos. Si se aade un paso en
la parte inferior de una jerarqua entonces slo necesita, el procesamiento y los datos
asociados con ese paso nico que se aade. Todo lo dems en ese paso se hereda. La
capacidad de reutilizar los objetos existentes se considera una de las principales ventajas de
la tecnologa 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:
Programacin orientada a objetos permite que los procedimientos acerca de los objetos que
se creen cuyo tipo exacto no se conoce hasta el tiempo de ejecucin. Por ejemplo, un cursor
de la pantalla puede cambiar su forma de una flecha a una lnea segn el modo de programa.
La rutina para mover el cursor en la pantalla en respuesta al movimiento del ratn se escribira
para "cursor", y el polimorfismo permite que el cursor para asumir cualquier forma que se
requiere en tiempo de ejecucin. Tambin permite nuevas formas para integrar fcilmente.
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 programacin, al igual que otra
programacin orientada a objetos, como C ++ y Java. Se centra ms en los datos en s,
mientras que las versiones anteriores de Visual Basic 6 y se centran ms en las acciones. VB6
y sus predecesores se les conoce como lenguaje de programacin procedimental o funcional.
Algunos otros lenguajes de programacin procedimentales son C, Pascal y Fortran.
Visual Basic 2012 permite a los usuarios escribir programas que se descomponen en
mdulos. Estos mdulos 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 tambin 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 mtodos. 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

Lets 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 cmo crear una clase. El siguiente ejemplo muestra cmo 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 dilogo 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 botn, 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 Leccin Visual Basic 5-Escribir el Cdigo
[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 leccin anterior, que ha aprendido que Visual Basic 2012 es un lenguaje de
programacin orientado a objetos. Tambin ha entendido el significado de clase, objeto,
herencia encapsulacin y polimorfismo. Tambin ha aprendido a escribir algunos programas
simples sin mucho entender algunos fundamentos y teoras subyacentes. En esta leccin,
usted aprender algunas teoras bsicas acerca de programacin Visual Basic 2012, pero nos
centraremos ms en aprender haciendo, es decir, aprender a escribir programas .I
mantendremos las teoras corto, as que no sera demasiado difcil 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 programacin orientado a objetos y orientada a eventos.
De hecho, todas las aplicaciones de Windows estn evento impulsado. Evento impulsado
significa que el usuario decidir qu hacer con el programa, si l o ella quiere hacer clic en el
botn de comando, escriba el texto en un cuadro de texto, o cerrar la aplicacin, etc Un evento
se relaciona con un objeto, es un incidente que ocurre en el objeto debido a la accin 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 aplicacin de Windows en Visual
Basic 2012 en los captulos 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 dont have
to worry the rest of the stuff at the moment, they will be explained in later lessons.
Para comenzar a escribir cdigo en Visual Basic 2012, haga clic en cualquier parte de la forma
de entrar en la ventana de cdigo, 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 vaca. Usted no tiene que preocuparse del resto de las cosas en
este momento, que se explicarn 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 ms, como se muestra en el diagrama de la Figura 5.2 (aparece al hacer
clic en el panel superior derecho de la ventana de cdigo)

Figure 5.2
5.2 Writing the code 5.2 Escritura del cdigo

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. Lets
enter the following code :
Ahora ya est listo para escribir el cdigo para el procedimiento de evento para que se va a
hacer algo ms que cargar un formulario en blanco. El cdigo debe ser introducido entre
Private Sub ...... .End Sub. Nos adentraremos en el siguiente cdigo:
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 lnea del cdigo va a cambiar el ttulo del formulario a Mi Primer programa Visual
Basic 2012, la segunda lnea 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 lnea cambia el fondo al color AzulReal. El operador de igualdad = en el
cdigo se utiliza para asignar algo al objeto, al igual que la asignacin de color amarillo en el
primer plano del objeto Form1 (o una instancia de Form1). Me es el nombre dado a la clase
Form1. Tambin podemos llamar a estas lneas como declaraciones. As, las acciones del
programa dependern de las declaraciones formuladas por el programador.
La salida se muestra la Figura 5.3 a continuacin:

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 botn en el formulario y cambie su texto
de la etiqueta de "pantalla oculta de nombres". Haga clic en este botn para entrar en la
ventana de cdigo y clave-en el siguiente cdigo:
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 slo pueden manejar texto. Los nombres de las variables es
aceptar los nombres que se unen entre s por los "y" seales como una nica cadena. El
MsgBox funcin es la de mostrar la cadena en un cuadro de mensaje, y el ltimo argumento
"ocultos nombres" es el ttulo de la funcin MsgBox. La salida se muestra en la Figura 5.4 a
continuacin:

Figure 5.4

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

Visual Basic 2012 Lesson 6- Managing Data
Visual Basic 2012 Leccin 6 Administracin 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,
estadsticas y etc cotidiana. Del mismo modo, en Visual Basic 2012, tenemos que lidiar con
todo tipo de datos, algunos pueden ser calculados matemticamente mientras que algunos
son en forma de texto o de otras formas. 2012 divide los datos bsicos visuales en diferentes
tipos de modo que sea ms fcil de manejar cuando tenemos que escribir el cdigo que
participarn 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 informacin mencionada en dos tipos de datos principales, que
son los tipos de datos numricos y los tipos de datos no numricos.
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 numricos
Tipos de datos numricos son los tipos de datos que consisten en nmeros, que pueden
calcularse matemticamente con varios operadores de la norma, tales como agregar, menos,
multiplicar, dividir y as sucesivamente. Ejemplos de tipos de datos numricos son sus
calificaciones de los exmenes, su altura, su peso, el nmero de alumnos en una clase,
valores de acciones, precio de las mercancas, facturas mensuales, cuotas y etc En Visual
Basic 2012, los datos numricos se dividen en siete tipos , dependiendo de la gama de valores
que pueden almacenar. Los clculos que slo involucran cifras redondas o datos que no
necesitan de precisin puede utilizar entero o entero largo en el clculo. Los programas que
requieren alta necesidad de clculo de precisin para utilizar los tipos de datos de precisin
simple y doble, que tambin se llaman nmeros de punto flotante. Para el clculo de la
moneda, puede utilizar los tipos de datos de moneda. Por ltimo, si se requiere ms precisin
para realizar clculos 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 numricos
Tipos de datos no numricos son datos que no pueden ser manipulados matemticamente
utilizando operadores aritmticos estndar. Los datos no numrico consta de texto o datos de
cadena tipos, los tipos de datos de fecha, los tipos de datos booleanos que almacenan slo
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
aadir un sufijo detrs de un literal para que Visual Basic 2012 puede manejar el clculo con
mayor precisin. 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:
Adems, 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 carcter,
incluyendo los nmeros. 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 Gestin 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 trmino 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 nmero
No se permite el Perodo
Ejemplos de nombres de variables vlidos y no vlidos 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 Declaracin de variables
En Visual Basic 2012, hay que declarar las variables antes de utilizarlas mediante la
asignacin de nombres y tipos de datos. Si no lo hace, el programa mostrar un error. Ellos
normalmente se declaran en la seccin general de las ventanas los cdigos 'utilizando la
instruccin 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:
Tambin puede combinarlos en una sola lnea, 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 declaracin 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, slo 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 continuacin:
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 ms 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 Asignacin de valores a las variables
Despus de declarar varias variables utilizando las instrucciones Dim, podemos asignar
valores a las variables. El syntx de una asignacin es
Variable = Expresin
La variable puede ser una variable declarada o un valor de propiedad de control. La expresin
puede ser una expresin matemtica, un nmero, 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 ejecucin del programa.
6.3.1 Declaring a Constant
The syntax to declare a constant is
6.3.1 La declaracin 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
Bsicos 2012 Leccin 7- operaciones matemticas 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 clculos matemticos mucho ms rpido que los seres humanos.
Sin embargo, el propio equipo no ser capaz de realizar cualquier clculo matemtico, sin
recibir instrucciones por parte del usuario. En Visual Basic 2012, se puede escribir cdigo para
indicar al ordenador para realizar clculos matemticos, tales como suma, resta,
multiplicacin, divisin y otros tipos de operaciones aritmticas. Para que Visual Basic 2012
para realizar clculos aritmticos, tenemos que escribir cdigo que implica el uso de varios
operadores aritmticos. Los Bsica 2.012 operadores aritmticos visuales son muy similares a
los operadores aritmticos normales, slo con ligeras variaciones. El ms y el menos
operadores son los mismos, mientras que el operador de multiplicacin utilizar el smbolo * y el
operador de divisin usar el smbolo /. La lista de 2012 los operadores aritmticos de Visual
Basic se muestran en la tabla 7.1 a continuacin:





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 botn. Haga clic en el botn e
introduzca el cdigo como se muestra a continuacin. Al ejecutar el programa, se llevar a cabo las cuatro operaciones
aritmticas bsicas 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 Pitgoras 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 frmula
para el Teorema de Pitgoras, 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 podra afectar seriamente su salud.
La obesidad se ha demostrado por los expertos mdicos para ser un uno de los principales
factores que trae muchos problemas mdicos 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 mdico, que slo puede usar una
calculadora o un programa de ordenador casero, esto es exactamente lo que te estoy
mostrando aqu. El ndice de clculo 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 frmula peso / (estatura) ^ 2,
donde se mide el peso en kilogramos y la altura en metros. Si slo conoce su peso y altura en
libras y pies, entonces usted necesita para convertir al sistema mtrico (que podra de hecho
escribir un programa de VB para la conversin).
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 cdigo que implican operaciones
aritmticas es relativamente fcil. stos son los proyectos ms aritmticas 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 Leccin 8 - Manipulacin 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 manipulacin de cadenas es importante porque ayuda a procesar los
datos que se presentan en forma de tipos no numricos tales como nombres, direcciones, el
gnero, las ciudades, los ttulos de libros y ms.
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 Manipulacin de cadena usando + y y signos.
En Visual Basic 2012, las cadenas pueden ser manipulados usando el signo & y el signo +,
ambos realizan la concatenacin de cadenas que implica la combinacin de dos o ms
cadenas ms pequeas en cadenas ms grandes. Por ejemplo, podemos unirnos "Visual",
"Basic" y "2012" en "Visual Basic 2012" por medio de "Visual" y "Basic" o "Visual" + "bsico",
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 lnea = 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 numricos, no se puede utilizar el signo +, slo 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 cdigo 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 ms de dos cadenas para formar una cadena ms 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 Manipulacin de cadena utilizando VB2012 Funciones Integradas
Una funcin es similar a un procedimiento normal pero el propsito principal de la funcin 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 manipulacin de cadenas
incorporadas en Visual Basic 2012 pero slo 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 funcin Len
La funcin Len devuelve un valor entero que es la longitud de una frase o una frase,
incluyendo los espacios vacos. 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 Funcin Derecha
La funcin derecha extrae la porcin 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 posicin 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 mayora 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 razn de utilizar la referencia completa se debe a que muchos objetos tienen las
propiedades adecuadas por lo que usar el botn 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 Funcin Izquierda
La funcin de Izquierda extraer la porcin 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 posicin 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 Leccin 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 cmo escribir cdigo que acepte la entrada por
parte del usuario y muestra la salida sin controlar el flujo del programa. En esta leccin, usted
aprender cmo escribir cdigo de Visual Basic 2012 que puede tomar la decisin 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 programacin en Visual Basic
2012, ya que puede resolver problemas prcticos de forma inteligente y proporcionar una
salida til o informacin 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 condicin, o un programa que rechazar los datos no numricos. Con
el fin de controlar el flujo del programa y tomar decisiones, tenemos que utilizar los operadores
condicionales y los operadores lgicos 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
matemticos. 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 ms. Tambin se conocen como operadores de comparacin
numricos. Normalmente se utilizan para comparar dos valores para ver si son iguales o un
valor es mayor o menor que el otro valor. La comparacin 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 lgicos
A veces puede ser que necesitemos hacer ms de uno comparaciones antes de una decisin
puede ser tomada y la accin tomada. En este caso, el uso de operadores de comparacin
numrica por s sola no es suficiente, tenemos que usar operadores adicionales, y ellos son
los operadores lgicos. Estos operadores lgicos 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 numricos. Sin embargo, tambin
puede comparar cadenas con los operadores anteriores. Al hacer la comparacin cuerdas, hay ciertas
reglas que sigue:. Las letras maysculas son menores que las letras minsculas, "A" <"B" <"C" <"D" ......


<"Z" y el nmero 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 comparacin
Para controlar eficazmente el flujo del programa Visual Basic 2012, utilizaremos la estructura
de control Si junto con los operadores condicionales y operadores lgicos. Hay bsicamente
tres tipos de estructuras de control Si, a saber ... Si la declaracin .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 ifthen.. statement is
9.3 (a) Si ... Declaracin .Then
Esta es la estructura de control ms simple que indica al ordenador para realizar una
determinada accin especificada por la expresin de Visual Basic 2012 si la condicin es
verdadera. Sin embargo, cuando la condicin es falsa, no se realizar ninguna accin. La
sintaxis de la si ... entonces .. afirmacin 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 dont see any display.
* Cuando se ejecuta el programa y escribe un nmero que es mayor que 100, ver la
declaracin "Usted gana un premio de la suerte". Por otro lado, si el nmero introducido es
inferior o igual a 100, no ve ninguna pantalla.
9.3(b) If.ThenElse 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.ThenElse 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 ifthen.. Else statement is
9.3 (b) Si ... .Then ... Else
Utilizando slo si ... .Then declaracin no es muy til en la programacin y no ofrece opciones
para los usuarios. Con el fin de proporcionar una opcin, podemos utilizar la instruccin If ...
.Then ... Else. Esta estructura de control le pedir a la computadora para realizar una
determinada accin especificada por la expresin de Visual Basic 2012 si se cumple la
condicin. Y cuando la condicin es falsa, se ejecutar una accin 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 nmero que es mayor que 100, la declaracin
"Enhorabuena! Usted gana un premio de la suerte "se muestran. Por otro lado, si el nmero
introducido es menor o igual a 100, ver la declaracin "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 lgico 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 cdigo. En este ejemplo, el
nmero introducido debe ser ms de 100, y la edad debe ser ms 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.ThenElseIf 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.ThenElseIf Statement.
executed. The general format for the ifthen.. Else statement is
9.3 (c) Si ... .Then ... ElseIf Declaracin
Si hay ms de dos opciones alternativas, utilizando slo si ... .Then ... .Else declaracin no
ser suficiente. Con el fin de ofrecer ms opciones, podemos utilizar la instruccin 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 Leccin 10- Usando Seleccione
caso
[Lesson 9] << [CONTENTS] >> [Lesson 11]
In the previous lesson, we have learned how to control the program flow using the IfElseIf
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 IfThen..ElseIf statements will
become too messy.
En la leccin anterior, hemos aprendido a controlar el flujo del programa utilizando la
estructura de control If ... ElseIf. En esta leccin, obtendr informacin sobre cmo utilizar la
estructura Select casos y controles en Visual Basic 2012 para controlar el flujo del programa.
La estructura de control de seleccin de casos es ligeramente diferente de la Si ... .ElseIf
estructura de control. La diferencia es que la estructura Select casos y controles, bsicamente,
slo tomar la decisin en una expresin o dimensin (por ejemplo, la calificacin del examen),
mientras que la estructura de control de instruccin If ... ElseIf puede evaluar slo una
expresin, cada uno ... Si .ElseIf declaracin puede tambin calcular totalmente diferente
dimensiones. Se prefiere Select Case cuando existen mltiples condiciones como el uso de Si
... Then..ElseIf declaraciones se harn demasiado sucio.
10.1 The Select CaseEnd 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 seleccin 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
Expresin de prueba Caso
Lista de expresiones Caso 1
Bloque de uno o ms estados de Visual Basic 2012
Lista de expresiones Caso 2
Bloque de uno o ms de Visual Basic 2012 Declaraciones
Lista de expresiones de caso 3
.
.

caso
Else
Bloque de uno o ms de Visual Basic 2012 StatementsEnd Seleccionar
10.2 The usage of Select Case is shown in the following examples
Example 10.1
Examination Grades
Dim grade As String
Private Sub Compute_Click(
)
Example 10.2
In this example, you can use the
keyword Is together with the
comparison operators.Private Sub
Button1_Click(ByVal sender As
grade=txtgrade.Text
Select Case grade
Case A
Label1.Text=High
Distinction
Case A-
Label1.Text=Distinction
Case B
Label1.Text=Credit
Case C
Label1.Text=Pass
Case Else
Label1.Text=Fail
End Select
System.Object, ByVal e As
System.EventArgs) Handles
Button1.ClickExamination MarksDim
mark As Single
mark = mrk.Text
Select Case mark
Case Is >= 85
Label1.Text= Excellence
Case Is >= 70
Label2.Text= Good
Case Is >= 60
Label3.Text = Above Average
Case Is >= 50
Label4.Text= Average
Case Else
Label5.Text = Need to work harder
End SelectEnd Sub
Example 10.3Example
10.2 can be rewritten as
follows:
Private Sub
Button1_Click(ByVal
sender As
System.Object, ByVal e
As System.EventArgs)
Handles Button1.Click
Examination Marks
Dim mark As Single
mark = Textbox1.Text
Select Case mark
Example 10.4Grades in high school
are usually presented with a single
capital letter such as A, B, C, D or E.
The grades can be computed as
follow:
Private Sub
Button1_Click(ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles
Button1.Click
Examination Marks

The output of Example 10.4


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

[Lesson 9] << [CONTENTS] >> [Lesson 11]


Visual Basic 2012 Lesson 11- Looping
Visual Basic 2012 Leccin 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 podran apoyar. Esto generalmente se llama bucle. Se requiere
Looping cuando necesitamos para procesar algo repetidamente hasta que se cumpla una
determinada condicin. Por ejemplo, podemos disear un programa que agrega una serie de
nmeros 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 instruccin Exit
For dentro del bucle; y se utiliza normalmente junto con el Si ... .Then
... ..sstatement. Para su aplicacin, se puede hacer referencia al ejemplo
11.1 d.


Example 11.1 a
Dim counter as Integer
For counter=1 to 10
ListBox1.Items.Add
(counter)
Next
* The program will enter
number 1 to 10 into the list
box.
Example 11.1b
Dim counter , sum As Integer
For counter=1 to 100 step 10
sum+=counter
ListBox1.Items.Add (sum)
Next
* The program will calculate the sum of the numbers as
follows:
sum=0+10+20+30+40+
Example 11.1c
Dim counter, sum As
Integer
sum = 1000
For counter = 100 To 5
Step -5
sum = counter
ListBox1.Items.Add(sum)
Next
*Notice that increment can
be negative.
The program will compute
the
subtraction as follow:
1000-100-95-90-.
Example 11.1d
Dim n as Integer
For n=1 to 10
If n>6 then
Exit For
End If
Else
ListBox1.Items.Add ( n)
Next
End If
Next
The process will stop when n is greater than 6.
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 algn momento tenemos que salir para salir de un bucle
prematuramente debido a un cierto
condicin se cumple. La sintaxis de uso es conocido como Exit
Do. Vamos a examinar los siguientes ejemplos















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

Example 11.2(a)
Do while counter
<=1000
TextBox1.Text=counter
counter +=1
Loop
* The above example
will keep on adding
until counter >1000.
The above example can
be rewritten as
Do
TextBox1.Text=counter
counter+=1
Loop until
counter>1000
Example 11.2(b)
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim sum, n As Integer
ListBox1.Items.Add(n & vbTab & Sum)
ListBox1.Items.Add(-)
Do
n += 1
sum += n
ListBox1.Items.Add(n & vbTab & sum)
If n = 100 Then
Exit Do
End If
Loop
End Sub
Visual Basic 2012 Lesson 12- Functions Part 1

Visual Basic 2012 Leccin 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 funcin en Visual Basic 2012 es similar a un procedimiento normal pero el propsito
principal de la funcin es la de aceptar una cierta entrada y devolver un valor que se transmite
al programa principal para terminar la ejecucin. 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 funcin es
FunctionName (argumentos)
Los argumentos son los valores que se transmiten a la function.In esta leccin, vamos a
aprender dos funciones internas muy bsicas 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 () Funcin
El objetivo de MsgBox es producir un cuadro de mensaje emergente y pedir al usuario que
haga clic en un botn de comando antes de que l / ella pueda contina. Este formato es el
siguiente:
yourMsg = MsgBox (Prompt, Estilo Valor, Ttulo)
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 botn de comando que se muestran. El
argumento Ttulo mostrar el ttulo 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 ms legibles. De hecho, Visual Basic 2012 se muestra automticamente
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 funcin 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 seccin de declaracin
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 ms sofisticado, puede agregar un icono
adems 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 wont 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 () Funcin
Una funcin 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, Ttulo, default_text, la posicin x, y posicin)
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.
Ttulo - El ttulo 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.
posicin x e y de la posicin - la posicin o exceda 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, Ttulo, default_text, x-posicin, y-posicin)
Los parmetros 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 botn
de comando

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



Visual Basic 2012 Lesson 13- Function Part II
Visual Basic 2012 Leccin 13-Funcin 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 bsico de la funcin en Visual Basic 2012 En particular, hemos
demostrado cmo utilizar la funcin MsgBox y la funcin InputBox en la Leccin 12 De hecho,
ya hemos ilustrado algunas funciones de manipulacin de cadenas en la leccin 8, que son la
funcin Len, la funcin de la izquierda y de la funcin Derecha. En esta leccin, aprenderemos
otras funciones de manipulacin 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.
uncin 13.1 El Mid
La funcin Mid se utiliza para recuperar una parte de texto forman una frase. El formato de la
funcin Mid es
Mediados (frase, posicin, n)
donde
frase es la cadena de la que una parte de texto se va a recuperar.
posicin es la posicin inicial de la frase de la cual comienza el proceso de recuperacin.
n es el nmero 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 botn de comando, una caja de texto
aparecer para preguntarle al usuario que introduzca una frase. Despus de introducir una
frase y se pulsa el botn OK, la etiqueta mostrar el texto extrado a partir de la posicin 2 de
la frase y el nmero de caracteres extrada 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 Funcin Derecha
La funcin derecha extrae la porcin derecha de una frase. El formato es
Microsoft.Visualbasic.Right ("Frase", n)
Donde n es la posicin 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 Funcin Izquierda
La funcin de Izquierda extrae la porcin izquierda de una frase. El formato es
Microsoft.Visualbasic.Right ("Frase", n)
Donde n es la posicin 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 funcin de ajuste
La funcin Recortar recorta los espacios vacos 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 funcin LTrim
La funcin LTrim recorta los espacios vacos 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 Funcin Rtrim
La funcin de Rtrim recorta los espacios vacos 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 funcin InStr
La funcin InStr busca una frase que est incrustado dentro de la frase original y devuelve la
posicin inicial de la frase embebido. El formato es
Instr (n, fase original, frase embebido)
Donde n es la posicin donde la funcin Instr comenzar a buscar la frase embebido. por
ejemplo
Instr (1, "Visual Basic 2012", "Basic") = 8
* La funcin devuelve un valor numrico.
Usted puede escribir un cdigo de programa como se muestra a continuacin:
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 funcin Ucase convierte todos los caracteres de una cadena a maysculas. Por otro lado,
la funcin de LCASE convierte todos los caracteres de una cadena de letras pequeas.
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 funcin Chr devuelve la cadena que corresponde a un cdigo ASCII mientras que la
funcin Asc convierte un carcter ASCII o smbolo en el cdigo ASCII correspondiente. ASCII
significa "Cdigo Estndar Americano para Intercambio de Informacin". En total hay 255
cdigos ASCII y tantos caracteres ASCII. Algunos de los caracteres no se muestren, ya que
pueden representar algunas acciones, como la pulsacin de una tecla o producir un sonido de
pitido. El formato de la funcin 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 Leccin 14- Funciones Funciones Parte III
Matemticas
[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 cmo escribir cdigos en Visual Basic 2012 que
realizan operaciones aritmticas mediante operadores matemticos estndar. Sin embargo,
con el fin de realizar clculos matemticos ms complejos, tenemos que utilizar las funciones
matemticas incorporadas en Visual Basic 2012 Hay numerosas funciones integradas de
matemticas en Visual Basic 2012 que vamos a introducirlos uno a uno en esta leccin.
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 funcin Abs devuelve el valor absoluto de un nmero
dado.
La sintaxis es
Matemticas. Abs (nmero)
* La palabra clave de Matemticas aqu indica que la funcin
Abs pertenecen a la clase de matemticas. Sin embargo, no
todas las funciones matemticas pertenecen a la clase de
matemticas.


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 funcin Exp
El Exp de un nmero x es el valor exponencial de x, es decir, ex. Por ejemplo, Exp (1) = e =
2,71828182
La sintaxis es math.exp (nmero)
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 funcin Fix
La funcin de correccin trunca la parte decimal de un nmero positivo y devuelve el mayor
entero menor que el nmero. Sin embargo, cuando el nmero es negativo, volver nmero
entero ms pequeo mayor que el nmero. 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 funcin Int
La Int es una funcin que convierte un nmero en un entero truncando su parte decimal y el
entero resultante es el mayor entero que es menor que l nmero. 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 funcin de registro
La funcin de registro es la funcin que devuelve el logaritmo natural de un nmero. 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 () Funcin
Vta es una funcin muy til en Visual Basic 2012. Usamos el funciton Vta escribir cdigo que
involucra el azar y probabilidad. La funcin Rnd devuelve un valor aleatorio entre 0 y 1.
nmeros aleatorios en su forma original no son muy tiles en la programacin hasta que los
convertimos a enteros. Por ejemplo, si tenemos que obtener una salida aleatoria de 6 nmeros
enteros de 1 a 6, lo que hace que el programa se comporte como un dado virtuales,
necesitamos convertir los nmeros al azar a nmeros enteros utilizando la frmula 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 funcin Int
trunca la parte decimal del nmero aleatorio y devuelve un entero. Despus de aadir 1,
obtendr un nmero aleatorio entre 1 y 6 cada vez que hace clic en el botn de comando. Por
ejemplo, vamos a decir que el nmero aleatorio generado es de 0,98, despus de multiplicar
por 6, se convierte en 5,88, y el uso de la funcin Int nmero entero (5.88) se convertir el
nmero a 5; y despus de la adicin 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 funcin de Ronda
La funcin de Ronda es la funcin que redondea un nmero a un nmero determinado de
decimales. El formato es redonda (n, m) lo que significa para redondear un nmero 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 matemticas aqu indica que la funcin Round pertenecen a la clase Math.
[Lesson 13] << [CONTENTS] >> [Lesson 15]

Visual Basic 2012 Lesson 15 Functions Part IV- Formatting
Functions
Visual Basic 2012 Leccin 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 funcin de formato en Visual Basic 2012 es una funcin de formato muy potente. Se utiliza
para mostrar los valores numricos 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 funcin de formato predefinido se
Formato (n, "el argumento de estilo")
donde n es un nmero.
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
argument
Explanation Example
General
Number
To display the number
without having separators
between thousands.
Format(8972.234,
General
Number)=8972.234
Fixed To display the number
without having separators
between thousands and
rounds it up to two decimal
places.
Format(8972.2,
Fixed)=8972.23
Standard To display the number with
separators or separators
between thousands and
rounds it up to two decimal
places.
Format(6648972.265,
Standard)=
6,648,972.27
Currency To display the number with
the dollar sign in front, has
separators between
thousands as well as rounding
it up to two decimal places.
Format(6648972.265,
Currency)=
$6,648,972.27
Percent Converts the number to the
percentage form and displays
a % sign and rounds it up to
two decimal places.
Format(0.56324,
Percent)=56.32 %
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, users 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 funcin 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, todava 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 Leccin 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", tambin 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
Adems de utilizar los formatos predefinidos, tambin puede utilizar las funciones de formato
definidas por el usuario. La sintaxis general de una fecha para la definida por el usuario / hora
Format (expresin, 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
Bsica 2012 Leccin 17-Uso de casilla de verificacin
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 verificacin es un control muy til en Visual Basic 2012 Permite al usuario
seleccionar uno o ms elementos marcando la casilla de verificacin o casillas de verificacin
de que se trate. Por ejemplo, en el cuadro de dilogo Fuente de cualquier editor de texto de
Microsoft como FrontPage, hay muchas casillas de verificacin en la seccin de efectos, tales
como la que se muestra en el siguiente diagrama. El usuario puede elegir subrayado,
subndice, versalitas, superndice, parpadeo, etc En Visual Basic 2012, puede crear un carrito
de compras en el que el usuario puede hacer clic en las casillas de verificacin
correspondientes a los elementos que tengan la intencin 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 cdigo 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 cdigo 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 seleccin del
usuario al marcar la casilla de verificacin particular, es similar al evento clic. la declaracin
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)
Tambin mantendr el tipo de fuente original, pero cambiar a caracteres normales. (Los otros
estados emplean la misma lgica)


* 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", tambin 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 Leccin 18 - El uso del botn 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.
Botn de radio es tambin un control muy til en Visual Basic 2012. funciona de forma
diferente a partir de las casillas de verificacin. Mientras que las casillas de verificacin
trabajar de forma independiente y permiten al usuario seleccionar uno o ms elementos,
botones de radio son mutuamente excluyentes, lo que significa que el usuario slo puede
elegir una opcin slo de una serie de opciones. He aqu un ejemplo que permite al usuario
seleccionar un solo color.



The Code: El cdigo
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 slo puede seleccionar un elemento a la vez, se puede hacer ms de una
seleccin, si esos elementos pertenecen a diferentes categoras. Por ejemplo, el usuario
desea elegir la camiseta tamao y color, que necesita para seleccionar un color y una talla, lo
que significa una seleccin en cada categora. Esto se consigue fcilmente en Visual Basic
2012 utilizando el control Cuadro de grupo en las categoras contenedores.
Bajo el bsico 2012 IDE Visual, despus 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. Slo los botones de opcin 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 cdigo
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 Leccin 19 - Creacin 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, isnt 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.
Bsicamente todo el mundo le gusta navegar por Internet utilizando navegadores web
producidos comercialmente como el Internet Explorer producida por Microsoft o los
navegadores de cdigo abierto diseado por los expertos como Firefox, Opera y el ms
reciente de Chrome creado por Google. Sin embargo, no es que se enfre 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 fcil tambin. En este captulo, te voy a mostrar
cmo 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 slo 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 tamao a 640.480. Despus, usted
necesita para aadir 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 tamao a 600.400. A continuacin, arrastre un cuadro de texto y colquelo en


la parte superior del control WebBrowser, esta ser la barra de direcciones, donde el usuario puede
introducir la URL. Por ltimo, coloque un botn de comando al lado del cuadro de texto y etiquetarlo
como Go y cambiar su nombre para ir tambin. El diseo de la interfaz se muestra a continuacin:

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 cdigo para el navegador web es sorprendentemente simple, slo es una sola lnea de
cdigo! Haga doble clic en el botn Ir y escriba el siguiente cdigo:
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 botn Go. Usted ser
capaz de navegar por cualquier pgina web que desee.
Figura 19.2: La interfaz en tiempo de ejecucin


Visual Basic 2012 Lesson 20 Errors Handling
Visual Basic 2012Leccin 20- Gestin 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 Introduccin a la gestin de errores en Visual Basic 2012
El manejo de errores es un procedimiento esencial en la programacin de Visual Basic 2012,
ya que ayuda a hacer sin errores de un programa. Cdigo libre de errores, no slo permite a
los programas para funcionar sin problemas y eficientemente, sino que tambin 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 podra cometer el error de tratar de introducir texto (string) a una caja que est
diseado para manejar slo valores numricos tales como el peso de una persona, el equipo
no ser capaz de realizar clculo aritmtico para el texto, por lo tanto lo har crear un error.
Estos errores se conocen como errores sncronos.
Por lo tanto un buen programador debe estar ms alerta a las partes del programa que
podran provocar errores y debe escribir los errores de manipulacin de cdigo para ayudar al
usuario en el manejo de los errores. Escribir los errores de manipulacin de cdigo es una
buena prctica para los programadores de Visual Basic 2012, as que no trate de terminar un
programa rpido al omitir los errores de manejo de cdigo. Sin embargo, no debera haber
demasiados errores de manipulacin de cdigo en el programa, ya que crea problemas para el
programador para mantener y solucionar problemas del programa ms adelante.
Visual Basic 2012 ha mejorado mucho en su base de errores capacidades de manejo en
comparacin con Visual Basic 6 Por ejemplo, cuando el usuario intenta dividir un nmero por
cero, Vb2012 no devolver un mensaje de error, pero da el 'infinito' como el contestar (aunque
esto es matemticamente 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 todava admite los errores VB6 manejo de la sintaxis, que es el On Error
GoTo estructura program_label. Aunque tiene un mtodo ms avanzado de manejo de
errores, nos ocuparemos de que later.We ahora deber aprender a escribir los errores de
manipulacin de cdigo en Visual Basic 2012 La sintaxis de los errores de manipulacin es
On Error GoTo program_label
donde program_label es la seccin del cdigo que est diseado por el programador para
gestionar el error cometido por el usuario. Una vez que se detecta un error, el programa
saltar a la seccin 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 textOne 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: Divisin por cero
En este ejemplo, vamos a tratar con el error de introducir datos no numricos en los cuadros
de texto que suponen para contener valores numricos. El program_label aqu es
error_hanldler. cuando el usuario introduce un valor no numrico en los cuadros de texto, el
mensaje de error se mostrar el texto "Una de las entradas no es un nmero! Intntalo de
nuevo! ". Si no se produce ningn error, se mostrar la respuesta correcta. Prubelo usted
mismo.
The Code El cdigo
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 TryCatchEnd Try structure.
The structure looks like this
20.3 Errores de manipulacin utilizando Try ... ..Catch ... .End Trate Estructura
VB2012 ha adoptado un nuevo enfoque en el manejo de errores, o ms bien el manejo de
excepciones. Se supone que es ms eficiente que el viejo mtodo 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
TryCatchEnd 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 modificacin del Ejemplo 20.1. En lugar de utilizar On Error GoTo mtodo, se
utiliza el mtodo Try Try ... Catch ... End. En este ejemplo, la instruccin Catch se captura la
excepcin cuando el usuario introduce un conjunto de datos no numricos y devolver el
mensaje de error. Si no hay excepcin, no habr ninguna accin de la declaracin de capturas
y el programa devuelve la respuesta correcta.
el cdigo
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 Leccin 21- Grficos Gestin Conceptos bsicos
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 dont have much
choices in creating customized drawings.
21.1 Introduccin
La gestin de grficos es fcil 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 slo tiene que arrastrar
los controles de la forma en la forma de crear rectngulo, cuadrado, elipse, crculo y ms. Sin
embargo, su simplicidad tiene las deficiencias, no tienes muchas opciones en la creacin 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 programacin orientada a objetos en el marco VB.net, forma a los controles ya no estn
disponibles. Ahora el programador necesita escribir cdigo para crear diferentes formas y dibujos. A pesar de que la curva de aprendizaje es empinada,
el programador puede escribir poderoso cdigo para crear todo tipo de grficos. Usted puede incluso disear 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 grficas que permiten a los programadores a escribir cdigo que puede dibujar todo tipo
de formas e incluso fuentes. En esta leccin, usted aprender cmo escribir cdigo para dibujar lneas 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 Creacin de un objeto de Grficos
Antes de que pueda dibujar cualquier cosa en un formulario, es necesario crear el objeto
Graphics en Bsico 2012. Un objeto grfico visual se crea usando un mtodo ()
CreateGraphics. Puede crear un objeto grfico que dibuja a la forma en s o un control. Por
ejemplo, si desea llamar a la forma, puede utilizar la siguiente declaracin:
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 grfico para dibujar a un PictureBox, puede escribir la siguiente
declaracin:
Dim myGraphics As Graphics = PictureBox1.CreateGraphics
You can also use the textbox as a drawing surface, the statement is:
Tambin puede utilizar el cuadro de texto como superficie de dibujo, la declaracin 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 mtodos del
objeto Graphics. Adems, es necesario crear el objeto Pen como la herramienta de dibujo.
Vamos a examinar el cdigo que puede crear una pluma en la siguiente seccin.



21.2 Creating a Pen
A Pen can be created using the following code:
21.2 Creacin de una pluma
Una pluma puede ser creado usando el siguiente cdigo:
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 lnea de dibujo y el segundo
argumento define el ancho de la lnea de dibujo.
Tambin puede crear un Pen con la siguiente declaracin:
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 lnea de dibujo.
Despus de haber creado los grficos y los objetos Pen, que ahora est listo para dibujar
grficos 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 seccin, le mostraremos cmo dibujar una lnea recta en el formulario.
En primer lugar, iniciar Visual basic 2012 Express. En la pgina de inicio, arrastre un botn en
el formulario. Haga doble clic en el botn e introduzca el siguiente cdigo.
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 lnea de crear el objeto Pen. El quinto
dibujar una lnea en el formulario utilizando el mtodo 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 lnea de coordenadas, la cuarta y los ltimos argumentos definen el fin de
coordinar de la lnea. 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 continuacin:



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

Visual Basic 2012 Lesson 22 Managing Graphics -Drawing Rectangle
Visual Basic 2012 Leccin 22-Manejo de Grficos-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 cmo crear los grficos y la pluma objetos para dibujar lneas rectas en
Visual Basic 2012 en la leccin anterior. Ahora vamos a aprender a dibujar diferentes formas,
tales como rectngulo, cuadrado, elipse y el crculo.
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 corners 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 Creacin de rectngulos
Para dibujar un rectngulo en la pantalla en Visual Basic 2012, hay dos maneras:
(i) La primera manera es dibujar un rectngulo directamente utilizando el mtodo
DrawRectangle especificando coordenadas de su esquina superior izquierda y anchura y
altura. Tambin es necesario crear una grfica y un objeto Pen para manejar el dibujo actual.
El mtodo para dibujar el rectngulo 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.
Dnde 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
vlidos y significativos. X, Y es la coordenada de la esquina superior izquierda del rectngulo
mientras que la anchura y altura son autoexplicativo, es decir, la anchura y la altura del
rectngulo.
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 tringulo
usando el mtodo DrawRectangle. La sintaxis es como se muestra a continuacin:
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 cdigo para crear un objeto rectangtle es como se muestra a continuacin:
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:
Tambin puede crear un objeto de rectngulo con un cdigo de una lnea de la siguiente
manera:
Dim myRectangle As New Rectangle(X,Y,width, height)
and the code to draw the above rectange is
y el cdigo para dibujar la rectange anterior es
myGraphics.DrawRectangle(myPen, myRectangle)
The sample code is shown below:
A continuacin se muestra el cdigo 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 Personalizacin de Estilo de lnea del objeto Pen
La forma nos acercamos hasta ahora se dibujan con lnea continua, en realidad podemos
personalizar el estilo de lnea del objeto Pen para que hemos salpicado lnea, la lnea que
consiste en guiones y ms. Por ejemplo, a continuacin se muestra la sintaxis para llamar a la
lnea 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 lnea en particular, una lnea que
compone de puntos aqu. El siguiente cdigo dibuja un rectngulo con lnea 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 lnea 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 Leccin 23 al Gerente Grficos -Dibujo Elipse y
crculo
[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 cmo dibujar rectngulos con diferentes estilos de lnea en Visual Basic
2012 en la leccin anterior. Ahora vamos a aprender a dibujar elipse y el crculo.
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 detrs de dibujar una elipse en Visual Basic
2012 La estructura bsica de la mayora de las formas es un rectngulo, elipse no es una
excepcin. Elipse es una forma oval que est delimitado por un rectngulo, como se muestra a
continuacin:

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 rectngulo sirve como un rectngulo de delimitacin de la elipse.
Todava tenemos que utilizar el mtodo drawEllipse para terminar el trabajo. Por otro
lado, tambin podemos dibujar una elipse con el mtodo drawEllipse sin crear
primero un rectngulo. 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 mtodo, Digamos que usted ha creado un objeto rectangular conocida como
myRectangle y un objeto lpiz como myPen, a continuacin, se puede dibujar una elipse con
la siguiente declaracin:
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 tambin ya creado el objeto Graphics myGraphics.
El siguiente es un ejemplo del cdigo 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 mtodo utiliza el mtodo drawEllipse sin crear un objeto de rectngulo. Offcourse
usted todava tiene que crear los grficos 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 rectngulo 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 cdigo 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)
Despus de haber aprendido a dibujar una elipse, dibujando un crculo se hace muy simple.
Utilizamos exactamente los mismos mtodos utilizados en la seccin anterior, pero modificar
la anchura y altura de modo que sean de los mismos valores.
Los siguientes ejemplos se basan en el mismo crculo.
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 Leccin 24 Managing Grficos -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 lets 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 cmo dibujar rectngulo, elipse y el crculo en visual basic 2012 en los
captulos anteriores, ahora vamos a aprender a dibujar texto en la pantalla. S, en lugar de
utilizar el comando de impresin, tambin 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 mtodo DrawString. El formato es el
siguiente:
myGraphics.DrawString (myText, myFont, MyBrush, X, Y)
Dnde myGraphics se oponen los grficos, 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 declaracin:
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
tamao de la fuente. Usted puede agregar un tercer argumento como estilo de fuente, ya sea
negrita, cursiva, subrayado. Aqu estn 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 dont 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:
Adems de los siete colores, algunas de las Cepillo Colores comunes son Aliceblue,
AquaMarine Beige, DarkMagenta, DrarkOliveGreen, SkyBlue y ms. Usted no tiene que
recordar los nombres de todos los colores, el IntelliSense le permitir navegar a travs de los
colores en un men desplegable, una vez que escribe el punto despus de la palabra en color.
Ahora procederemos a dibujar el tipo de letra utilizando el cdigo 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 dont 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 lnea en el ejemplo anterior con esta lnea (tendr que borrar las lneas que
crean el cepillo y objetos de la fuente tambin)
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
Tambin puede agregar un InputBox que dejar que el usuario introduzca su mensaje a
continuacin, 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 Leccin 25-Gerente Grficos -Dibujo
Polgono y Pie
[Lesson 24] << [CONTENTS] >> [Lesson 26]
We have learned how to draw rectangle, ellipse ,circle and text in the preceding chapters, now
lets learn how to draw polygons on the screen. Besides that, we shall also learn how to draw
pie.
Hemos aprendido cmo dibujar rectngulo, elipse, crculo y el texto en los captulos anteriores,
ahora vamos a aprender a dibujar polgonos en la pantalla. Adems de eso, vamos a aprender
tambin cmo 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 polgonos
Polgono es una figura plana cerrada delimitada por tres o ms lados rectos. Para dibujar un
polgono en la pantalla, tenemos que definir las coordenadas de todos los puntos (tambin
conocidos como vrtices) que se unieron para formar la pollygon.
La sintaxis para define los puntos de un polgono con vrtices 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:
Despus 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 grfico y utilizar el mtodo drawPolygon para dibujar el polgono
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 tringulo
Un tringulo es un polgono con tres vrtices. Aqu est el cdigo 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 cuadriltero
Un cuadriltero es un polgono formado por cuatro lados, por lo que necesita para definir
cuatro vrtices. El siguiente es el cdigo:
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 continuacin:

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 mtodo DrawPie del objeto grfico. Como siempre, es
necesario crear los grficos 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 rectngulo delimitador, otros argumentos son fciles de
entender. Tanto startAngle y SweepAngle se miden en grados. SweepAngle puede tener
posibles o negativos valores. Si el valor es positivo, barrer a travs de las agujas del reloj
mientras negativo significa que barren a travs de direccin hacia la izquierda.
Ejemplo 25.3: Dibujar un pastel que se inicia con 0 grados y barrer las agujas del reloj a travs
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 continuacin:

[Lesson 24] << [CONTENTS] >> [Lesson 26]


Visual Basic 2012 Lesson 26 Managing Graphics-Filling
Shapes with Color
Visual Basic 2012 Leccin 26- Formas Gestin de Grficos-
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 dont 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 cmo dibujar rectngulo, elipse, crculo,
polgono y pastel con slo esbozos. En esta leccin, vamos a mostrarle cmo llenar las formas
con el color, o simplemente formas slidas. Tres mtodos 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)
Dnde myColor puede ser de cualquier color como el rojo, azul, amarillo y ms. Usted no tiene
que preocuparse acerca de los nombres de los colores porque el IntelliSense mostrar los
colores y entrar en el perodo despus 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 rectngulo
La sintaxis para llenar un rectngulo con el color definido por el objeto cepillo es:
myGraphics.FillRectangle (MyBrush, 0, 0, 150, 150)
El cdigo 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 continuacin:



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 cdigo 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 continuacin:



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 polgono
La sintaxis para llenar un polgono con el color definido por el objeto cepillo es:
myGraphics.FillPolygon (MyBrush, myPoints)
El cdigo 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 cdigo 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 Leccin 27-Utilizacin 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 leccin, vamos a mostrarle cmo 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 cronmetro, un dado, animacin y mucho ms.
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 Creacin 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 slo es utilizado por el
desarrollador, es invisible en tiempo de ejecucin 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 aplicacin para Windows. Puede dar al proyecto cualquier nombre que
desee, pero vamos a nombrarla MyClock. Cambie el ttulo del Form1 para MyClock en la
ventana de propiedades. Ahora agregue el control Timer al formulario arrastrndolo desde la
caja de herramientas. A continuacin, inserte un control de etiqueta en el formulario. Cambiar
el tamao de fuente de la etiqueta a 14 o cualquier tamao que quieran, y establecer la
alineacin de fuente para ser centro medio. Antes de que nos olvidemos, pondrs tambin 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 codificacin. En realidad sera una sorpresa que lo que usted
necesita para crear un reloj es slo un cdigo de una sola lnea, es decir:
Label1.Text = TimeOfDay
Para realmente crear el reloj, haga clic en el control Timer e introduzca el cdigo de seguridad,
como se muestra a continuacin:
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 continuacin:



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 Creacin de un cronmetro
Podemos crear un cronmetro simple utilizando el control Timer. Inicie un nuevo proyecto y el
nombre del cronmetro. Cambie el ttulo Form1 para Cronmetro. Inserte el control Timer en el
formulario y establezca su intervalo de 1000 que es igual a un segundo. Tambin 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 cdigo 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 cronmetro es como se muestra a continuacin:



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 Creacin de un Dice digital
Podemos crear un dado digitales fcilmente utilizando el control Timer. Para crear un dado,
que necesita para generar nmeros al azar utilizando la funcin Rnd. Vta genera nmeros
entre 0 y 1 La declaracin
n = Int (1 + Rnd () * 6)
genera nmeros enteros de 1 a 6 azar.
En el cdigo, se introduce la variable m para controlar la longitud de tiempo del proceso de
laminacin. 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 continuacin:
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 nmeros cambiando rpidamente que paran en
un nmero determinado. La interfaz se muestra a continuacin:

[Lesson 26] << [CONTENTS] >> [Lesson 28]

Visual Basic 2012 Lesson 28 Creating Animation
Visual Basic 2012 Leccin 28- Creacin 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 programacin diseado para la
creacin de otras aplicaciones comerciales e industriales y no para la creacin de animacin,
que puede ser utilizado para crear la animacin. En esta leccin, 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 seccin, le mostraremos cmo mover un objeto pulsando un botn de comando. Es
necesario hacer uso de las propiedades Top y Left de un objeto para crear la animacin. La
propiedad Top define la distancia del objeto desde la frontera ms superior de la pantalla,
mientras que la propiedad Left define la distancia del objeto desde la izquierda borde de la
pantalla. Mediante la adicin o sustraccin de la distancia del objeto podemos crear el efecto
animado de un objeto en movimiento.
Inicie un nuevo proyecto y el nombre como objeto mvil, o cualquier nombre que desee. Ahora
insertar un cuadro de imagen y en su importacin Propiedad de la imagen de una imagen de
su disco duro u otras fuentes. Luego, inserte cuatro botones de comando, cambiar sus ttulos
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 cdigo:
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.
explicacin:
Cada vez que el usuario hace clic en el botn Mover hacia abajo, la distancia de los
PictureBox se incrementa en 10 pxeles desde el borde superior, la creacin de un movimiento
hacia abajo. Por otro lado, cada vez que el usuario hace clic en el botn Mover hacia arriba, la
distancia de la PictureBox disminuye por 10 pxeles desde la parte superior de las fronteras,
creando as un movimiento hacia arriba. Adems, cada vez que el usuario hace clic en el
botn Mover Izquierda, la distancia de la PictureBox disminuye por 10 pxeles desde el borde
izquierdo, creando as un movimiento hacia la izquierda. Por ltimo, cada vez que el usuario
hace clic en el botn Mover a la derecha, la distancia de los PictureBox se incrementa en 10
pxeles desde el borde izquierdo, creando as un movimiento hacia la derecha.




The interface is shown below: La interfaz se muestra a continuacin:



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 Creacin de animaciones utilizando Timer
Podemos crear animacin continua usando temporizador sin necesidad de hacer clic
manualmente un botn de comando. Podemos crear izquierda a derecha o de arriba a abajo el
movimiento al escribir el cdigo 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 montn 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 ttulo 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 cdigo:
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 cdigo 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 aade un valor de 10 a la
distancia del cuadro de imagen desde el borde izquierdo cada vez que la seal 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 botn para detener el movimiento. El cdigo 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 botn de comando e introduzca el siguiente
cdigo:
Timer1.Enabled = True
The Image of the Animation program is shown below: La imagen del programa de animacin se muestra a continuacin:



[Lesson 27] << [CONTENTS] >> [Lesson 29]

Visual Basic 2012 Lesson 29- Working with Databases Part 1
Visual Basic 2012 Leccin 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 Introduccin a la base de datos en Visual Basic 2012
En nuestra vida diaria, nos ocupamos de muchos tipos de informacin o datos tales como
nombres, direcciones, el dinero, la fecha, cotizaciones de bolsa, estadsticas y mucho ms. Si
ests en el negocio o trabajar como un profesional, usted tiene que manejar ms datos. Por
ejemplo, un mdico tiene que realizar un seguimiento de la informacin personal y mdica de
los pacientes, tales como nombres, direcciones, nmeros de telfono, as como lecturas de la
presin arterial, las lecturas de azcar en la sangre, antecedentes quirrgicos, medicamentos
prescritos en el pasado y ms. 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 gestin 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 rpido medio ambiente mundial y la edad
de la informacin, ya no es viable para gestionar los datos de forma manual. La mayora de los
datos ahora se gestionan mediante sistemas de gestin de bases de datos basadas en la
informtica. Sistemas de gestin de bases de datos basados en computadoras pueden
manejar datos mucho ms rpidas y ms eficientes que los seres humanos hacen. Con la
llegada de la red y las tecnologas de Internet, los datos se pueden gestionar de forma local y
remota. Las empresas suelen invertir fuertemente en sistemas de gestin de bases de datos
con el fin de ejecutar las organizaciones de manera eficiente y eficaz. Sistemas de gestin de
bases de datos se utilizan por lo general en el funcionamiento de sistema de nmina, sistema
de inventarios, sistema, sistema de pago, sistema de gestin de rdenes, sistema de gestin
de relaciones con clientes (CRM) y ms que representan. Algunos de los sistema de gestin
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 Creacin de una aplicacin de base de datos en Visual Basic 2012
Un sistema de gestin de base de datos se ocupa tpicamente con almacenar, modificar y
extraer informacin de una base de datos. Tambin puede agregar, editar y eliminar registros
de la base de datos. Sin embargo, un DBMS puede ser muy difcil de manejar por la gente
comn o los hombres de negocios que no tienen antecedentes tecnolgicos.
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 Microsofts 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 tecnologa de base de datos
de Microsoft que puede trabaja con muchos otros sistemas de gestin de bases de datos avanzadas, como
Microsoft SQL Server. En esta leccin, vamos a desarrollar cdigos 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 conexin 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 forms 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 continuacin, 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 navegacin y la manipulacin
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 continuacin, seleccione Proyecto de base de datos 1 propiedades para mostrar las
propiedades del proyecto. Siguiente, haga clic en la pestaa 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, asegrese system.data, System.Data.SQLClient se
seleccionan, de lo contrario los revise. Habiendo hecho esto usted necesita hacer clic en el
botn Guardar todo en la barra de herramientas y luego regresar a la base 2012 IDE Visual.
Se procede a crear la conexin con el archivo de origen de base de datos en la siguiente
leccin.
[Lesson 28] << [CONTENTS] >> [Lesson 30]

Visual Basic 2012 Lesson 30- Working with Databases Part 2
Visual Basic 2012 Leccin 30 Cmo 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, lets 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 Creacin de la conexin a una base de datos usando ADO.NET

En Visual Basic 2012, tenemos que crear la conexin 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 extensin mdf. Vamos a
llamar a este archivo de base de datos como test.mdf. Despus 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 conexin como OleDbConnection, SqlConnection y
ms. 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

Despus de haber creado la instancia del objeto SqlConnecton, el siguiente paso es
establecer una conexin 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.

Despus de establecer la conexin 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 conexin 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 aadimos objetos ms relevantes y escribir los cdigos pertinentes para el proyecto.
El siguiente paso es crear una instancia de la SqlDataAdpater en nuestro cdigo para que
podamos llenar el DataTable con los datos del origen de datos. Adems, tambin es necesario
para crear una instancia de la DataTable. Aparte de eso, tambin se debe crear una instancia
de theSqlCommandBuilder que se utiliza para manipular los datos, tales como la actualizacin
y supresin 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 users current row within the
data table. The statement is
Adems de eso, tenemos que declarar una variable para realizar un seguimiento de la fila
actual del usuario dentro de la tabla de datos. La declaracin 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:
Despus 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:
Despus de llenar el DataTable, tenemos que escribir cdigo 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 travs 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 cdigo 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 cmo manipular los datos en la siguiente leccin.
[Lesson 29] << [CONTENTS]>> [Lesson 31]

Visual Basic 2012 Lesson 31: Working with Databases Part 3
Visual Basic 2012 Leccin 31: Cmo 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 cmo 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 manipulacin de los datos significa aadir registros de
usuarios, la edicin de registros, eliminar registros, registros de navegacin y mucho ms.
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 buttons text << to indicate to the
user that it is the button to move to the first record and buttons text >> to move to the last record. Besides
we can use buttons text < for moving to previous record and buttons text > for moving to next record.
En la leccin anterior, hemos aprendido cmo mostrar el primer registro, usando el procedimiento
showRecords sub. En esta leccin, vamos a crear botones de comando y escribir cdigos pertinentes para
permitir al usuario navegar por los registros hacia adelante y hacia atrs, as como el avance rpido hasta el
ltimo registro y volver al primer botn record.The primero tenemos que crear es para el usuario navegar por
el primer registro. Podemos utilizar el texto del botn << para indicar al usuario que es el botn para
desplazarse al primer registro y el texto del botn >> para mover al ltimo registro. Adems podemos utilizar
el texto del botn <para mover al registro anterior y el texto del botn> para mover al siguiente registro.


The code for moving to the first record is: El cdigo para moverse al primer
registro es:
MyRowPosition = 0


Me.showRecords()
The code for moving to previous record is: El cdigo para mover al rcord
anterior es:
If MyRowPosition > 0 Then
MyRowPosition = MyRowPosition 1
Me.showRecords()
End If
The code for moving to next record is:

El cdigo 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 cdigo 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 Edicin, guardar, aadir 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 despus de la edicin de ellos. Es necesario utilizar
el mtodo de actualizacin del SqlDataAdapter para guardar los datos. El cdigo 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 :
Tambin puede agregar nuevo registro o una nueva fila a la tabla usando el siguiente cdigo:
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 cdigo 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
botn 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 podra querer borrar los datos. El cdigo 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 Bsico base de datos de 2012 se muestra a continuacin:

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 cmo crear una aplicacin 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 electrnico escrito por el webmaster de nuestro
Tutorial de Visual Basic 2010, Dr.Liew. Con ms de 200 pginas de contenido, que
complementa nuestro tutorial en lnea 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 bsicos de programacin Visual Basic 2010
Crear sus propios programas VB2010 desde el principio
Obtener la programacin de las ideas de muchos programas de ejemplo interesantes.
Modificar los cdigos fcilmente para adaptarse a sus necesidades.
Aprenda cmo 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 pgina
despus 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 estn asociados, afiliados,
avalados o patrocinados por Microsoft, ni han sido revisados probado o certificado por
Microsoft.
Informacin del contacto
Si usted requiere asistente y soporte tcnico, por favor correo electrnico
admin@vbtutor.net

Das könnte Ihnen auch gefallen