Visual Basic 2012 Tutorial PDF
Visual Basic 2012 Tutorial PDF
Visual Basic 2012 is the latest version of Visual Basic launched by Microsoft in 2012. Visual
Basic 2012 is almost similar to Visual Basic Express 2010 and Visual Basic 2008, but it has
added many new features. The most distinct difference is that Visual Basic 2012 no more
comes as a stand alone program, it is now integrated with other Microsoft Programming
languages C# and C++ in a package called Visual Studio 2012. Start learning Visual Basic
2012 by clicking the topics listed under contents:
Visual Basic 2012 es la última versión de Visual Basic lanzado por Microsoft en 2012 Visual Basic 2012 es
casi similar a Visual Basic Express 2010 y Visual Basic 2008 , pero se ha añadido muchas características
nuevas. La diferencia más clara es que Visual Basic 2012 no más se presenta como un programa
independiente , que ahora está integrado con otros lenguajes de Microsoft de programación C # y C ++ en un
paquete llamado Visual Studio 2012 Empieza a aprender Visual Basic 2012 haciendo clic en los temas
enumerados en el contenido :
CONTENTS
Lesson 1- Introduction
If you wish to learn more about Visual Basic 2012, you can download our E-Book, Visual Basic 2010 Made
Easy ,written by our webmaster and tutor Dr.Liew . Although it is about Visual Basic 2010, the concepts are nearly
similar to Visual Basic 2012, only with very slight variations. With more than 200 pages of contents and many hands
on examples, you should be able to master the basics of VB2010 and VB2012 quickly. This book can also be used as a
textbook for classroom learning. Click on the book image below for more information.
Si desea obtener más información acerca de Visual Basic 2012, puede descargar nuestro E-Book, Visual Basic 2010
Made Easy, escrito por nuestro webmaster y Dr.Liew tutor. Aunque se trata de Visual Basic 2010, los conceptos son
casi similares a Visual Basic 2012, sólo con variaciones muy leves. Con más de 200 páginas de contenidos y muchas
manos en ejemplos, usted debería ser capaz de dominar los fundamentos de la VB2010 y VB2012 rápidamente. Este
libro también puede ser utilizado como libro de texto para el aprendizaje en el aula. Haga clic en la imagen del libro
ISBN-13: 978-1467975193
Visual Basic Express 2012 is the latest version of Visual Basic launched by
Microsoft in 2012. Visual Basic Express 2012 is almost similar to Visual Basic
Express 2010 and Visual Basic 2008, but it has added many new features. The
most distinct difference is that Visual Basic Express 2012 no more comes as a
stand alone program, it is now integrated with other Microsoft Programming
languages C# and C++ in a package called Visual Studio 2012. Further, Visual
Studio Express 2012 now come in five editions, they are:
Visual Basic Express 2012 es la última versión de Visual Basic lanzado por Microsoft en 2012
de Visual Basic Express 2012 es casi similar a Visual Basic Express 2010 y Visual Basic 2008,
pero se ha añadido muchas características nuevas. La diferencia más clara es que Visual
Basic Express 2012 no más se presenta como un programa independiente, que ahora está
integrado con otros lenguajes de Microsoft de programación C # y C ++ en un paquete
denominado Además Visual Studio 2012, Visual Studio Express 2012 ahora viene en cinco
ediciones , ellos son:
Right now we shall concentrate on learning Visual Basic 2012 Express for Windows Desktop , so you
will need to download the free software from Microsoft site below:
Ahora nos concentraremos en aprender Visual Basic 2012 Express para Windows de escritorio, por lo
que tendrá que descargar el software gratuito de Microsoft en la siguiente lista:
http://www.microsoft.com/en-us/download/details.aspx?id=34673
Like Visual Basic Express 2010 and Visual Basic Express 2008 , Visual Basic Express 2012 is
also a full fledged Object-Oriented Programming(OOP) Language, so it has caught up with
other OOP languages such as C++, Java,C# and others.
The Integrated Development Environment when you launch VB2012 Express is shown in the
diagram below.
Al igual que Visual Basic Express 2010 y Visual Basic 2008 Express, Visual Basic Express
2012 es también una programación completa orientada a objetos hecha y derecha (POO)
Idioma, por lo que ha puesto al día con otros lenguajes de POO como C ++, Java, C # y otros.
El entorno de desarrollo integrado al iniciar VB2012 Express se muestra en el siguiente
diagrama.
Figure 1.1: Visual Studio 2012 Start Page Figura 1.1: Visual Studio 2012 Página de inicio
To start a new Visual Studio Express 2012 project, simply click on New Project to launched
The Visual Studio New Project page as shown below:
Para iniciar un nuevo proyecto de Visual Studio Express 2012, simplemente haga clic en
Nuevo proyecto para lanzar la página Visual Studio Nuevo proyecto, como se muestra a
continuación:
Figure 1.2: Visual Studio 2012 Project Page Figura 1.2: Visual Studio 2012 Página del
proyecto
The New Project Page comprises three templates, Visual Basic, Visual C# and Visual C++.
Since we are going to learn Visual Basic 2012, we shall select Visual Basic. Visual Basic 2012
offers you four types of projects that you can create. As we are going to learn to create
windows Applications, we will select Windows Forms Application.
At the bottom of this dialog box, you can change the default project name
WindowsApplication1 to some other name you like, for example, MyFirstProgram. After you
have renamed the project, click OK to continue. The following IDE Windows will appear, it
is similar to Visual Basic 2010. The Toolbox is not shown until you click on the Toolbox
tab.When you click on the Toolbox tab, the common controls Toolbox will appear.
La página Nuevo proyecto comprende tres plantillas, Visual Basic, Visual C # y Visual C ++.
Ya que vamos a aprender Visual Basic 2012, vamos a seleccionar Visual Basic. Visual Basic
2012 le ofrece cuatro tipos de proyectos que se pueden crear. Como vamos a aprender a
crear aplicaciones de Windows, seleccionaremos Aplicación de Windows Forms.
En la parte inferior de este cuadro de diálogo, puede cambiar el nombre del proyecto por
defecto WindowsApplication1 a algún otro nombre que te gusta, por ejemplo, MyFirstProgram.
Después de haber cambiado el nombre del proyecto, haga clic en Aceptar para continuar.
Aparecerá la siguiente IDE de Windows, que es similar a Visual Basic 2010, no se muestra el
cuadro de herramientas hasta que haga clic en el cuadro de herramientas tab.When hace clic
en la ficha Herramientas, aparecerá el cuadro de herramientas controles comunes.
Figure 1.3:Visual Basic 2012 IDE Figura 1.3: Visual Basic 2012 IDE
Visual Basic Express 2012 IDE comprises a few windows, the Form window , the Solution
Explorer window and the Properties window . It also consists of a toolbox which contains many
useful controls that allows a programmer to develop his or her VB programs. The toolbox is
shown in Figure 1.4.
Basic Express 2012 IDE Visual comprende algunas ventanas, la ventana del formulario, la
ventana Explorador de soluciones y la ventana Propiedades. También consta de una caja de
herramientas que contiene muchos controles útil que permite a un programador para
desarrollar sus programas en VB. La caja de herramientas se muestra en la Figura 1.4.
Figure 1.4: Visual Basic 2012 Toolbox Figura 1.4: 2012 Caja de herramientas
de Visual Basic
Now, we shall proceed to show you how to create your first program. First, change the text of
the form to My First Program in the properties window, it will appear as the title of the program.
Next, insert a button and change its text to OK. The design interface is shown in Figure 1.5
Ahora, procederemos a mostrar cómo crear su primer programa. En primer lugar, cambiar el
texto de la forma a mi primer programa en la ventana de propiedades, aparecerá como el título
del programa. A continuación, inserte un botón y cambiar su texto a Aceptar. La interfaz de
diseño se muestra en la Figura 1.5
Ahora haga clic en el botón OK para que aparezca la ventana de código y escriba el siguiente
comunicado entre Private Sub y End Sub procedimiento, como se muestra en la Figura 1.6:
The function MsgBox is a built-in function of Visual Basic 2012 and it will display the text
enclosed within the brackets.
Now you have created your first program, we shall learn more VB2012 programming
techniques in coming lessons.
El MsgBox función es una función integrada de Visual Basic 2012 y se mostrará el texto
encerrado entre corchetes.
Ahora que ha creado su primer programa, vamos a aprender más técnicas de programación
VB2012 en próximas lecciones.
[CONTENTS] >>[Lesson 2]
Visual Basic 2012 Lesson 2-Working with Controls
[Lesson 1]<< [CONTENTS] >> [Lesson 3]
Controls in Visual Basic 2012 are tools that can be placed in the form to perform various tasks.
We can use them to create all kinds of Windows applications. The diagram below shows the
toolbox that contains the controls of Visual Basic 2012. They are categorized into Common
Controls, Containers, Menus, Toolbars, Data, Components, Printings and Dialogs. At the
moment, we will focus on the common controls. Some of the most used common controls are
Button, Label, ComboBox, ListBox, PictureBox, TextBox etc.
To insert a control into your form in Visual Basic 2012 IDE, you just need to drag the control
from the toolbox and drop it into the form. You can reposition and resize it as you like. Let’s
examine a few programs that made use of Button, Label, TextBox , ListBox and PictureBox .
You don’t have to worry so much about the code yet because we will explain the program
syntax as you progress to later lessons.
Los controles en Visual Basic 2012 son herramientas que se pueden colocar en el formulario
para realizar diversas tareas. Podemos usarlas para crear todo tipo de aplicaciones de
Windows. El siguiente diagrama muestra la caja de herramientas que contiene los controles de
Visual Basic 2012 se clasifican en controles comunes, Contenedores, menús, barras de
herramientas, datos, Componentes, Impresiones y diálogos. Por el momento, nos centraremos
en los controles comunes. Algunos de los controles comunes más utilizados son Button, Label,
ComboBox, ListBox, PictureBox, TextBox etc
Para insertar un control en su forma en 2012 IDE de Visual Basic, sólo tiene que arrastrar el
control desde la caja de herramientas y soltarlo en el formulario. Puede volver a colocar y
cambiar el tamaño a su gusto. Vamos a examinar algunos programas que hacen uso de
Button, Label, TextBox, ListBox y PictureBox. Usted no tiene que preocuparse tanto por el
código todavía, porque vamos a explicar la sintaxis del programa a medida que avanza en
lecciones posteriores.
When you click on the Toolbox tab, the common controls Toolbox will appear.
2.1 Creating your first program 2.1 Creación del primer programa
To create your first program in Visual Basic 2012, drag the button control into the form, and
change its default Text Button1 to OK in the properties window, the word OK will appear on the
button in the form, as shown below:
Para crear su primer programa en Visual Basic 2012, arrastre el botón de control en el
formulario y cambie su texto por defecto Button1 a OK en la ventana de propiedades, la
palabra Aceptar aparecerá en el botón en el formulario, como se muestra a continuación:
Now click on the OK button and the code window appears. Enter the code as follows:
2.2 Using the Text Box 2.2 Cómo utilizar el cuadro de texto
Next I will show you how to create a simple calculator that adds two numbers using the
TextBox control. In this program, you insert two textboxes , three labels and one button. The
two textboxes are for the users to enter two numbers, one label is to display the addition
operator and the other label is to display the equal sign. The last label is to display the answer.
Siguiente te mostraré cómo crear una calculadora simple que suma dos números utilizando el
control TextBox. En este programa, inserte dos cuadros de texto, tres etiquetas y un botón.
Los dos cuadros de texto son para los usuarios introducir dos números, una etiqueta es
mostrar el operador de suma y la otra etiqueta es para mostrar el signo igual. La última
etiqueta es para ver la respuesta.
Now change the label on the button to Calculate,then click on this button and enter the
following code:
Ahora cambie la etiqueta del botón para calcular, a continuación, haga clic en este botón e
introduzca el siguiente código:
num1 = TextBox1.Text
num2 = TextBox2.Text
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.
Before writing an event procedure for a control in Visual Basic 2012 to response to a user’s
input or action, you have to set certain properties for the control to determine its appearance
and how it will work with the event procedure. You can set the properties of the controls in the
properties window of Visual Basic 2012 IDE at design time or at run time. Figure 3.1 is the
typical properties window for a form. It refers particularly to interface of the first program you
have learned in the previous lesson:
Antes de escribir un procedimiento de evento para un control en Visual Basic 2012 para
respuesta a la entrada o la acción de un usuario, hay que establecer ciertas propiedades del
control para determinar su aspecto y cómo se va a trabajar con el procedimiento de evento.
Puede establecer las propiedades de los controles en la ventana de propiedades de 2012 IDE
de Visual Basic en tiempo de diseño o en tiempo de ejecución. Figura 3.1 es la ventana de
propiedades típicas de un formulario. Se refiere en particular a la interfaz del primer programa
que has aprendido en la lección anterior:
Figure 3.1
Figure 3.2
The title of the form is defined by the Text property and its default name is Form 1. To change
the form’s title to any name that you like, simple click in the box on the right of the Text
property and type in the new name, in this example, the title is Addition Calculator. Notice that
this title will appear on top of the windows. In the properties window, the item appears at the
top part is the object currently selected (in Figure 3.1, the object selected is Form1). At the
bottom part, the items listed in the left column represent the names of various properties
associated with the selected object while the items listed in the right column represent the
states of the properties. Properties can be set by highlighting the items in the right column then
change them by typing or selecting the options available. You may also alter other properties of
the form such as font, location, size, foreground color, background color ,MaximizeBox,
MinimizeBox and etc. You can also change the properties of the object at runtime to give
special effects such as change of color, shape, animation effect and so on.
For example the following code will change the form color to yellow every time the form is
loaded. Visual Basic 2012 uses RGB(Red, Green, Blue) to determine the colors. The RGB
code for yellow is 255,255,0. Me in the code refer to the current form and Backcolor is the
property of the form’s background color. The formula to assign the RGB color to the form
is Color.FormArbg(RGB code). The event procedure is as follows:
El título del formulario se define mediante la propiedad Text y su nombre por defecto es la
Forma 1 Para cambiar de título del formulario a cualquier nombre que usted quiere, simple clic
en la casilla de la derecha de la propiedad Text y escriba el nuevo nombre, en este ejemplo, el
título es Calculadora de adición. Tenga en cuenta que este título aparecerá en la parte
superior de las ventanas. En la ventana de propiedades, el elemento aparece en la parte
superior es el objeto seleccionado en ese momento (en la Figura 3.1, el objeto seleccionado
es Form1). En la parte inferior, los elementos que aparecen en la columna de la izquierda
representan los nombres de varias propiedades asociadas con el objeto seleccionado,
mientras que los elementos que se enumeran en la columna de la derecha representan los
estados de las propiedades. Las propiedades pueden ser establecidas por destacar los
artículos en la columna de la derecha y luego cambiarlos escribiendo o seleccionando las
opciones disponibles. También puede alterar otras propiedades de la forma como la fuente,
ubicación, tamaño, color de primer plano, color de fondo, MaximizeBox, MinimizeBox y etc
También puede cambiar las propiedades del objeto en tiempo de ejecución para dar efectos
especiales tales como el cambio de color, forma, efecto de animación y así sucesivamente.
Por ejemplo el siguiente código cambiará el color a amarillo forma cada vez que se carga el
formulario. Visual Basic 2012 utiliza RGB (rojo, verde, azul) para determinar los colores. El
código RGB para el amarillo es 255,255,0. Yo en el código refiero a la forma actual y
Backcolor es propiedad de color de fondo del formulario. La fórmula para asignar el color RGB
a la forma es Color.FormArbg (código RGB). El procedimiento de evento es el siguiente:
End Sub
End Class
You may also use the follow procedure to assign the color at run time.
También puede utilizar el procedimiento siguiente para asignar el color en tiempo de
ejecución.
Me.BackColor = Color.Magenta
End Sub
Both procedures above will load the form with a magenta background as follows:
Here are some of the common colors and the corresponding RGB codes. You can always
experiment with other combinations, but remember the maximum number for each color is 255
and the minimum number is 0.
Éstos son algunos de los colores comunes y los códigos RGB correspondientes. Siempre se
puede experimentar con otras combinaciones, pero recuerda que el número máximo para
cada color es 255 y el mínimo es 0.
The following is another program that allows the user to enter the RGB codes into three
different textboxes and when he or she clicks the display color button, the background color of
the form will change according to the RGB codes. So, this program allows users to change the
color properties of the form at run time.
El siguiente es otro programa que permite al usuario introducir los códigos RGB en tres
cuadros de texto diferentes y cuando él o ella hace clic en el botón de color de la pantalla, el
color de fondo del formulario cambiará de acuerdo con los códigos RGB. Así, este programa
permite a los usuarios cambiar las propiedades de color de la forma en tiempo de ejecución.
End Sub
*This article has been translated to Serbo-Croatian language by Vera Djuraskovic from Webhostinggeeks.com.
In first three lessons, you have learned how to enter the program code and run the sample
Visual Basic 2012 programs but without much understanding about the logics of Visual Basic
2012 programming. Now, let’s get down to learning a few basic rules about writing the Visual
Basic 2012 program code.
En las tres primeras lecciones, has aprendido cómo entrar en el código del programa y
ejecutar el ejemplo de programas de Visual Basic 2012, pero sin mucha comprensión sobre la
lógica de programación Visual Basic 2012. Ahora, vayamos a aprender algunas reglas básicas
sobre cómo escribir el código del programa Visual Basic 2012.
First of all, Visual Basic 2012 is very much similar to Visual Basic 2010 and Visual Basic 2008.
However, it is very different from Visual Basic 6. While they are nearly similar in terms of
Interface and program structure, their underlying concepts are quite different. The main
difference is that Visual Basic 2012 is a full fledged Object Oriented Programming Language
while Visual Basic 6 may have OOP capabilities, it is not fully object oriented. In order to
qualify as a fully object oriented programming language, it must have three core technologies
namely encapsulation, inheritance and polymorphism. These three terms are explained
below:
En primer lugar, Visual Basic 2012 es muy similar a Visual Basic 2010 y Visual Basic 2008 Sin
embargo, es muy diferente de Visual Basic 6 Si bien son casi similares en términos de interfaz
y estructura del programa, sus conceptos subyacentes son bastante diferentes . La principal
diferencia es que Visual Basic 2012 es un hecho y derecho Object Oriented Programming
Language, mientras que Visual Basic 6 puede tener capacidades de programación orientada a
programación orientado a objetos completo, debe tener tres tecnologías básicas a saber
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.
Inheritance Herencia
Classes are created according to hierarchies, and inheritance allows the structure and
methods in one class to be passed down the hierarchy. That means less programming is
required when adding functions to complex systems. If a step is added at the bottom of a
hierarchy, then only the processing and data associated with that unique step needs to be
added. Everything else about that step is inherited. The ability to reuse existing objects is
considered a major advantage of object technology.
Las clases se crean de acuerdo con las jerarquías, y la herencia permite a la estructura y los
métodos de una clase que se deben pasar por la jerarquía. Esto significa que se requiere
menos programación y al añadir funciones a los sistemas complejos. Si se añade un paso en
la parte inferior de una jerarquía entonces sólo necesita, el procesamiento y los datos
asociados con ese paso único que se añade. Todo lo demás en ese paso se hereda. La
capacidad de reutilizar los objetos existentes se considera una de las principales ventajas de
la tecnología de objetos.
Polymorphism El polimorfismo
Object-oriented programming allows procedures about objects to be created whose exact type
is not known until runtime. For example, a screen cursor may change its shape from an arrow
to a line depending on the program mode. The routine to move the cursor on screen in
response to mouse movement would be written for “cursor,” and polymorphism allows that
cursor to take on whatever shape is required at runtime. It also allows new shapes to be easily
integrated.
VB6 is not a full OOP in the sense that it does not have inheritance capabilities although it can
make use of some benefits of inheritance. However, VB2012 is a fully functional Object
Oriented Programming Language, just like other OOP such as C++ and Java. It is focuses
more on the data itself while VB6 and earlier versions focus more on the actions. VB6 and its
predecessors are known as procedural or functional programming language. Some other
procedural programming languages are C, Pascal and Fortran.
Visual Basic 2012 allows users to write programs that break down into modules. These
modules will represent the real-world objects and are knows as classes or types. An object can
be created out of a class and it is known as an instance of the class. A class can also comprise
subclass. For example, apple tree is a subclass of the plant class and the apple in your
backyard is an instance of the apple tree class. Another example is student class is a subclass
of the human class while your son John is an instance of the student class.
A class consists of data members as well as methods. In Visual Basic 2012, the program
structure to define a Human class can be written as follows:
Programación orientada a objetos permite que los procedimientos acerca de los objetos que
se creen cuyo tipo exacto no se conoce hasta el tiempo de ejecución. Por ejemplo, un cursor
de la pantalla puede cambiar su forma de una flecha a una línea según el modo de programa.
La rutina para mover el cursor en la pantalla en respuesta al movimiento del ratón se escribiría
para "cursor", y el polimorfismo permite que el cursor para asumir cualquier forma que se
requiere en tiempo de ejecución. También permite nuevas formas para integrar fácilmente.
Visual Basic 2012 permite a los usuarios escribir programas que se descomponen en
módulos. Estos módulos se representan los objetos del mundo real y son conoce como clases
o tipos. Un objeto puede ser creado a partir de una clase y se le conoce como una instancia
de la clase. Una clase también puede comprender subclase. Por ejemplo, el manzano es una
subclase de la clase de plantas y la manzana en su patio trasero es una instancia de la clase
manzano. Otro ejemplo es la clase del estudiante es una subclase de la clase humana,
mientras que su hijo Juan es una instancia de la clase de los estudiantes.
Una clase se compone de miembros de datos, así como métodos. En Visual Basic 2012, la
estructura del programa para definir una clase de humano se puede escribir de la siguiente
manera:
‘Data Members
‘Methods
MessageBox.Show(Name)
MessageBox.Show(Birthdate)
MessageBox.Show(Gender)
MessageBox.Show(Age)
End Sub
End Class
Another Example:
‘Methods
MessageBox.Show(Brand)
MessageBox.Show(Model)
MessageBox.Show(Year Made)
MessageBox.Show(Capacity)
End Sub
End Class
Let’s look at one example on how to create a class. The following example shows you how to
create a class that can calculate your BMI (Body Mass Index).
To create class, start Visual Basic 2012 as usual and choose Windows Applications. In the
Visual Basic 2012 IDE, click on Project on the menu bar and select Add Class, the Add New
Item dialog appears, as shown in the Figure below:
Veamos un ejemplo de cómo crear una clase. El siguiente ejemplo muestra cómo crear una
clase que puede calcular su IMC (Índice de Masa Corporal).
Para crear la clase, iniciar Visual Basic 2012 como de costumbre y elegir aplicaciones de
Windows. En el IDE de Visual Basic 2012, haga clic en Proyecto en la barra de menú y
seleccione Agregar clase, el complemento aparece diálogo Nuevo elemento, como se muestra
en la siguiente figura:
The default class Class1.vb will appear as a new tab with a code window. Rename the class as
MyClass.vb. Rename the form as MyFirstClass.vb.
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:
MessageBox.Show(MyObject.BMI(h, w))
End Sub
When you run this program and click the button, the user will be presented with two input
boxes to enter his or her height and weight subsequently and the value of BMI will be shown in
a pop-up message box.
Al ejecutar este programa y haga clic en el botón, el usuario se le presentará con dos cajas de
entrada para entrar en su altura y peso, posteriormente, y el valor del índice de masa corporal
se mostrará en un cuadro de mensaje emergente.
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.
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.
Figure 5.1
To start writing code in Visual Basic 2012, click on any part of the form to go into the code
window as shown in Figure 5.2. This is the structure of an event procedure. In this case, the
event procedure is to load Form1 and it starts with Private Sub and end with End Sub. This
procedure includes the Form1 class and the event Load, and they are bind together with an
underscore, i.e. Form_Load. It does nothing other than loading an empty form. You don’t have
to worry the rest of the stuff at the moment, they will be explained in later lessons.
Para comenzar a escribir código en Visual Basic 2012, haga clic en cualquier parte de la forma
de entrar en la ventana de código, como se muestra en la Figura 5.2. Esta es la estructura de
un procedimiento de evento. En este caso, el procedimiento de evento es cargar Form1 y
comienza con Private Sub y End With End Sub. Este procedimiento incluye la clase Form1 y la
carga de eventos, y se unen junto con un subrayado, es decir Form_Load. No hace nada que
no sea la carga de una forma vacía. Usted no tiene que preocuparse del resto de las cosas en
este momento, que se explicarán en lecciones posteriores.
Public Class Form1
End Sub
End Class
There are other events associated with the Form1 class, such as click, cursorChanged,
DoubleClick, DragDrop, Enter and more, as shown in the diagram Figure 5.2 (It appears when
you click on the upper right pane of the code window)
Hay otros eventos asociados a la clase Form1, como clic, CursorChanged, DoubleClick,
DragDrop, Enter y más, como se muestra en el diagrama de la Figura 5.2 (aparece al hacer
clic en el panel superior derecho de la ventana de código)
Figure 5.2
5.2 Writing the code 5.2 Escritura del código
Now you are ready to write the code for the event procedure so that it will do something more
than loading a blank form. The code must be entered between Private Sub…….End Sub. Let’s
enter the following code :
Ahora ya está listo para escribir el código para el procedimiento de evento para que se va a
hacer algo más que cargar un formulario en blanco. El código debe ser introducido entre
Private Sub ...... .End Sub. Nos adentraremos en el siguiente código:
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.
La primera línea del código va a cambiar el título del formulario a Mi Primer programa Visual
Basic 2012, la segunda línea va a cambiar el objeto en primer plano a LightGoldenrodYellow
(en este caso, es una etiqueta que se inserta en el formulario y cambiar su texto a primer
plano) y la última línea cambia el fondo al color AzulReal. El operador de igualdad = en el
código se utiliza para asignar algo al objeto, al igual que la asignación de color amarillo en el
primer plano del objeto Form1 (o una instancia de Form1). Me es el nombre dado a la clase
Form1. También podemos llamar a estas líneas como declaraciones. Así, las acciones del
programa dependerán de las declaraciones formuladas por el programador.
Here is another example. In this project, you insert one button into the form and change its
label text to “Display Hidden Names”. Click on this button to enter the code window and key-in
the following code:
He aquí otro ejemplo. En este proyecto, se inserta un botón en el formulario y cambie su texto
de la etiqueta de "pantalla oculta de nombres". Haga clic en este botón para entrar en la
ventana de código y clave-en el siguiente código:
End Sub
The keyword Dim is to declare variables name1, name2 and name3 , names as string, which
means they can only handle text. The variable names is to accept the names that are joined
together by the “&” signs as a single string. The function MsgBox is to display the string in a
message box, and the last argument “Hidden Names” is the title of the MsgBox function.
The output is shown in Figure 5.4 below:
La palabra clave es Dim para declarar variables nombre1, nombre2 y name3, nombres como
cadena, lo que significa que sólo pueden manejar texto. Los nombres de las variables es
aceptar los nombres que se unen entre sí por los "y" señales como una única cadena. El
MsgBox función es la de mostrar la cadena en un cuadro de mensaje, y el último argumento
"ocultos nombres" es el título de la función MsgBox. La salida se muestra en la Figura 5.4 a
continuación:
Figure 5.4
We encounter many types of data in our daily life. For example, we need to handle data such
as names, addresses, money, date, stock quotes, statistics and etc everyday. Similarly in
Visual Basic 2012, we have to deal with all sorts of of data, some can be mathematically
calculated while some are in the form of text or other forms. Visual Basic 2012 divides data into
different types so that it is easier to manage when we need to write the code involving those
data.
Nos encontramos con muchos tipos de datos en nuestra vida diaria. Por ejemplo, tenemos que
manejar datos tales como nombres, direcciones, el dinero, la fecha, cotizaciones de bolsa,
estadísticas y etc cotidiana. Del mismo modo, en Visual Basic 2012, tenemos que lidiar con
todo tipo de datos, algunos pueden ser calculados matemáticamente mientras que algunos
son en forma de texto o de otras formas. 2012 divide los datos básicos visuales en diferentes
tipos de modo que sea más fácil de manejar cuando tenemos que escribir el código que
participarán los datos.
Visual Basic 2012 classifies the aforementioned information into two major data types, they are
the numeric data types and the non-numeric data types.
Visual Basic 2012 clasifica la información mencionada en dos tipos de datos principales, que
son los tipos de datos numéricos y los tipos de datos no numéricos.
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
Tipos de datos numéricos son los tipos de datos que consisten en números, que pueden
calcularse matemáticamente con varios operadores de la norma, tales como agregar, menos,
multiplicar, dividir y así sucesivamente. Ejemplos de tipos de datos numéricos son sus
calificaciones de los exámenes, su altura, su peso, el número de alumnos en una clase,
valores de acciones, precio de las mercancías, facturas mensuales, cuotas y etc En Visual
Basic 2012, los datos numéricos se dividen en siete tipos , dependiendo de la gama de valores
que pueden almacenar. Los cálculos que sólo involucran cifras redondas o datos que no
necesitan de precisión puede utilizar entero o entero largo en el cálculo. Los programas que
requieren alta necesidad de cálculo de precisión para utilizar los tipos de datos de precisión
simple y doble, que también se llaman números de punto flotante. Para el cálculo de la
moneda, puede utilizar los tipos de datos de moneda. Por último, si se requiere más precisión
para realizar cálculos que involucran muchos puntos decimales, podemos utilizar los tipos de
datos decimales. Estos tipos de datos se resumen en la Tabla 6.1
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
Tipos de datos no numéricos son datos que no pueden ser manipulados matemáticamente
utilizando operadores aritméticos estándar. Los datos no numérico consta de texto o datos de
cadena tipos, los tipos de datos de fecha, los tipos de datos booleanos que almacenan sólo
dos valores (verdadero o falso), el tipo de datos Object y Variant tipo de datos .They se
resumen en la Tabla 6.2
6.1.3 Suffixes for Literals
Literals are values that you assign to a data. In some cases, we need to add a suffix behind a
literal so that Visual Basic 2012 can handle the calculation more accurately. For example, we
can use num=1.3089# for a Double type data. Some of the suffixes are displayed in Table 6.3.
Los literales son valores que se asignan a una de datos. En algunos casos, tenemos que
añadir un sufijo detrás de un literal para que Visual Basic 2012 puede manejar el cálculo con
mayor precisión. Por ejemplo, podemos utilizar num = 1.3089 # para un tipo de datos doble.
Algunos de los sufijos se muestran en la Tabla 6.3.
In addition, we need to enclose string literals within two quotations and we enclose date and
time literals within two # sign. Strings can contain any characters, including numbers. The
following are few examples:
Además, tenemos que incluir literales de cadena dentro de dos citas y adjuntamos fecha y
hora literales dentro de dos signo #. Las cadenas pueden contener cualquier carácter,
incluyendo los números. Los siguientes son algunos ejemplos:
memberName=”Turban, John.”
TelNumber=”1800-900-888-777″
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
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.
Las variables son como cajas de correo en la oficina de correos. El contenido de las variables
cambian de vez en cuando, al igual que los buzones de correo. En término de Visual Basic
2012, las variables son zonas asignadas por la memoria de la computadora para guardar
datos. Al igual que los buzones de correo, cada variable debe tener un nombre. Para nombrar
una variable en Visual Basic 2012, hay que seguir una serie de reglas.
The following are the rules when naming the variables in Visual Basic 2010
Las siguientes son las reglas al asignar nombres a las variables en Visual Basic 2010
No spacing is allowed
Examples of valid and invalid variable names are displayed in Table 6.4
No se permite el espaciamiento
No se permite el Período
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:
Example 6.1
En Visual Basic 2012, hay que declarar las variables antes de utilizarlas mediante la
asignación de nombres y tipos de datos. Si no lo hace, el programa mostrará un error. Ellos
normalmente se declaran en la sección general de las ventanas los códigos 'utilizando la
instrucción Dim.
La sintaxis es la siguiente:
ejemplo 6.1
End Sub
You may also combine them in one line , separating each variable with a comma, as follows:
También puede combinarlos en una sola línea, separando cada variable con una coma, de la
siguiente manera:
Dim password As String, yourName As String, firstnum As Integer,………….
For string declaration, there are two possible forms, one for the variable-length string and
another for the fixed-length string. For the variable-length string, just use the same syntax as
example 6.1 above. However, for the fixed-length string, you have to use the syntax as shown
below:
Por declaración de cuerdas, hay dos formas posibles, uno para la cadena de longitud variable
y otro para la cadena de longitud fija. Para la cadena de longitud variable, sólo tiene que
utilizar la misma sintaxis que en el ejemplo 6.1 anterior. Sin embargo, para la cadena de
longitud fija, usted tiene que utilizar la sintaxis que se muestra a continuación:
Dim VariableName as String * n, where n defines the number of characters the string can hold.
Example 6.2:
Ejemplo 6.2:
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:
Después de declarar varias variables utilizando las instrucciones Dim, podemos asignar
valores a las variables. El syntx de una asignación es
Variable = Expresión
La variable puede ser una variable declarada o un valor de propiedad de control. La expresión
puede ser una expresión matemática, un número, una cadena, un valor booleano (verdadero o
falso), etc Los siguientes son algunos ejemplos:
firstNumber=100
secondNumber=firstNumber-99
userName=”John Lyan”
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
6.3 Constants
Constants are different from variables in the sense that their values do not change during the
running of the program.
6.3 Constantes
Las constantes son diferentes de variables en el sentido de que sus valores no cambian
durante la ejecución del programa.
Example 6.3
Const Pi As Single=3.142
End Sub
Computer can perform mathematical calculations much faster than human beings. However,
computer itself will not be able to perform any mathematical calculations without receiving
instructions from the user. In Visual Basic 2012, we can write code to instruct the computer to
perform mathematical calculations such as addition, subtraction, multiplication, division and
other kinds of arithmetic operations. In order for Visual Basic 2012 to carry out arithmetic
calculations, we need to write code that involve the use of various arithmetic operators. The
Visual Basic 2012 arithmetic operators are very similar to the normal arithmetic operators, only
with slight variations. The plus and minus operators are the same while the multiplication
operator use the * symbol and the division operator use the / symbol. The list of Visual Basic
2012 arithmetic operators are shown in table 7.1 below:
Ordenador puede realizar cálculos matemáticos mucho más rápido que los seres humanos.
Sin embargo, el propio equipo no será capaz de realizar cualquier cálculo matemático, sin
recibir instrucciones por parte del usuario. En Visual Basic 2012, se puede escribir código para
indicar al ordenador para realizar cálculos matemáticos, tales como suma, resta,
multiplicación, división y otros tipos de operaciones aritméticas. Para que Visual Basic 2012
para realizar cálculos aritméticos, tenemos que escribir código que implica el uso de varios
operadores aritméticos. Los Básica 2.012 operadores aritméticos visuales son muy similares a
los operadores aritméticos normales, sólo con ligeras variaciones. El más y el menos
operadores son los mismos, mientras que el operador de multiplicación utilizar el símbolo * y el
operador de división usar el símbolo /. La lista de 2012 los operadores aritméticos de Visual
Basic se muestran en la tabla 7.1 a continuación:
Example 7.1 ejemplo 7.1
In this program, you need to insert two Textboxes, four labels and one button. Click the button and enter the code as
shown below. When you run the program, it will perform the four basic arithmetic operations and displays the results on
En este programa, es necesario insertar dos cuadros de texto, cuatro etiquetas y un botón. Haga clic en el botón e
introduzca el código como se muestra a continuación. Al ejecutar el programa, se llevará a cabo las cuatro operaciones
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
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
Dim a, b, c As Single
a = TextBox1.Text
b = TextBox2.Text
c=(a^2+b^2)^(1/2)
Label3.Text=c
End Sub
Example 7.3: BMI Calculator Ejemplo 7.3: BMI Calculator
A lot of people are obese now and it could affect their health seriously . Obesity has proven by
the medical experts to be a one of the main factors that brings many adverse medical
problems, including the the cardiovascular disease. If your BMI is more than 30, you are
considered obese. You can refer to the following range of BMI values for your weight status.
Una gran cantidad de personas son obesas ahora y que podría afectar seriamente su salud.
La obesidad se ha demostrado por los expertos médicos para ser un uno de los principales
factores que trae muchos problemas médicos adversos, incluyendo la de la enfermedad
cardiovascular. Si su IMC es superior a 30, usted es considerado obeso. Puede hacer
referencia a la siguiente gama de valores del IMC para su estado de peso.
Underweight = <18.5
Normal weight = 18.5-24.9
Overweight = 25-29.9
Obesity = BMI of 30 or greater
In order to calculate your BMI, you do not have to consult your doctor, you can just
use a calculator or a home made computer program, this is exactly what I am
showing you here. The BMI calculator is a Visual Basic program that can calculate
the body mass index, or BMI of a person based on the body weight in kilogram and
the body height in meter. BMI can be calculated using the formula weight/( height
)^2, where weight is measured in kg and height in meter. If you only know your
weight and height in lb and feet, then you need to convert them to the metric
system (you could indeed write a VB program for the conversion).
Para calcular su IMC, usted no tiene que consultar a su médico, que sólo puede usar una
calculadora o un programa de ordenador casero, esto es exactamente lo que te estoy
mostrando aquí. El índice de cálculo es un programa de Visual Basic que puede calcular el
índice de masa corporal, o IMC de una persona basado en el peso corporal en kilogramos y la
altura del cuerpo en metros. BMI se puede calcular mediante la fórmula peso / (estatura) ^ 2,
donde se mide el peso en kilogramos y la altura en metros. Si sólo conoce su peso y altura en
libras y pies, entonces usted necesita para convertir al sistema métrico (que podría de hecho
escribir un programa de VB para la conversión).
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)
From the above examples, you can see that writing code that involve arithmetic operations is
relatively easy. Here are more arithmetic projects you can try to program:
De los ejemplos anteriores, se puede ver que la escritura de código que implican operaciones
aritméticas es relativamente fácil. Éstos son los proyectos más aritméticas usted puede tratar
de programa:
Area of a triangle
Area of a rectangle
Area of a circle
Volume of a cylinder
Volume of a cone
Volume of a sphere
Compound interest
Future value
Mean
Variance
Sum of angles in polygons
Conversion of lb to kg
Conversion of Fahrenheit to Celsius
In Visual Basic 2012 , string manipulation is important because it helps to process data that
come in the form of non-numeric types such as names, addresses, gender, cities, book titles
and more.
En Visual Basic 2012, la manipulación de cadenas es importante porque ayuda a procesar los
datos que se presentan en forma de tipos no numéricos tales como nombres, direcciones, el
género, las ciudades, los títulos de libros y más.
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
En Visual Basic 2012, las cadenas pueden ser manipulados usando el signo & y el signo +,
ambos realizan la concatenación de cadenas que implica la combinación de dos o más
cadenas más pequeñas en cadenas más grandes. Por ejemplo, podemos unirnos "Visual",
"Basic" y "2012" en "Visual Basic 2012" por medio de "Visual" y "Basic" o "Visual" + "básico",
como se muestra en los siguientes ejemplos
Example 8.1(a)
End Sub
End Class
The line text4=text1+ text2 + text3 can be replaced by text4=text1 & text2 &text3 and produces
the same output. However, if one of the variables is declared as numeric data type, you cannot
use the + sign, you can only use the & sign.
El texto4 línea = texto1 texto2 + + text3 puede ser sustituida por texto4 = texto1 y texto2 y
text3 y produce la misma salida. Sin embargo, si una de las variables se declara como tipo de
datos numéricos, no se puede utilizar el signo +, sólo se puede utilizar el y firmar.
Example 8.1(b)
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.
text1 = “Visual”
text2=22
Label1.Text = text3
You can combine more than two strings to form a larger string, like the following example:
Puede combinar más de dos cadenas para formar una cadena más grande, como el siguiente
ejemplo:
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.
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.
La función Len devuelve un valor entero que es la longitud de una frase o una frase,
incluyendo los espacios vacíos. La sintaxis es
Len (“Phrase”)
For example,
Len (Visual Basic) = 12 and Len (“welcome to VB tutorial”) = 22
Example 8.3
End Sub
End Class
The output:
La función derecha extrae la porción derecha de una frase. El formato para el 6 de Visual
Basic es
Right (“Phrase”, n)
Where n is the starting position from the right of the phase where the portion of the phrase is
going to be extracted. For example,
However, this format is not applicable in VB2012. In VB2012, we need use the following format
Microsoft.VisualBasic.Right(“Phrase”,n)
Example 8.2(a)
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:
La salida:
*The reason of using the full reference is because many objects have the Right properties so
using Right on its own will make it ambiguous to Visual Basic 2012.
* La razón de utilizar la referencia completa se debe a que muchos objetos tienen las
propiedades adecuadas por lo que usar el botón derecho en su propio hará que sea ambigua
a Visual Basic 2012.
The Left function extract the left portion of a phrase. The syntax is
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,
In the previous lessons, we have learned how to write code that accepts input from the user
and displays the output without controlling the program flow. In this lesson, you will learn how
to write Visual Basic 2012 code that can make decision when it process input from the user,
and control the program flow in the process.
Decision making process is an important part of programming in Visual Basic 2012 because it
can solve practical problems intelligently and provide useful output or feedback to the user. For
example, we can write a Visual Basic 2012 program that can ask the computer to perform
certain task until a certain condition is met, or a program that will reject non-numeric data. In
order to control the program flow and to make decisions, we need to use the conditional
operators and the logical operators together with the If control structure.
En las lecciones anteriores, hemos aprendido cómo escribir código que acepte la entrada por
parte del usuario y muestra la salida sin controlar el flujo del programa. En esta lección, usted
aprenderá cómo escribir código de Visual Basic 2012 que puede tomar la decisión cuando se
procesa la entrada del usuario, y controlar el flujo del programa en el proceso.
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.
Los operadores condicionales son herramientas poderosas que se asemeja a los operadores
matemáticos. Estos operadores permiten a un programa de Visual Basic 2012 para comparar
valores de datos y luego decidir qué acciones tomar, ya sea para ejecutar un programa o
terminar el programa y más. También se conocen como operadores de comparación
numéricos. Normalmente se utilizan para comparar dos valores para ver si son iguales o un
valor es mayor o menor que el otro valor. La comparación devolverá un resultado verdadero o
falso. Estos operadores se muestran en la Tabla 9.1.
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.
A veces puede ser que necesitemos hacer más de uno comparaciones antes de una decisión
puede ser tomada y la acción tomada. En este caso, el uso de operadores de comparación
numérica por sí sola no es suficiente, tenemos que usar operadores adicionales, y ellos son
los operadores lógicos. Estos operadores lógicos se muestran en la Tabla 9.2.
Normally the above operators are use to compare numerical data. However, you can also compare strings
with the above operators. In making strings comparison, there are certain rules to follows: Upper case
letters are less than lowercase letters, “A”<“B”<“C”<“D”…….<“Z” and number are less than letters.
Normalmente los operadores anteriores son el uso de comparar datos numéricos. Sin embargo, también
puede comparar cadenas con los operadores anteriores. Al hacer la comparación cuerdas, hay ciertas
reglas que sigue:. Las letras mayúsculas son menores que las letras minúsculas, "A" <"B" <"C" <"D" ......
<"Z" y el número es menos que las letras.
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.
Para controlar eficazmente el flujo del programa Visual Basic 2012, utilizaremos la estructura
de control Si junto con los operadores condicionales y operadores lógicos. Hay básicamente
tres tipos de estructuras de control Si, a saber ... Si la declaración .Then, SI ... .Then ... Else
andif ... .Then ... .ElseIf comunicado.
Esta es la estructura de control más simple que indica al ordenador para realizar una
determinada acción especificada por la expresión de Visual Basic 2012 si la condición es
verdadera. Sin embargo, cuando la condición es falsa, no se realizará ninguna acción. La
sintaxis de la si ... entonces .. afirmación es
If condition Then
End If
Example 9.1
* When you run the program and enter a number that is greater than 100, you will see the “You
win a lucky prize” statement. On the other hand, if the number entered is less than or equal to
100, you don’t see any display.
* Cuando se ejecuta el programa y escribe un número que es mayor que 100, verá la
declaración "Usted gana un premio de la suerte". Por otro lado, si el número introducido es
inferior o igual a 100, no ve ninguna pantalla.
Using just If….Then statement is not very useful in programming and it does not provide
choices for the users. In order to provide a choice, we can use the If….Then…Else Statement.
This control structure will ask the computer to perform a certain action specified by the Visual
Basic 2012 expression if the condition is met. And when the condition is false ,an alternative
action will be executed. The syntax for the if…then.. Else statement is
Utilizando sólo si ... .Then declaración no es muy útil en la programación y no ofrece opciones
para los usuarios. Con el fin de proporcionar una opción, podemos utilizar la instrucción If ...
.Then ... Else. Esta estructura de control le pedirá a la computadora para realizar una
determinada acción especificada por la expresión de Visual Basic 2012 si se cumple la
condición. Y cuando la condición es falsa, se ejecutará una acción alternativa. La sintaxis de la
si ... entonces .. Else es
If condition Then
Else
End If
Example 9.2
* When you run the program and enter a number that is greater than 100, the statement
“Congratulation! You win a lucky prize” will be shown. On the other hand, if the number entered
is less than or equal to 100, you will see the “Sorry, You dif not win any prize” statement
* Cuando se ejecuta el programa y escribe un número que es mayor que 100, la declaración
"¡Enhorabuena! Usted gana un premio de la suerte "se muestran. Por otro lado, si el número
introducido es menor o igual a 100, verá la declaración "Lo sentimos, usted no DIF ganar
cualquiera de los premios"
Example 9.3
End Sub
* This program use the logical operator And beside the conditional operators. This means that
both the conditions must be fulfilled in order for the conditions to be true, otherwise the second
block of code will be executed. In this example, the number entered must be more than 100
and the age must be more than 60 in order to win a lucky prize, any one of the above
conditions not fulfilled will disqualify the user from winning a prize.
* Este programa utiliza el operador lógico Y junto a los operadores condicionales. Esto
significa que tanto las condiciones deben cumplirse para que las condiciones sean
verdaderas, de lo contrario se ejecutará el segundo bloque de código. En este ejemplo, el
número introducido debe ser más de 100, y la edad debe ser más de 60 con el fin de ganar un
premio de la suerte, cualquiera de las anteriores condiciones no cumplidas, se descalificará al
usuario de ganar un premio.
If there are more than two alternative choices, using just If….Then….Else statement will not be
enough. In order to provide more choices, we can use the If….Then…ElseIf Statement.
executed. The general format for the if…then.. Else statement is
Si hay más de dos opciones alternativas, utilizando sólo si ... .Then ... .Else declaración no
será suficiente. Con el fin de ofrecer más opciones, podemos utilizar la instrucción If ... .Then
... ElseIf. ejecutado. El formato general para el si ... entonces .. Else es
If condition Then
Else
End If
Example 9.4
Mark = TextBox1.Text
If myNumber >=80 Then
Grade=”A”
Grade=”B”
Grade=”C”
Else
Grade=”D”
End If
End Sub
In the previous lesson, we have learned how to control the program flow using the If…ElseIf
control structure. In this lesson, you will learn how to use the Select Case control structure
in Visual Basic 2012 to control the program flow . The Select Case control structure is slightly
different from the If….ElseIf control structure . The difference is that the Select Case control
structure basically only make decision on one expression or dimension (for example the
examination grade) while the If …ElseIf statement control structure may evaluate only one
expression, each If….ElseIf statement may also compute entirely different dimensions. Select
Case is preferred when there exist multiple conditions as using If…Then..ElseIf statements will
become too messy.
The syntax of the Select Case control structure in Visual Basic 2012 is as follows:
.
.
Case Else
Seleccione
caso
Else
) Button1_Click(ByVal sender As
grade=txtgrade.Text System.Object, ByVal e As
Case Else
End Sub
Visual Basic 2012 allows a procedure to be repeated as many times as long as the processor
and memory could support. This is generally called looping . Looping is required when we need
to process something repetitively until a certain condition is met. For example, we can design a
program that adds a series of numbers until the sum exceeds a certain value, or a program
that asks the user to enter data repeatedly until he/she keys in the word ‘Finish’. In Visual
Basic 2012, we have three types of Loops, they are the For…..Next loop, the Do loop. and the
While…..End while loop
Visual Basic 2012 permite que un procedimiento que se repite tantas veces tan largo como el
procesador y la memoria podrían apoyar. Esto generalmente se llama bucle. Se requiere
Looping cuando necesitamos para procesar algo repetidamente hasta que se cumpla una
determinada condición. Por ejemplo, podemos diseñar un programa que agrega una serie de
números hasta que la suma es superior a un cierto valor, o un programa que pide al usuario
que introduzca los datos varias veces hasta que él / ella las llaves en la palabra 'Finish'. En
Visual Basic 2012, tenemos tres tipos de bucles, que son la For ... ..Next bucle, el bucle Do. y
el tiempo ... ..End while
Next
To exit a For…..Next Loop, you can place the Exit For statement
within the loop; and it is normally used together with the
If….Then…..sstatement. For its application, you can refer to example
11.1 d.
Para salir de un bucle For ... ..Next, se puede colocar la instrucción Exit
For dentro del bucle; y se utiliza normalmente junto con el Si ... .Then
... ..sstatement. Para su aplicación, se puede hacer referencia al ejemplo
11.1 d.
Example 11.1 a Example 11.1b
sum=0+10+20+30+40+……
The program will compute The process will stop when n is greater than 6.
the
subtraction as follow:
1000-100-95-90-……….
11.2 Do Loop
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
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.
FunctionName (arguments)
The arguments are values that are passed on to the function.In this lesson, we are going to
learn two very basic but useful internal functions of Visual Basic 2012 , i.e. the MsgBox( ) and
InputBox ( ) functions.
Una función en Visual Basic 2012 es similar a un procedimiento normal pero el propósito
principal de la función es la de aceptar una cierta entrada y devolver un valor que se transmite
al programa principal para terminar la ejecución. Hay dos tipos de funciones en Visual Basic
2012, las funciones integradas (o funciones internas) y las funciones creadas por los
programadores.
FunctionName (argumentos)
Los argumentos son los valores que se transmiten a la function.In esta lección, vamos a
aprender dos funciones internas muy básicas pero útiles de Visual Basic 2012, es decir, el
MsgBox () y InputBox () funciones.
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:
The first argument, Prompt, will display the message in the message box. The Style Value will
determine what type of command buttons appear on the message box, please refer to Table
12.1 for types of command button displayed. The Title argument will display the title of the
message board.
12.1 MsgBox () Función
We can use named constants in place of integers for the second argument to make the
programs more readable. In fact, Visual Basic 2012 will automatically shows up a list of named
constants where you can select one of them.
Podemos utilizar constantes con nombre en lugar de enteros para el segundo argumento para
hacer los programas más legibles. De hecho, Visual Basic 2012 se muestra automáticamente
una lista de constantes con nombre que se puede seleccionar uno de ellos.
yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The
values are determined by the type of buttons being clicked by the users. It has to be declared
as Integer data type in the procedure or in the general declaration section. Table 12.2 shows
the values, the corresponding named constant and buttons.
yourMsg es una variable que contiene los valores devueltos por la función MsgBox (). Los
valores se determinan por el tipo de botones que se ha pulsado por los usuarios. Tiene que
ser declarado como tipo de datos de entero en el procedimiento o en la sección de declaración
general. Tabla 12.2 muestra los valores, los correspondientes nombrados botones y
constante.
Example 12.1
If testmsg = 1 Then
MessageBox.Show(“You have clicked the OK button”)
Else
MessageBox.Show(“You have clicked the Cancel button”)
End If
End Sub
To make the message box looks more sophisticated, you can add an icon besides the
message. There are four types of icons available in VB2008 as shown in Table 12.3
Para hacer que el cuadro de mensaje parece más sofisticado, puede agregar un icono
además del mensaje. Hay cuatro tipos de iconos disponibles en VB2008 como se muestra en
la Tabla 12.3
Example 12.2
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
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 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:
However, the format won’t work in Visual Basic 2012 because InputBox is considered a
namespace. So, you need to key in the full reference to the Inputbox namespace, which is
Una función InputBox () aparecerá un cuadro de mensaje en el que el usuario puede introducir
un valor o un mensaje en forma de texto. En VB2005, puede utilizar el siguiente formato:
myMessage 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:
The inputbox will appear as shown in the figure below when you press the command button
La caja de texto aparecerá como se muestra en la figura siguiente, cuando se pulsa el botón
de comando
We have learned the basic concept of function in Visual Basic 2012. In particular, we have
shown you how to use the MsgBox function and InputBox function in Lesson 12. In fact, we
have already illustrated a few string manipulation functions in Lesson 8, they are the Len
function, the Left function and the Right Function. In this lesson, we will learn other string
manipulation functions in visual basic 2012.
Hemos aprendido el concepto básico de la función en Visual Basic 2012 En particular, hemos
demostrado cómo utilizar la función MsgBox y la función InputBox en la Lección 12 De hecho,
ya hemos ilustrado algunas funciones de manipulación de cadenas en la lección 8, que son la
función Len, la función de la izquierda y de la función Derecha. En esta lección, aprenderemos
otras funciones de manipulación de cadenas en Visual Basic 2012.
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
position is the starting position of the phrase from which the retrieving process begins.
La función Mid se utiliza para recuperar una parte de texto forman una frase. El formato de la
función Mid es
donde
Example 13.1:
* In this example, when the user clicks the command button, an inputbox will pop up asking the
user to input a phrase. After a phrase is entered and the OK button is pressed, the label will
show the extracted text starting from position 2 of the phrase and the number of characters
extracted is 6.
* En este ejemplo, cuando el usuario hace clic en el botón de comando, una caja de texto
aparecerá para preguntarle al usuario que introduzca una frase. Después de introducir una
frase y se pulsa el botón OK, la etiqueta mostrará el texto extraído a partir de la posición 2 de
la frase y el número de caracteres extraída es 6.
The 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:
Microsoft.Visualbasic.Right ("Frase", n)
Example 13.2: The following code extracts the right portion any phrase entered by the user.
myword = TextBox1.Text
Label1.Text = Microsoft.VisualBasic.Right (myword, 4)
End Sub
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:
Microsoft.Visualbasic.Right ("Frase", n)
Example 13.3: The following code extracts the left portion any phrase entered by the user.
myword = TextBox1.Text
End Sub
The Trim function trims the empty spaces on both side of the phrase. The format is
Trim(“Phrase”)
La función Recortar recorta los espacios vacíos en ambos lados de la frase. El formato es
Trim ("Frase")
.For Ejemplo, Recorte ("Visual Basic") = Visual basic
Example 13.4
The Ltrim function trims the empty spaces of the left portion of the phrase. The format is
Ltrim(“Phrase”)
.For example,
La función LTrim recorta los espacios vacíos de la parte izquierda de la frase. El formato es
Ltrim ("Frase")
.For Ejemplo,
The Rtrim function trims the empty spaces of the right portion of the phrase. The format is
Rtrim(“Phrase”)
.For example,
La función de Rtrim recorta los espacios vacíos de la parte derecha de la frase. El formato es
Rtrim ("Frase")
.For Ejemplo,
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
Where n is the position where the Instr function will begin to look for the embedded phrase. For
example
La función InStr busca una frase que está incrustado dentro de la frase original y devuelve la
posición inicial de la frase embebido. El formato es
Donde n es la posición donde la función Instr comenzará a buscar la frase embebido. por
ejemplo
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
La función Ucase convierte todos los caracteres de una cadena a mayúsculas. Por otro lado,
la función de LCASE convierte todos los caracteres de una cadena de letras pequeñas.
El formato es
Microsoft.VisualBasic.UCase(Phrase)
Microsoft.VisualBasic.LCase(Phrase)
For example,
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
La función Chr devuelve la cadena que corresponde a un código ASCII mientras que la
función Asc convierte un carácter ASCII o símbolo en el código ASCII correspondiente. ASCII
significa "Código Estándar Americano para Intercambio de Información". En total hay 255
códigos ASCII y tantos caracteres ASCII. Algunos de los caracteres no se muestren, ya que
pueden representar algunas acciones, como la pulsación de una tecla o producir un sonido de
pitido. El formato de la función Chr es
Chr(charcode)
Asc(Character)
Asc(“B”)=66, Asc(“&”)=38
In previous lessons, we have learned how to write codes in Visual Basic 2012 that perform
arithmetic operations using standard mathematical operators. However, in order to perform
more complex mathematical calculations, we need to use the built-in math functions in Visual
Basic 2012. There are numerous built-in mathematical functions in Visual Basic 2012 which we
will introduce them one by one in this lesson.
En las lecciones anteriores, hemos aprendido cómo escribir códigos en Visual Basic 2012 que
realizan operaciones aritméticas mediante operadores matemáticos estándar. Sin embargo,
con el fin de realizar cálculos matemáticos más complejos, tenemos que utilizar las funciones
matemáticas incorporadas en Visual Basic 2012 Hay numerosas funciones integradas de
matemáticas en Visual Basic 2012 que vamos a introducirlos uno a uno en esta lección.
The syntax is
La sintaxis es
El Exp de un número x es el valor exponencial de x, es decir, ex. Por ejemplo, Exp (1) = e =
2,71828182
Example:
End Sub
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:
ejemplo:
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
La Int es una función que convierte un número en un entero truncando su parte decimal y el
entero resultante es el mayor entero que es menor que él número. por ejemplo
The Log function is the function that returns the natural logarithm of a number. For example,
Log(10)=2.302585
Example:
ejemplo:
End Sub
Rnd is a very useful function in Visual Basic 2012 . We use the Rnd funciton to write code that
involves chance and probability. The Rnd function returns a random value between 0 and 1.
Random numbers in their original form are not very useful in programming until we convert
them to integers. For example, if we need to obtain a random output of 6 integers ranging from
1 to 6, which makes the program behave like a virtual dice, we need to convert the random
numbers to integers using the formula Int(Rnd*6)+1.
Example:
14.6 El Rnd () Función
Vta es una función muy útil en Visual Basic 2012. Usamos el funciton Vta escribir código que
involucra el azar y probabilidad. La función Rnd devuelve un valor aleatorio entre 0 y 1.
números aleatorios en su forma original no son muy útiles en la programación hasta que los
convertimos a enteros. Por ejemplo, si tenemos que obtener una salida aleatoria de 6 números
enteros de 1 a 6, lo que hace que el programa se comporte como un dado virtuales,
necesitamos convertir los números al azar a números enteros utilizando la fórmula Int (Rnd *
6) +1 .
ejemplo:
Randomize( )
Num=Int(Rnd()*6)+1
Label1.Text=Num
End Sub
In this example, Int(Rnd*6) will generate a random integer between 0 and 5 because the
function Int truncates the decimal part of the random number and returns an integer. After
adding 1, you will get a random number between 1 and 6 every time you click the command
button. For example, let say the random number generated is 0.98, after multiplying it by 6, it
becomes 5.88, and using the integer function Int(5.88) will convert the number to 5; and after
adding 1 you will get 6.
En este ejemplo, Int (Rnd * 6) va a generar un entero aleatorio entre 0 y 5 porque la función Int
trunca la parte decimal del número aleatorio y devuelve un entero. Después de añadir 1,
obtendrá un número aleatorio entre 1 y 6 cada vez que hace clic en el botón de comando. Por
ejemplo, vamos a decir que el número aleatorio generado es de 0,98, después de multiplicar
por 6, se convierte en 5,88, y el uso de la función Int número entero (5.88) se convertirá el
número a 5; y después de la adición de 1 obtendrá 6.
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
End Sub
* The Math keyword here indicates that the Round function belong to the Math class.
* La palabra clave matemáticas aquí indica que la función Round pertenecen a la clase Math.
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.
where n is a number.
The list of style arguments in Visual Basic 2012 is given in Table 15.1.
La función de formato en Visual Basic 2012 es una función de formato muy potente. Se utiliza
para mostrar los valores numéricos de varias formas. Hay dos tipos de funciones de formato,
uno de ellos es el incorporado o formato predefinido mientras que otro puede ser definido por
los usuarios.
donde n es un número.
Table 15.1 List of style arguments Tabla 15.1 Lista de argumentos del estilo
argument
places.
places.
Example 15.1
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
A pesar de que se conoce como formato definido por el usuario, todavía tenemos que sigue
ciertos estilos de formato. Los ejemplos de estilo de formato definido por el usuario se
enumeran en la Tabla 15.2
Example 15.2
16.1 Formatting Date and time using predefined formats in Visual Basic 2012
In Visual Basic 2012 , we can format date and time using predefined formats or user-defined
formats. The predefined formats of date and time are shown in Table 16.1.
16.1 Formato de fecha y hora utilizando formatos predefinidos en Visual Basic 2012
En Visual Basic 2012, se puede dar formato a la fecha y la hora utilizando formatos
predefinidos o formatos definidos por el usuario. Los formatos predefinidos de fecha y hora se
muestran en la Tabla 16.1.
* Instead of “General date”, you can also use the abbreviated format “G” , i.e. Format (Now,
“G”). For “Long Time”, you can use the abbreviated format “T” and for “Short Time”, you may
use the abbreviated format “t”
Example 16.1
* En lugar de "fecha general", también se puede utilizar el formato abreviado "G", es decir,
Formato (Ahora, "G"). Para "Long Time", puede utilizar el formato abreviado de "T" y de "poco
tiempo", puede utilizar el formato "t" abreviado
Ejemplo 16.1
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)
Además de utilizar los formatos predefinidos, también puede utilizar las funciones de formato
definidas por el usuario. La sintaxis general de una fecha para la definida por el usuario / hora
End Sub
Check box is a very useful control in Visual Basic 2012. It allows the user to select one or more
items by checking the check box or check boxes concerned. For example, in the Font dialog
box of any Microsoft Text editor like FrontPage, there are many check boxes under the Effects
section such as that shown in the diagram below. The user can choose underline, subscript,
small caps, superscript, blink and etc. In Visual Basic 2012, you may create a shopping cart
where the user can click on check boxes that correspond to the items they intend to buy, and
the total payment can be computed at the same time as shown in Example 17.1.
Casilla de verificación es un control muy útil en Visual Basic 2012 Permite al usuario
seleccionar uno o más elementos marcando la casilla de verificación o casillas de verificación
de que se trate. Por ejemplo, en el cuadro de diálogo Fuente de cualquier editor de texto de
Microsoft como FrontPage, hay muchas casillas de verificación en la sección de efectos, tales
como la que se muestra en el siguiente diagrama. El usuario puede elegir subrayado,
subíndice, versalitas, superíndice, parpadeo, etc En Visual Basic 2012, puede crear un carrito
de compras en el que el usuario puede hacer clic en las casillas de verificación
correspondientes a los elementos que tengan la intención de comprar, y el pago total se puede
calcular al mismo tiempo, como se muestra en el Ejemplo 17.1.
Example 17.1:Shopping Cart Ejemplo 17.1: Compras
The program code for shopping cart is as follows: El código de programa para cesta de la
compra es el siguiente:
Const HD As Integer = 80
Example 17.2
He aquí otro ejemplo
Ejemplo 17.2
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.
End If
End Sub
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
will retain the original font type but change it to italic font style.
will also retain the original font type but change it to regular font style. (The other statements
employ the same logic)
También mantendrá el tipo de fuente original, pero cambiar a caracteres normales. (Los otros
estados emplean la misma lógica)
* Instead of “General date”, you can also use the abbreviated format “G” , i.e. Format (Now,
“G”). And for “Long Time”, you can use the abbreviated format “T”. As for “Short Time”, you
may use the abbreviated format “t”
* En lugar de "fecha general", también se puede utilizar el formato abreviado "G", es decir,
Formato (Ahora, "G"). Y para "Long Time", puede utilizar el formato abreviado de "T". En
cuanto a "Short Time", usted puede utilizar el formato abreviado "t"
Radio button is also a very useful control in Visual Basic 2012. It operates differently from the
check boxes. While the check boxes work independently and allow the user to select one or
more items , radio buttons are mutually exclusive, which means the user can only choose one
item only out of a number of choices. Here is an example which allows the user to select one
color only.
Botón de radio es también un control muy útil en Visual Basic 2012. funciona de forma
diferente a partir de las casillas de verificación. Mientras que las casillas de verificación
trabajar de forma independiente y permiten al usuario seleccionar uno o más elementos,
botones de radio son mutuamente excluyentes, lo que significa que el usuario sólo puede
elegir una opción sólo de una serie de opciones. He aquí un ejemplo que permite al usuario
seleccionar un solo color.
Although the user may only select one item at a time, he may make more than one selection if
those items belong to different categories. For example, the user wishes to choose T-shirt size
and color, he needs to select one color and one size, which means one selection in each
category. This is easily achieved in Visual Basic 2012 by using the Groupbox control under the
containers categories.
Under the Visual Basic 2012 IDE, after inserting the Groupbox from the tool box into the form,
you can proceed to insert the radio buttons into the Groupbox. Only the radio buttons inside the
Groupbox are mutually exclusive, they are not mutually exclusive with the radio buttons outside
the Groupbox. In Example 18.2, the user can select one color and one size of the T-shirt.
Example 18.2
Aunque el usuario sólo puede seleccionar un elemento a la vez, se puede hacer más de una
selección, si esos elementos pertenecen a diferentes categorías. Por ejemplo, el usuario
desea elegir la camiseta tamaño y color, que necesita para seleccionar un color y una talla, lo
que significa una selección en cada categoría. Esto se consigue fácilmente en Visual Basic
2012 utilizando el control Cuadro de grupo en las categorías contenedores.
Bajo el básico 2012 IDE Visual, después de insertar el Cuadro de grupo de la caja de
herramientas en la forma, se puede proceder a insertar los botones de radio en el Cuadro de
grupo. Sólo los botones de opción dentro del Cuadro de grupo son mutuamente excluyentes,
no son mutuamente excluyentes con los botones de radio fuera del Cuadro de grupo. En el
Ejemplo 18.2, el usuario puede seleccionar un color y una talla de la camiseta.
The code: El código
Basically everyone likes to navigate the Internet using commercially produced web browsers
such the Internet Explorer produced by Microsoft or those open source browsers designed by
the experts such FireFox , Opera and the latest Chrome created by Google. However, isn’t it
cool that if you can create your very own web browser that you can customize to your own
taste ? Yes, you can do that in Visual Basic 2012, and pretty easy too. In this chapter, I will
show you how to create a simple web browser and get it running in a few minutes.
Básicamente todo el mundo le gusta navegar por Internet utilizando navegadores web
producidos comercialmente como el Internet Explorer producida por Microsoft o los
navegadores de código abierto diseñado por los expertos como Firefox, Opera y el más
reciente de Chrome creado por Google. Sin embargo, no es que se enfríe que si usted puede
crear su propio navegador web que se puede personalizar a su gusto? Sí, usted puede
hacerlo en Visual Basic 2012, y bastante fácil también. En este capítulo, te voy a mostrar
cómo crear un simple navegador web y ponerlo en marcha en pocos minutos.
First of all, start a new project in Visual Basic 2012 and name it with any name you like. Here I am just
using the name Web Browser. Change the name of Form1 to MyWebBrowser and the text property to
Web Browser and set its size property to 640,480. Next, you need to add an engine so that your web
browser can connect to the Internet, and this very engine is the WebBrowser control, located on the
Toolbox on the left side, set the size property to 600,400. Next, drag a text box and place it at the top
of the WebBrowser control, this will be the address bar where the user can enter the URL. Lastly,
place a command button beside the text box and label it as Go and change its name to Go as well.
The design interface is shown below:
En primer lugar, iniciar un nuevo proyecto en Visual Basic 2012 y el nombre con el nombre que desee.
Aquí sólo estoy usando el navegador Web nombre. Cambie el nombre de Form1 a MyWebBrowser y
la propiedad de texto a Navegador Web y establezca su propiedad tamaño a 640.480. Después, usted
necesita para añadir un motor para que su navegador puede conectarse a Internet, y este mismo
introducir la URL. Por último, coloque un botón de comando al lado del cuadro de texto y etiquetarlo
como Go y cambiar su nombre para ir también. El diseño de la interfaz se muestra a continuación:
The code for the web browser is surprisingly simple, it is only a single line code! Double click
on the Go button and key in the following code:
El código para el navegador web es sorprendentemente simple, sólo es una sola línea de
código! Haga doble clic en el botón Ir y escriba el siguiente código:
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.
Ahora ejecuta el programa, escriba cualquier URL y haga clic en el botón Go. Usted será
capaz de navegar por cualquier página web que desee.
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)
Errores menudo se producen debido a la entrada incorrecta del usuario. Por ejemplo, el
usuario podría cometer el error de tratar de introducir texto (string) a una caja que está
diseñado para manejar sólo valores numéricos tales como el peso de una persona, el equipo
no será capaz de realizar cálculo aritmético para el texto, por lo tanto lo hará crear un error.
Estos errores se conocen como errores síncronos.
Por lo tanto un buen programador debe estar más alerta a las partes del programa que
podrían provocar errores y debe escribir los errores de manipulación de código para ayudar al
usuario en el manejo de los errores. Escribir los errores de manipulación de código es una
buena práctica para los programadores de Visual Basic 2012, así que no trate de terminar un
programa rápido al omitir los errores de manejo de código. Sin embargo, no debería haber
demasiados errores de manipulación de código en el programa, ya que crea problemas para el
programador para mantener y solucionar problemas del programa más adelante.
Visual Basic 2012 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
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.
Visual Basic 2012 todavía admite los errores VB6 manejo de la sintaxis, que es el On Error
GoTo estructura program_label. Aunque tiene un método más avanzado de manejo de
errores, nos ocuparemos de que later.We ahora deberá aprender a escribir los errores de
manipulación de código en Visual Basic 2012 La sintaxis de los errores de manipulación es
donde program_label es la sección del código que está diseñado por el programador para
gestionar el error cometido por el usuario. Una vez que se detecta un error, el programa
saltará a la sección program_label para el tratamiento de errores.
In this example, we will deal with the error of entering non-numeric data into the textboxes that
suppose to hold numeric values. The program_label here is error_hanldler. when the user
enter a non-numeric values into the textboxes, the error message will display the text”One of
the entries is not a number! Try again!”. If no error occurs, it will display the correct answer. Try
it out yourself.
En este ejemplo, vamos a tratar con el error de introducir datos no numéricos en los cuadros
de texto que suponen para contener valores numéricos. El program_label aquí es
error_hanldler. cuando el usuario introduce un valor no numérico en los cuadros de texto, el
mensaje de error se mostrará el texto "Una de las entradas no es un número! Inténtalo de
nuevo! ". Si no se produce ningún error, se mostrará la respuesta correcta. Pruébelo usted
mismo.
The Code El código
Lbl_ErrorMsg.Visible = False
firstNum = Txt_FirstNumber.Text
secondNum = Txt_SecondNumber.Text
Exit Sub ‘To prevent error handling even the inputs are valid
error_handler:
Lbl_Answer.Text = “Error”
Lbl_ErrorMsg.Visible = True
End Sub
End Class
The Output la salida
VB2012 has adopted a new approach in handling errors, or rather exceptions handling. It is
supposed to be more efficient than the old On Error Goto method, where it can handles various
types of errors within the Try…Catch…End Try structure.
20.3 Errores de manipulación utilizando Try ... ..Catch ... .End Trate Estructura
Try
statements
End Try
Example 20.2
This is a modification of Example 20.1. Instead of using On Error GoTo method, we use the
Try…Catch…End Try method. In this example, the Catch statement will catch the exception
when the user enters a non-numeric data and return the error message. If there is no
exception, there will not any action from the Catch statement and the program returns the
correct answer.
The code
Ejemplo 20.2
Esta es una modificación del Ejemplo 20.1. En lugar de utilizar On Error GoTo método, se
utiliza el método Try Try ... Catch ... End. En este ejemplo, la instrucción Catch se captura la
excepción cuando el usuario introduce un conjunto de datos no numéricos y devolver el
mensaje de error. Si no hay excepción, no habrá ninguna acción de la declaración de capturas
y el programa devuelve la respuesta correcta.
el código
Lbl_ErrorMsg.Visible = False
Try
firstNum = Txt_FirstNumber.Text
secondNum = Txt_SecondNumber.Text
Lbl_Answer.Text = answer
Catch ex As Exception
Lbl_Answer.Text = “Error”
Lbl_ErrorMsg.Visible = True
End Try
End Sub
End Class
21.1 Introduction
Managing graphics is easy in earlier versions of Visual Basic as they have built-in drawing
tools. For example, In Visual Basic 6, the drawing tools are included in the toolbox where the
programmer just need to drag the shape controls into the form to create rectangle, square,
ellipse,circle and more. However, its simplicity has the shortcomings, you don’t have much
choices in creating customized drawings.
21.1 Introducción
La gestión de gráficos es fácil en las versiones anteriores de Visual Basic, ya que han
incorporado en las herramientas de dibujo. Por ejemplo, en Visual Basic 6, las herramientas
de dibujo se incluyen en la caja de herramientas donde el programador sólo tiene que arrastrar
los controles de la forma en la forma de crear rectángulo, cuadrado, elipse, círculo y más. Sin
embargo, su simplicidad tiene las deficiencias, no tienes muchas opciones en la creación de
dibujos personalizados.
Since Visual Basic evolved into a fully OOP language under the VB.net framework, shape controls are no longer available. Now the programmer needs to
write code to create various shapes and drawings. Even though the learning curve is steeper, the programmer can write powerful code to create all kinds
Desde Visual Basic evolucionó a un lenguaje plenamente programación orientada a objetos en el marco VB.net, forma a los controles ya no están
disponibles. Ahora el programador necesita escribir código para crear diferentes formas y dibujos. A pesar de que la curva de aprendizaje es empinada,
el programador puede escribir poderoso código para crear todo tipo de gráficos. Usted puede incluso diseñar sus propios controles
Visual Basic 2012 offers various graphics capabilities that enable programmers to write code that can draw all kinds of shapes and
even fonts. In this lesson,you will learn how to write code to draw lines and shapes on the Visual Basic 2012 interface.
Visual Basic 2012 ofrece varias capacidades gráficas que permiten a los programadores a escribir código que puede dibujar todo tipo
de formas e incluso fuentes. En esta lección, usted aprenderá cómo escribir código para dibujar líneas y formas en la interfaz de
Visual Basic 2012.
21.1 Creating the Graphics Object
Before you can draw anything on a form, you need to create the Graphics object in Visual
Basic 2012. A graphics object is created using a CreateGraphics() method. You can create a
graphics object that draw to the form itself or a control. For example, if you wish to draw to the
form, you can use the following statement:
Antes de que pueda dibujar cualquier cosa en un formulario, es necesario crear el objeto
Graphics en Básico 2012. Un objeto gráfico visual se crea usando un método ()
CreateGraphics. Puede crear un objeto gráfico que dibuja a la forma en sí o un control. Por
ejemplo, si desea llamar a la forma, puede utilizar la siguiente declaración:
*Always use Dim to define the object. Using me instead of Form1 because it is not allow in
Visual Basic 2012.
Or if you want the graphics object to draw to a picturebox, you can write the following
statement:
* Siempre use Dim para definir el objeto. El uso de mí en lugar de Form1 ya que no se permite
en Visual Basic 2012.
O si usted quiere el objeto gráfico para dibujar a un PictureBox, puede escribir la siguiente
declaración:
You can also use the textbox as a drawing surface, the statement is:
También puede utilizar el cuadro de texto como superficie de dibujo, la declaración es:
The Graphics object that is created does not draw anything on the screen until you call the
methods of the Graphics object. In addition,you need to create the Pen object as the drawing
tool. We will examine the code that can create a pen in the following section.
El objeto Graphics que se crea no saca nada en la pantalla hasta que llame a los métodos del
objeto Graphics. Además, es necesario crear el objeto Pen como la herramienta de dibujo.
Vamos a examinar el código que puede crear una pluma en la siguiente sección.
21.2 Creating a Pen
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.
donde myPen es una variable Pen. Puede utilizar cualquier nombre de variable en lugar de
myPen. El primer argumento del objeto pluma definir el color de la línea de dibujo y el segundo
argumento define el ancho de la línea de dibujo.
Where the first argument define the color(here is blue, you can change that to red or whatever
color you want) and the second argument is the width of the drawing line.
Having created the Graphics and the Pen objects, you are now ready to draw graphics on the
screen which we will show you in the following section.s
Donde el primer argumento define el color (en este caso es azul, usted puede cambiar eso a
rojo o lo que quieras) y el segundo argumento es el ancho de la línea de dibujo.
Después de haber creado los gráficos y los objetos Pen, que ahora está listo para dibujar
gráficos en la pantalla que le mostramos en las siguientes secciones
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.
End Sub
The second created the Graphics object and the third and fourth line create the Pen object.
The fifth draw a line on the Form using the DrawLine method. The first argument use the Pen
object created by you, the second argument and the third arguments define the coordinate the
starting point of the line, the fourth and the last arguments define the ending coordinate of the
line. The general syntax of the Drawline argument is
La segunda crea el objeto Graphics y la tercera y cuarta línea de crear el objeto Pen. El quinto
dibujar una línea en el formulario utilizando el método DrawLine. El primer argumento de
utilizar el objeto Pen creado por usted, el segundo argumento y el tercer argumento a definir el
punto inicial de la línea de coordenadas, la cuarta y los últimos argumentos definen el fin de
coordinar de la línea. La sintaxis general del argumento es drawLine
We have learned how to create the Graphics and the Pen objects to draw straight lines in
Visual Basic 2012 in the previous lesson. Now we shall learn how to draw various shapes such
as rectangle, square,ellipse and circle.
Hemos aprendido cómo crear los gráficos y la pluma objetos para dibujar líneas rectas en
Visual Basic 2012 en la lección anterior. Ahora vamos a aprender a dibujar diferentes formas,
tales como rectángulo, cuadrado, elipse y el círculo.
To draw a rectangle on the screen in Visual Basic 2012, there are two ways:
(i)The first way is to draw a rectangle directly using the DrawRectangle method by specifying
its upper-left corner’s coordinate and it width and height. You also need to create a Graphics
and a Pen object to handle the actual drawing. The method to draw the rectangle is
DrawRectangle .
Para dibujar un rectángulo en la pantalla en Visual Basic 2012, hay dos maneras:
La sintaxis es la siguiente:
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.
(ii) The second way is to create a rectangle object first and then draw this triangle using the
DrawRectangle method. The syntax is as shown below:
(ii) La segunda manera es crear un objeto rectangular primero y luego dibujar este triángulo
usando el método DrawRectangle. La sintaxis es como se muestra a continuación:
myRect.X = 10
myRect.Y = 10
myRect.Width = 100
myRect.Height = 50
You can also create a rectangle object using a one-line code as follows:
También puede crear un objeto de rectángulo con un código de una línea de la siguiente
manera:
myGraphics.DrawRectangle(myPen, myRectangle)
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:
La forma nos acercamos hasta ahora se dibujan con línea continua, en realidad podemos
personalizar el estilo de línea del objeto Pen para que hemos salpicado línea, la línea que
consiste en guiones y más. Por ejemplo, a continuación se muestra la sintaxis para llamar a la
línea de puntos:
myPen.DashStyle=Drawing.Drawing2D.DashStyle.Dot
Where the last argument Dot specifies a particular line DashStyle value, a line that makes up
of dots here. The following code draws a rectangle with red dotted line.
Si el último argumento Dot especifica un valor DashStyle línea en particular, una línea que
compone de puntos aquí. El siguiente código dibuja un rectángulo con línea punteada roja.
myPen.DashStyle = Drawing.Drawing2D.DashStyle.Dot
End Sub
We have learned how to draw rectangles with various line styles in Visual Basic 2012 in the
previous lesson. Now we shall learn how to draw ellipse and circle.
Hemos aprendido cómo dibujar rectángulos con diferentes estilos de línea en Visual Basic
2012 en la lección anterior. Ahora vamos a aprender a dibujar elipse y el círculo.
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:
En primer lugar tenemos que entender el principio detrás de dibujar una elipse en Visual Basic
2012 La estructura básica de la mayoría de las formas es un rectángulo, elipse no es una
excepción. Elipse es una forma oval que está delimitado por un rectángulo, como se muestra a
continuación:
Therefore, we need to create a Rectangle object before we can draw an ellipse. This
rectangle serves as a bounding rectangle for the ellipse. We still need to use the
DrawEllipse method to finish the job. On the other hand, we can also draw an ellipse
with the DrawEllipse method without first creating a rectangle. We shall show you
both ways.
Por lo tanto, tenemos que crear un objeto Rectangle antes de que podamos dibujar
una elipse. Este rectángulo sirve como un rectángulo de delimitación de la elipse.
Todavía tenemos que utilizar el método drawEllipse para terminar el trabajo. Por otro
lado, también podemos dibujar una elipse con el método drawEllipse sin crear
primero un rectángulo. Le mostraremos dos formas.
In the first method, let say you have created a rectangle object known as myRectangle and a
pen object as myPen, then you can draw an ellipse using the following statement:
En el primer método, Digamos que usted ha creado un objeto rectangular conocida como
myRectangle y un objeto lápiz como myPen, a continuación, se puede dibujar una elipse con
la siguiente declaración:
myGraphics.DrawEllipse(myPen, myRectangle)
* Assume you have also already created the Graphics object myGraphics.
Example 23.1(a)
myRectangle.X = 10
myRectangle.Y = 10
myRectangle.Width = 200
myRectangle.Height = 100
myGraphics.DrawEllipse(myPen, myRectangle)
El segundo método utiliza el método drawEllipse sin crear un objeto de rectángulo. Offcourse
usted todavía tiene que crear los gráficos y los objetos Pen. La sintaxis es la siguiente:
Where (X,Y) are the coordinates of the upper left corner of the bounding rectangle, width is the
width of the ellipse and height is the height of the ellipse.
Donde (X, Y) son las coordenadas de la esquina superior izquierda del rectángulo delimitador,
ancho es el ancho de la elipse y la altura es la altura de la elipse.
Example 23.1(b)
Example 23.2(a)
Después de haber aprendido a dibujar una elipse, dibujando un círculo se hace muy simple.
Utilizamos exactamente los mismos métodos utilizados en la sección anterior, pero modificar
la anchura y altura de modo que sean de los mismos valores.
myRectangle.X = 10
myRectangle.Y = 10
myRectangle.Width = 100
myRectangle.Height = 100
myGraphics.DrawEllipse(myPen, myRectangle)
Example 23.2(b)
We have learned how to draw rectangle, ellipse and circle in visual basic 2012 in the preceding
chapters, now let’s learn how to draw text on the screen. Yes, instead of using the Print
command, you can also draw text on the screen.
Hemos aprendido cómo dibujar rectángulo, elipse y el círculo en visual basic 2012 en los
capítulos anteriores, ahora vamos a aprender a dibujar texto en la pantalla. Sí, en lugar de
utilizar el comando de impresión, también puede dibujar texto en la pantalla.
In order to draw text on the screen, we can use the DrawString method. The format is as
follows:
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:
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:
Dónde myGraphics se oponen los gráficos, myText es el texto que desea mostrar en la
pantalla, myFont es el objeto de fuente creado por usted, MyBrush es el estilo de pincel
creado por usted y X, Y son las coordenadas de la esquina superior izquierda del texto .
Usted puede crear el objeto de fuente en visual basic 2012 mediante la siguiente declaración:
To create your Brush object, you can use the following statement:
Besides the seven colors, some of the common Brush Colors are AliceBlue, AquaMarine
Beige, DarkMagenta, DrarkOliveGreen, SkyBlue and more. You don’t have to remember the
names of all the colors, the intelliSense will let you browse through the colors in a drop-down
menu once you type the dot after the word Color.
Now we shall proceed to draw the font using the sample code below:
Además de los siete colores, algunas de las Cepillo Colores comunes son Aliceblue,
AquaMarine Beige, DarkMagenta, DrarkOliveGreen, SkyBlue y más. Usted no tiene que
recordar los nombres de todos los colores, el IntelliSense le permitirá navegar a través de los
colores en un menú desplegable, una vez que escribe el punto después de la palabra en color.
Example 24.1
Run the program above and you can see the following output:
Ejecute el programa anterior y se puede ver el siguiente resultado:
The preceding can be modified if you don’t want to create the Font and the Brush objects. You
can use the font of an existing object such as the Form and the System Colors. Replace the
last line in the preceding example with this line(you need to delete the lines that create the
Brush and the Font objects as well)
Lo anterior puede ser modificada si no desea crear la fuente y los objetos Brush. Usted puede
utilizar la fuente de un objeto existente, como la forma y los colores del sistema. Vuelva a
colocar la última línea en el ejemplo anterior con esta línea (tendrá que borrar las líneas que
crean el cepillo y objetos de la fuente también)
You can also add a InputBox which let the user enter his or her message then display the
message on the screen.
También puede agregar un InputBox que dejar que el usuario introduzca su mensaje a
continuación, mostrar el mensaje en la pantalla.
Example 24.2
userMsg = InputBox(“What is your message?”, “Message Entry Form”, “Enter your message
here”, 100, 200)
We have learned how to draw rectangle, ellipse ,circle and text in the preceding chapters, now
let’s learn how to draw polygons on the screen. Besides that, we shall also learn how to draw
pie.
Hemos aprendido cómo dibujar rectángulo, elipse, círculo y el texto en los capítulos anteriores,
ahora vamos a aprender a dibujar polígonos en la pantalla. Además de eso, vamos a aprender
también cómo dibujar pastel.
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;
Polígono es una figura plana cerrada delimitada por tres o más lados rectos. Para dibujar un
polígono en la pantalla, tenemos que definir las coordenadas de todos los puntos (también
conocidos como vértices) que se unieron para formar la pollygon.
La sintaxis para define los puntos de un polígono con vértices A1, A2, A3, A4 ...... .An es como
sigue;
.Finally, create the graphics object and use the DrawPolygon method to draw the polygon
using the following syntax:
Después de declarar los puntos, tenemos que definir una estructura de puntos que agrupan
todos los puntos juntos utilizando la siguiente sintaxis:
.Finalmente, Crear el objeto gráfico y utilizar el método drawPolygon para dibujar el polígono
con la siguiente sintaxis:
myGraphics.DrawPolygon(myPen, myPoints)
where myPen is the Pen object created using the following syntax:
myGraphics.DrawPolygon(myPen, myPoints)
A quadrilateral is a polygon consists of four sides,so you need to define four vertices. The
following is the code:
Un cuadrilátero es un polígono formado por cuatro lados, por lo que necesita para definir
cuatro vértices. El siguiente es el código:
myGraphics.DrawPolygon(myPen, myPoints)
The output image is as shown below:
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:
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.
Para dibujar un sector, puede utilizar el método DrawPie del objeto gráfico. Como siempre, es
necesario crear los gráficos y los objetos Pen. La sintaxis para trazar un pastel es:
Donde X e Y son las coordenadas del rectángulo delimitador, otros argumentos son fáciles de
entender. Tanto startAngle y SweepAngle se miden en grados. SweepAngle puede tener
posibles o negativos valores. Si el valor es positivo, barrer a través de las agujas del reloj
mientras negativo significa que barren a través de dirección hacia la izquierda.
Ejemplo 25.3: Dibujar un pastel que se inicia con 0 grados y barrer las agujas del reloj a través
de 60 grados.
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:
Where myColor can be any color such as red,blue, yellow and more. You don’t have to worry
about the names of the colors because the intellisense will display the colors and enter the
period after the Color key word.
En las lecciones anteriores, hemos aprendido cómo dibujar rectángulo, elipse, círculo,
polígono y pastel con sólo esbozos. En esta lección, vamos a mostrarle cómo llenar las formas
con el color, o simplemente formas sólidas. Tres métodos que se utilizan para rellenar formas
son FillRectangle, FillEllipse, FillPolygon y FillPie.
Con el fin de llenar las formas anteriores con el color, tenemos que crear el objeto Brush
utilizando la siguiente sintaxis:
Dónde myColor puede ser de cualquier color como el rojo, azul, amarillo y más. Usted no tiene
que preocuparse acerca de los nombres de los colores porque el IntelliSense mostrará los
colores y entrar en el período después de la palabra clave de color.
The syntax to fill a rectangle with the color defined by the brush object is:
La sintaxis para llenar un rectángulo con el color definido por el objeto cepillo es:
myGraphics.FillRectangle (MyBrush, 0, 0, 150, 150)
Example 26.1
The syntax to fill a ellipse with the color defined by the brush object is:
La sintaxis para llenar una elipse con el color definido por el objeto cepillo es:
Example 26.2
The syntax to fill a polygon with the color defined by the brush object is:
myGraphics.FillPolygon(myBrush, myPoints)
La sintaxis para llenar un polígono con el color definido por el objeto cepillo es:
myGraphics.DrawPolygon(myPen, myPoints)
myGraphics.FillPolygon(myBrush, myPoints)
The syntax to fill a pie with the color defined by the brush object is:
La sintaxis para rellenar un pastel con el color definido por el objeto pincel es:
In this lesson, we shall show you how to use timer in VB2012. Timer is used to control and
manage events that are time related. For example, you need timer to create a clock, a stop
watch, a dice, animation and more.
En esta lección, vamos a mostrarle cómo utilizar el temporizador en VB2012. Timer se usa
para controlar y gestionar los eventos que son el tiempo correspondiente. Por ejemplo, usted
necesita temporizador para crear un reloj, un cronómetro, un dado, animación y mucho más.
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:
Con el fin de crear un reloj, es necesario utilizar el control Timer que viene con Basic 2012.
Control visual El temporizador es un objeto de control que sólo es utilizado por el
desarrollador, es invisible en tiempo de ejecución y que no permite al usuario interactuar con
ella.
Para crear el reloj, en primer lugar iniciar un nuevo proyecto en Visual Basic 2012 Express y
seleccione una nueva aplicación para Windows. Puede dar al proyecto cualquier nombre que
desee, pero vamos a nombrarla MyClock. Cambie el título del Form1 para MyClock en la
ventana de propiedades. Ahora agregue el control Timer al formulario arrastrándolo desde la
caja de herramientas. A continuación, inserte un control de etiqueta en el formulario. Cambiar
el tamaño de fuente de la etiqueta a 14 o cualquier tamaño que quieran, y establecer la
alineación de fuente para ser centro medio. Antes de que nos olvidemos, pondrás también la
propiedad Interval del control Timer a 1000, lo que refleja un segundo intervalo de un (1
unidad es 1 milisegundo).
Ahora, usted está listo para la codificación. En realidad sería una sorpresa que lo que usted
necesita para crear un reloj es sólo un código de una sola línea, es decir:
Label1.Text = TimeOfDay
Para realmente crear el reloj, haga clic en el control Timer e introduzca el código de seguridad,
como se muestra a continuación:
Label1.Text = TimeOfDay
End Sub
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:
Podemos crear un cronómetro simple utilizando el control Timer. Inicie un nuevo proyecto y el
nombre del cronómetro. Cambie el título Form1 para Cronómetro. Inserte el control Timer en el
formulario y establezca su intervalo de 1000 que es igual a un segundo. También establecer la
propiedad Enabled del temporizador en false para que no se iniciará marcando cuando se
inicia el programa. Inserte tres botones de comando y cambiar sus nombres a StartBtn,
StopBtn y ResetBtn respectivamente. Cambie su texto a "Inicio", "Stop" y "Reset" en
consecuencia. Ahora, introduzca el código de la siguiente manera:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Timer1.Tick
Label1.Text = Val(Label1.Text) + 1
End Sub
Timer1.Enabled = False
End Sub
Timer1.Enabled = True
End Sub
Label1.Text = 0
End Sub
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)
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.
Podemos crear un dado digitales fácilmente utilizando el control Timer. Para crear un dado,
que necesita para generar números al azar utilizando la función Rnd. Vta genera números
entre 0 y 1 La declaración
n = Int (1 + Rnd () * 6)
Dim n, m As Integer
m = m + 10
n = Int(1 + Rnd() * 6)
LblDice.Text = n
Else
Timer1.Enabled = False
m=0
End If
End Sub
Timer1.Enabled = True
End Sub
End Class
Running the program produces a dice with fast changing numbers which stop at a certain
number. The interface is shown below:
Ejecutar el programa produce un dado con los números cambiando rápidamente que paran en
un número determinado. La interfaz se muestra a continuación:
[Lesson 26] << [CONTENTS] >> [Lesson 28]
Visual Basic 2012 Lesson 28– Creating Animation
Visual Basic 2012 Lección 28- Creación de animaciones
[Lesson 27] << [CONTENTS] >> [Lesson 29]
Although Visual Basic 2012 is generally a programming language designed for creating
business and other industrial applications and not for creating animation, it can be used to
create animation. In this lesson, we will show you just that.
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.
Inicie un nuevo proyecto y el nombre como objeto móvil, o cualquier nombre que desee. Ahora
insertar un cuadro de imagen y en su importación Propiedad de la imagen de una imagen de
su disco duro u otras fuentes. Luego, inserte cuatro botones de comando, cambiar sus títulos
a Subir, Bajar, Mover a la izquierda y Mover a la derecha. Nombre de ellos como MoveUpBtn,
MoveDowbBtn, MoveLeftBtn y MoveRightBtn.
End Sub
PictureBox1.Left = PictureBox1.Left – 10
End Sub
PictureBox1.Left = PictureBox1.Left + 10
End Sub
Explanation:
Each time the user clicks on the Move Down button, the distance of the PictureBox increases
by 10 pixels from the top border, creating a downward motion. On the other hand, each time
the user clicks on the Move Up button, the distance of the PictureBox decreases by 10 pixels
from the top borders, thus creating an upward motion. In addition, each time the user clicks on
the Move Left button, the distance of the PictureBox decreases by 10 pixels from the left
border, thus creating a leftward motion. Lastly, each time the user clicks on the Move Right
button, the distance of the PictureBox increases by 10 pixels from the left border, thus creating
an rightward motion.
explicación:
Cada vez que el usuario hace clic en el botón Mover hacia abajo, la distancia de los
PictureBox se incrementa en 10 píxeles desde el borde superior, la creación de un movimiento
hacia abajo. Por otro lado, cada vez que el usuario hace clic en el botón Mover hacia arriba, la
distancia de la PictureBox disminuye por 10 píxeles desde la parte superior de las fronteras,
creando así un movimiento hacia arriba. Además, cada vez que el usuario hace clic en el
botón Mover Izquierda, la distancia de la PictureBox disminuye por 10 píxeles desde el borde
izquierdo, creando así un movimiento hacia la izquierda. Por último, cada vez que el usuario
hace clic en el botón Mover a la derecha, la distancia de los PictureBox se incrementa en 10
píxeles desde el borde izquierdo, creando así un movimiento hacia la derecha.
The interface is shown below: La interfaz se muestra a continuación:
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:
Podemos crear animación continua usando temporizador sin necesidad de hacer clic
manualmente un botón de comando. Podemos crear izquierda a derecha o de arriba a abajo el
movimiento al escribir el código necesario.
Hacemos uso de la propiedad Left del PictureBox para crear el movimiento. PictureBox.Left
significa la distancia de PictureBox desde el borde izquierdo del formulario. Ahora haga clic en
el control Timer y escriba el siguiente código:
PictureBox1.Left = PictureBox1.Left + 10
Else
PictureBox1.Left = 0
End If
End Sub
In the code above, Me.Width represents the width of the Form. If the distance of the PictureBox
from the left is less than the width of the Form, a value of 10 is added to the distance of the
PictureBox from the left border each time the Timer tick, or every 0.1 second in this example.
When the distance of the PictureBox from the left border is equal to the width of the form, the
distance from the left border is set to 0, which move the PictureBox object to the left border and
then move left again, thus creates an oscillating motion from left to right. We need to insert a
button to stop motion. The code is:
En el código anterior, Me.Width representa el ancho del formulario. Si la distancia del cuadro
de imagen de la izquierda es menor que el ancho del formulario, se añade un valor de 10 a la
distancia del cuadro de imagen desde el borde izquierdo cada vez que la señal de
temporizador, o cada 0,1 segundos en este ejemplo. Cuando la distancia de PictureBox desde
el borde izquierdo es igual a la anchura de la forma, la distancia desde el borde izquierdo se
establece en 0, el cual se mueve el objeto PictureBox a la frontera izquierda y luego moverse
a la izquierda de nuevo, por lo que crea un movimiento oscilante de izquierda a derecha.
Tenemos que insertar un botón para detener el movimiento. El código es:
Timer1.Enabled = False
To animate the PictureBox object, we insert a command button and key in the following code:
Timer1.Enabled = True
The Image of the Animation program is shown below: La imagen del programa de animación se muestra a continuación:
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
En nuestra vida diaria, nos ocupamos de muchos tipos de información o datos tales como
nombres, direcciones, el dinero, la fecha, cotizaciones de bolsa, estadísticas y mucho más. Si
estás en el negocio o trabajar como un profesional, usted tiene que manejar más datos. Por
ejemplo, un médico tiene que realizar un seguimiento de la información personal y médica de
los pacientes, tales como nombres, direcciones, números de teléfono, así como lecturas de la
presión arterial, las lecturas de azúcar en la sangre, antecedentes quirúrgicos, medicamentos
prescritos en el pasado y más. Por otro lado, las empresas normalmente tienen que gestionar
gran cantidad de datos relativos a los productos y clientes. Todos estos datos deben ser
organizados en una base de datos para la facilidad de gestión de datos.
En el pasado, la gente por lo general se refieren a los datos de forma manual, como el uso de
tarjetas y carpetas. Sin embargo, en la actual ritmo rápido medio ambiente mundial y la edad
de la información, ya no es viable para gestionar los datos de forma manual. La mayoría de los
datos ahora se gestionan mediante sistemas de gestión de bases de datos basadas en la
informática. Sistemas de gestión de bases de datos basados en computadoras pueden
manejar datos mucho más rápidas y más eficientes que los seres humanos hacen. Con la
llegada de la red y las tecnologías de Internet, los datos se pueden gestionar de forma local y
remota. Las empresas suelen invertir fuertemente en sistemas de gestión de bases de datos
con el fin de ejecutar las organizaciones de manera eficiente y eficaz. Sistemas de gestión de
bases de datos se utilizan por lo general en el funcionamiento de sistema de nómina, sistema
de inventarios, sistema, sistema de pago, sistema de gestión de órdenes, sistema de gestión
de relaciones con clientes (CRM) y más que representan. Algunos de los sistema de gestión
de bases de datos comerciales (DBMS) son Oracle, Microsoft SQL Server y Microsoft Access
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.
Visual Basic 2012 uses ADO.NET to handle databases. ADO.NET is Microsoft’s latest database technology which can
works with many other advanced database management system such as Microsoft SQL server. In this lesson, we
will develop codes that make use of Microsoft SQL Server 2012, therefore you need to have Microsoft SQL Server
2012 installed in your PC, you can download Microsoft SQL Server 2012 Express for
Visual Basic 2012 utiliza ADO.NET para manejar bases de datos. ADO.NET es la última tecnología de base de datos
de Microsoft que puede trabaja con muchos otros sistemas de gestión de bases de datos avanzadas, como
Microsoft SQL Server. En esta lección, vamos a desarrollar códigos que hacen uso de Microsoft SQL Server 2012,
por lo tanto, es necesario tener Microsoft SQL Server 2012 instalado en su PC, puede descargar Microsoft SQL
us/download/details.aspx?id=29062
To begin building the database project in Visual Basic 2012, launch Visual Basic 2012. You
can name your project as Database Project 1 or what ever name you wish to call it. Next,
change the default form’s Text property to Contacts as we will be building a database of
contact list. There are a few objects in ADO.NET that are required to build the database. There
are:
Para comenzar a construir el proyecto de base de datos en Visual Basic 2012, Visual Basic
inicia 2012. Usted puede nombrar su proyecto como Project Database 1 o lo que sea el
nombre que desea llamar. A continuación, cambie la propiedad Text del formulario
predeterminado a Contactos ya que estaremos construyendo una base de datos de la lista de
contactos. Hay unos cuantos objetos de ADO.NET que se requieren para construir la base de
datos. Hay:
We shall proceed to create connection to the database source file in the next lesson.
In Visual Basic 2012, we need to create connection to a database before we can access its
data. Before we begin, let’s create a new database. Since we are using SQL Server 2012 as
the database engine, we will use Microsoft Studio Management Express to create a
database with the mdf extension. We shall name this database file as test.mdf. After creating
the database, build a table called Contacts and create two fields and name them ContactName
and State respectively. Enter a few data in the table and click Save All to save the data. Now
we are ready to connect to this new database.
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:
* 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()
En Visual Basic 2012, tenemos que crear la conexión a una base de datos antes de poder
acceder a sus datos. Antes de empezar, vamos a crear una nueva base de datos. Ya que
estamos usando SQL Server 2012 como el motor de base de datos, vamos a utilizar Microsoft
Management Studio Express para crear una base de datos con la extensión mdf. Vamos a
llamar a este archivo de base de datos como test.mdf. Después de crear la base de datos,
crear una tabla llamada Contactos y crear dos campos y nombrarlos ContactName y el
Estado, respectivamente. Introduzca unas pocas de datos en la tabla y haga clic en Guardar
todo para guardar los datos. Ahora estamos listos para conectarse a esta nueva base de
datos.
Después de establecer la conexión a la base de datos, se puede abrir la base de datos con la
siguiente sintaxis:
MyCn.Open ()
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:
El siguiente paso es crear una instancia de la SqlDataAdpater en nuestro código para que
podamos llenar el DataTable con los datos del origen de datos. Además, también es necesario
para crear una instancia de la DataTable. Aparte de eso, también se debe crear una instancia
de theSqlCommandBuilder que se utiliza para manipular los datos, tales como la actualización
y supresión de datos en el Datatable y enviar los cambios a la fuente de datos. Los estados
son:
Besides that, we need to declare a variable to keep track of the user’s current row within the
data table. The statement is
Además de eso, tenemos que declarar una variable para realizar un seguimiento de la fila
actual del usuario dentro de la tabla de datos. La declaración es
Having created the above of objects, you need to include the following statements in the Sub
Form_Load event to start filling the DataTable with data from the data source. The statements
are as follows:
Después de haber creado las anteriores de los objetos, es necesario incluir las siguientes
declaraciones en el evento Form_Load Sub para comenzar a llenar el DataTable con los datos
del origen de datos. Los estados son los siguientes:
After filling up the DataTable , we need to write code to access the data. To access data in the
DataTable means that we need to access the rows in the table. We can achieve this by using
the DataRow object. For example, we can write the following to access the first row of the table
and present the data via two text boxes with the name txtName and txtState respectively:
Después de llenar el DataTable, tenemos que escribir código para acceder a los datos. Para
acceder a los datos en el DataTable significa que tenemos que acceder a las filas de la tabla.
Podemos lograr esto mediante el uso del objeto DataRow. Por ejemplo, podemos escribir lo
siguiente para acceder a la primera fila de la tabla y presentar los datos a través de dos
cuadros de texto con el nombre txtName y txtState respectivamente:
strName = MyDataRow(“ContactName”)
strState = MyDataRow(“State”)
txtName.Text = strName.ToString
txtState.Text = strState.ToStringMe.showRecords()
* The two fields being referenced here are ContactName and State. Note Index 0 means first
row.
showRecords() is a sub procedure created to show data in the text boxes. The code is as
follows:
* Los dos campos que se hace referencia aquí son ContactName y Estado. Nota Índice 0
significa primera fila.
showRecords () es un procedimiento sub creado para mostrar los datos en los cuadros de
texto. El código es el siguiente:
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
In previous lessons, you have learned how to connect to a database as well as filling up the
table with data in Visual Basic 2012, now you shall learn how to manipulate data in the
database. Manipulating data means adding news records, editing records, deleting records,
browsing records and more.
En las lecciones anteriores, usted ha aprendido cómo conectarse a una base de datos, así
como llenar la tabla con datos en Visual Basic 2012, ahora usted deberá aprender a manipular
los datos en la base de datos. La manipulación de los datos significa añadir registros de
usuarios, la edición de registros, eliminar registros, registros de navegación y mucho más.
this lesson, we will create command buttons and write relevant codes to allow the user to browse the records
forward and backward as well as fast forward to the last record and back to the first record.The first button
we need to create is for the user to browse the first record. We can use button’s text << to indicate to the
user that it is the button to move to the first record and button’s text >> to move to the last record. Besides
we can use button’s text < for moving to previous record and button’s text > for moving to next record.
En la lección anterior, hemos aprendido cómo mostrar el primer registro, usando el procedimiento
showRecords sub. En esta lección, vamos a crear botones de comando y escribir códigos pertinentes para
permitir al usuario navegar por los registros hacia adelante y hacia atrás, así como el avance rápido hasta el
último registro y volver al primer botón record.The primero tenemos que crear es para el usuario navegar por
el primer registro. Podemos utilizar el texto del botón << para indicar al usuario que es el botón para
desplazarse al primer registro y el texto del botón >> para mover al último registro. Además podemos utilizar
el texto del botón <para mover al registro anterior y el texto del botón> para mover al siguiente registro.
The code for moving to the first record is: El código para moverse al primer
registro es:
MyRowPosition = 0
Me.showRecords()
The code for moving to previous record is: El código para mover al récord
anterior es:
MyRowPosition = MyRowPosition – 1
Me.showRecords()
End If
The code for moving to next record is: El código para mover al siguiente registro es:
The code for moving to last record is: El código para mover al último registro es:
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:
Puede editar cualquier registro, vaya hasta el registro y cambiar los valores de los datos. Sin
embargo, es necesario guardar los datos después de la edición de ellos. Es necesario utilizar
el método de actualización del SqlDataAdapter para guardar los datos. El código es:
También puede agregar nuevo registro o una nueva fila a la tabla usando el siguiente código:
The code above will present a new record with blank fields for the user to enter the new data.
After entering the data, he or she can then click the save button to save the data.
El código anterior presentará un nuevo registro con campos en blanco para que el usuario
introduzca los nuevos datos. Una vez introducidos los datos, él o ella puede hacer clic en el
botón Guardar para guardar los datos.
Lastly, the user might want to delete the data. The code to delete the data is:
Por último, el usuario podría querer borrar los datos. El código para eliminar los datos es:
La interfaz del programa Visual Básico base de datos de 2012 se muestra a continuación:
Finally, you have learned how to create a database application in Visual Basic 2012. Please try
to create your very own database applications in Visual Basic 2012 from now on.
Por último, usted ha aprendido cómo crear una aplicación de base de datos en Visual Basic
2012 Por favor, intente crear sus propias aplicaciones de base de datos en Visual Basic 2012
a partir de ahora.
Price: $25.00
Dear Friend,
Visual Basic 2010 Made Easy is an eBook written by the webmaster of our
Visual Basic 2010 Tutorial , Dr.Liew. With more than 200 pages of
contents,it complements our free online tutorial by providing a complete tutorial
for beginners.
Estimado amigo,
Visual Basic 2010 Made Easy es un libro electrónico escrito por el webmaster de nuestro
Tutorial de Visual Basic 2010, Dr.Liew. Con más de 200 páginas de contenido, que
complementa nuestro tutorial en línea gratis, proporcionando un completo tutorial para
principiantes.
Warmest Regards
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
Descargo de responsabilidad
Este sitio y los productos y servicios ofrecidos en este sitio no están asociados, afiliados,
avalados o patrocinados por Microsoft, ni han sido revisados probado o certificado por
Microsoft.