VB Notes and Solutions
VB Notes and Solutions
Visual Basic 2010 is the latest version of Visual Basic launched by Microsoft in 2010.
VB2010 is almost similar to Visual Basic 2008, but it has added many new features. Like
Visual Basic 2008 , Visual Basic 2010 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.
However, you don't have to know OOP to learn VB2010. In fact, if you are familiar with
Visual Basic 6, you can learn VB2010 effortlessly because the syntax and interface are
similar. Visual Basic 2010 Express Edition is available free for download from the Microsoft
site. Click on this link Visual Studio to download Vb2010. After installation, you need to
register your copy of Visual Basic 2010 Express, otherwise, it will expire in 30 days. The
registration is free provided you have a Microsoft account.
The dialog box offers you five 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 exampe, myFirstProgram. After you
have renamed the project, click OK to continue. The following IDE Windows will appear, it
is almost similar to Visual Basic 6. It consists of an empty form, the toolbox tab and the
properties. The layout is slightly different from vb2008 as 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.
Now 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:
Next, click on the OK button and the code window appears. Enter the code as follows:
When you run the the program and click on the OK button, a dialog box will appear and
display the "WELCOME TO VISUAL BASIC 2010" message,as shown below:
Lesson 2: Working with Controls
The Controls in Visual Basic 2010 are objects that can be placed on the form to perform
various tasks. To view the controls in VB2010, click on the Toolbox tab to bring up the
common controls Toolbox as shown in Figure 2.1. The controls 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.
Figure 2.1
To insert a control into your form, you just need to drag the control and drop it onto the form.
You can reposition and resize it as you like. Lets examine a few programs that made use
of Button, Label, TextBox , ListBox and PictureBox . You don't have to worry so much
about the code because I will explain the program syntax as you progress to laterlessons.
Figure 2.4
2.2 Using the Text Box
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. Now change the label on the button to Calculate,then click on this button and enter
the following code:
End Sub
When you run the program and enter two numbers, pressing the calculate button can let the
progam performs addition of the two numbers, as shown in Figure 2.5.
Lesson 3: Working with Control
Properties
3.1 The Control Properties
Before writing an event procedure for the control to response to a user's input, 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 at design
time or at runtime. Figure 3.1 is a typical properties window for a form. It refers particularly
to interface of the program as shown in Figure 3.2.
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. VB2010 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 codes).
End Sub
End Class
You may also use the follow procedure to assign the color at run time.
Me.BackColor = Color.Magenta
End Sub
Both procedures above will load the form with a magenta background as shown in Figure 3.3
Figure 3.3
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.
The following is another program that allows the user to enter the RGB codes into three
different textboxes and when he/she clicks the display color button, the background color of
the form will change according to the RGB codes. This program allows users to change the
color properties of the form at run time.
The code
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim rgb1, rgb2, rgb3 As Integer
rgb1 = TextBox1.Text
rgb2 = TextBox2.Text
rgb3 = TextBox3.Text
Me.BackColor = Color.FromArgb(rgb1, rgb2,rgb3)
End Sub
The Output
Figure 3.4
First of all, let me say that though VB2010 is very much similar to VB6 in terms of Interface
and program structure, their underlying concepts are quite different. The main different is that
VB2010 is a full Object Oriented Programming Language while VB6 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:
Encapsulation
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
In object-oriented programming, classes are created according to hierarchies. 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.
Polymorphism
Object-oriented pogramming 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.
Visual Basic 6 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. On the other hand, Visual Basic
2010 is a fully functional Object Oriented Programming Language, just like other OOP such
as C++ and Java. It is different from VB6 because it focuses more on the data itself while
VB6 focuses more on the actions. VB6 and earlier versions of VB are known as procedural or
functional programming language. Some other procedural programming languages are C,
Pascal and Fortran.
VB2010 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 asubclassof theplantclass and the apple in your backyard is an
instance of the apple tree class. Another example is a 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 VB2010, the program structure to
define a Human class can be written as follows:
After you have created the human class, you can create a subclass that inherits the attributes
or data from the human class. For example, you can create a students class that is a subclass
of the human class. Under the student class, you don't have to define any data fields that are
already defined under the human class, you only have to define the data fields that are
different from an instance of the human class. For example, you may want to include
StudentID and Address in the student class. The program code for the StudentClass is as
follows:
End Sub
We will discuss more on OOP in later lessons. In the next lesson, we will start learning
simple programming techniques in VB2010
A class has events as it creates an instant of a class or an object. When we start a windows
application in VB2010 in previous chapters, we will see a default form with the 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 window in Figure 5.1.
End Sub
End Class
In addition, there are other events associated with the Form1 class. These events are click,
cursorChanged, DoubleClick, DragDrop, Enter and so on, as shown in Figure 5.2(It appears
when you click on the upper right pane of the code window)
Figure 5.2 The Events
5.2 Writing the code
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 :
End Sub
End Class
The first line of the code will change the title of the form to My First VB2010 Program, the
second line will change the foreground object to Forest Green( in this case, it is a label that
you insert into the form and change its name to Foreground) and the last line changes the
background to Csyan color. The equal in the code actually 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 porgrammer.
End Sub
In this example, you insert one command button into the form and rename its caption as
Show Hidden Names. The keyword Dim is to declare variables name1, name2 and name3 as
string, which means they can only handle text. The function MsgBox is to display the names
in a message box that are joined together by the "&" signs. The output is as shown in Figure
5.4
Figure 5.4
Table 6.3
Suffix Data Type>
& Long
! Single
# Double
@ Currency
In addition, we need to enclose string literals within two quotations and date and time literals
within two # sign. Strings can contain any characters, including numbers. The following are
few examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
My_Car My.Car
ThisYear 1NewBoy
You may also combine them in one line, separating each variable with a comma, as follows:
For string declaration, there are two possible formats, one for the variable-length string and
another for the fixed-length string. For the variable-length string, just use the same format as
example 6.1 above. However, for the fixed-length string, you have to use the format as shown
below:
Example 6.2
Dim yourName as String * 10
yourName can hold no more than 10 Characters.
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:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
6.3 Constants
Constants are different from variables in the sense that their values do not change during the
running of the program.
Example 7.1
In this program, you need to insert two Textboxes, four labels and one button. Click the
button and key in the code as shown below. Note how the various arithmetic operators are
being used. When you run the program, it will perform the four basic arithmetic operations
and display the results on the four labels.
c^2=a^2+b^2
The Code
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 could 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).
The Code
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArsgs) Handles Button1.Click
Dim height, weight, bmi As Single
height = TextBox1.Text
weight = TextBox2.Text
bmi = (weight) / (height ^ 2)
Label4.Text = bmi
End Sub
The output is shown in the Figure 7.1 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=0.45359237 kilogram)
From the above examples, you can see that perform arithmetic operations is relatively easy.
Here are more arithmetic projects you can try to programs:
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
Example 8.1(a)
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim text1, text2, text3 As String
text1 = "Visual"
text2 = "Basic"
text3 = text1 + text2
Label1.Text = text3
End Sub
The line text3=text1+ text2 can be replaced by text3=text1 & text2 and produced 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.
Example 8.2
Dim text1, text3 as string
Dim Text2 As Integertext1 = "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.
You can combine more than two strings to form a larger strings, like the following example:
Running the above program will produce the following screen shot, as shown in Figure 8.1
Figure 8.1
8.2 String Manipulation Using VB2010 Built-in Functions
A function is similar to a normal procedure but the main purpose of the function is to accept
a certain input and return a value which is passed on to the main program to finish the
execution.There are numerous string manipulation functions built into VB2010 but I will
only discuss a few here and will explain the rest of them in later lessons.
Len ("Phrase")
For example,
Example 8.3
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = Len(TextBox1.Text)
End Sub
End Class
Figure 8.2
8.2(b) The Right Function
The Right function extracts the right portion of a phrase. The syntax is
Microsoft.VisualBasic.Right("Phrase",n)
Example 8.3
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim text1 As String
text1 = TextBox1.Text
Label1.Text = Microsoft.VisualBasic.Right(text1, 4)
End Sub
The above program will return four right most characters of the phrase entered into the
textbox.
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,
= Equal to
If condition Then
End If
Example 9.1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim myNumber As Integer
myNumber = TextBox1.Text
If myNumber > 100 Then
Label2.Text = " You win a lucky prize"
End If
End Sub
* When you run the program and enter a number that is greater than 100, you will see the
"You win a lucky prize" statement. On the other hand, if the number entered is less than or
equal to 100, you don't see any display.
If condition Then
End If
Example 9.2: Using If...Then...Else
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim myNumber As Integer
myNumber = TextBox1.Text
If myNumber > 100 Then
Label2.Text = " Congratulation! You win a lucky prize"
Else
Label2.Text = " Sorry, You dif not win any prize"
End If
End Sub
* When you run the program and enter a number that is greater than 100, the statement
"Congratulation! You win a lucky prize" will be shown. On the other hand, if the number
entered is less than or equal to 100, you will see the "Sorry, You dif not win any prize"
statement
Example 9.3
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim myNumber, MyAge As Integer
myNumber = TextBox1.Text
MyAge = TextBox2.Text
* This program uses the logical And operator besides 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.
Else
Visual Basic 2010 expression
End If
Example 9.4
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim Mark As Integer
Dim Grade as String
Mark = TextBox1.Text
If myNumber >=80 Then
Grade="A"
ElseIf Mark>=60 and Mark<80 then
Grade="B"
ElseIf Mark>=40 and Mark<60 then
Grade="C"
Else
Grade="D"
End If
End Sub
Example 10.1
' Examination Grades
Dim grade As String
Private Sub Compute_Click( )
grade=txtgrade.Text
Select Case grade
Case "A"
Label1.Text="High Distinction"
Case "A-"
Label1.Text="Distinction"
Case "B"
Label1.Text="Credit"
Case "C"
Label1.Text="Pass"
Case Else
Label1.Text="Fail"
End Select
End Sub
Example 10.2
In this example, you can use the keyword Is together with the comparison operators.
End Sub
Example 10.3
Example 10.2 can be rewritten as follows:
End Sub
Lesson 11 : Looping
In Visual Basic 2010 programming, a sequence of instructions that is repeated until a certain
condition is met is called looping. For example, we can write VB code that adds a series of
numbers until the sum exceeds a certain value or a VB program that asks the user to enter
data repeatedly until he or she enters the word 'Finish'. In Visual Basic 2010, we have three
types of Loops, they are the For.....Next loop, the Do loop. and the While.....End while loop
Example 11.1 a
Dim counter as Integer
For counter=1 to 10
ListBox1.Items.Add (counter)
Next
Example 11.1b
Dim counter , sum As Integer
For counter=1 to 100 step 10
sum+=counter
ListBox1.Items.Add (sum)
Next
Example 11.1c
Dim counter, sum As Integer
sum = 1000
For counter = 100 To 5 Step -5
sum - = counter
ListBox1.Items.Add(sum)
Next
*Notice that increment can be negative.The program will compute the subtraction as follow:
1000-100-95-90-..........
Example 11.1d
Dim n as Integer
For n=1 to 10
If n>6 then
Exit For
End If
Else
ListBox1.Items.Add ( n)
Next
End If
Next
The process will stop when n is greater than 6.
a)
Do While condition
Block of VB 2010 statements
Loop
b)
Do
Block of VB2010 statements
Loop While condition
c)
Do Until condition
Block of VB2010 statements
Loop
d)
Do
Block of VB 2010 statements
Loop Until condition
Sometimes we need to exit a loop prematurely because a condition is fulfilled. The keyword
to use is known as Exit Do.Let's examine the following examples
Example 11.2(a)
Do while counter <=1000
TextBox1.Text=counter
counter +=1Loop
Do
TextBox1.Text=counter
counter+=1
Loop until counter>1000
Example 11.2(b)
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
In the above example, we find the arithmetic summation of 1+2+3+4+......+100. In the design
stage, you need to insert a ListBox into the form for displaying the output.The program uses
the Add method to populate the ListBox. The statement
will display the headings in the ListBox, where it uses the vbTab function to create a space
between the heading n and sum.
The statement
will list the number n and the values of the arithmetic summation. The output is displayed
below:
The above loop means that while the condition is not met, the loop will go on.The loop will
end when the condition is met.
Example 11.3
Dim sum, n As Integer
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim sum, n As Integer
While n <> 100
n += 1
sum = sum + n
ListBox1.Items.Add(n & vbTab & sum)
End While
End Sub
Lesson 12 : Functions
A Visual Basic 2010 function is a type of procedure that returns a value which is passed on to
the main procedure to finish the execution. A function is similar to a sub procedure but there
is one major difference, a function returns a value whilst a sub procedure does not.
In Visual Basic 2010, there are two types of functions, the built-in functions and the functions
created by the programmers. Functions created by the programmer are also known as user-
defined functions. In this lesson, we shall learn how to create the user-defined function.
or
The keyword Public indicates that the function is applicable to the whole project and the
keyword Private indicates that the function is only applicable to a certain module or
procedure. The argument is a parameter that can pass a value back to the function.There is no
limit to the number of arguments you can put in.
Example 12.1: BMI Calculator
This BMI calculator is a Visual Basic 2010 program that can calculate the body mass index
of a person based on his or her 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 the BMI is more than 30, a person is considered obese. You can refer to the following range of
BMI values for your weight status.
Underweight = <18.5
Normal weight = 18.5-24.9
Overweight = 25-29.9
Obesity = BMI of 30 or greater
The Code
Public Class Form1
Figure 12.1
For example, let's say you deposit $1000 in a bank and the bank is paying you 5% compound
interest annually. After the first year, you will earn an interest of $1000x0.05=$50. The new
principal will be $1000+$1000x0.05=$1000(1+0.05)=$1000(1.05)=$1050. After the second
year, the new principal is $1000(1.05)x1.05=$1000(1.05)2 =$1102.50. This new principal is
called the future value. Following the above calculation, the future value after n years will be
FV = PV * (1 + i / 100)n
Where PV represents the present value, FV represents the future value, i is the interest rate
and n is the number of periods (Normally months or years).
The Code
Public Class Form1
Private Function FV(pv As Single, i As Single, n As Integer)
As Double
FV = pv * (1 + i / 100) ^ n
End Function
Private Sub BtnCal_Click(sender As Object, e As EventArgs)
Handles BtnCal.Click
interest = TxtInt.Text
period = TxtN.Text
Figure 12.2
For example,
Example 12.2(a)
In this example, we created two functions that compute the square root of a number, the first
uses the keyword ByRef and the second uses the keyword ByVal.
The Code
Public Class Form1
End Sub
End Class
The Output
Case 1: Passing argument using ByRef
Figure 12.3
Figure 12.4
Mid(phrase, position,n)
phrase is the string from which a part of the text is to be retrieved. position is the starting position of
the phrase from which the retrieving process begins. n is the number of characters to retrieve.
Example 13.1:
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim myPhrase As String
myPhrase = Microsoft.VisualBasic.InputBox("Enter your
phrase")
Label1.Text = Mid(myPhrase, 2, 6)
End Sub
* When the user clicks the command button, an input box will pop up asking the user to enter
a phrase. After a phrase is entered and 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, as
shown in the figures below:
Figure 13.1
Figure 13.2
13.2 The Right Function
The Right function extracts the right portion of a phrase. The syntax 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 ("Phrase", n)
TWhere n is the starting position from the left of the phase where the portion of the phrase is
going to be extracted. For example:
Trim("Phrase")
For example,
Trim (" Visual Basic 2010 ") = Visual basic 2010
Example 13.4
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim myPhrase As String
myPhrase = Microsoft.VisualBasic.InputBox("Enter your
phrase")
Label1.Text = Trim(myPhrase)
End Sub
Ltrim("Phrase")
TFor example,
Rtrim("Phrase")
TFor example,
TWhere n is the position where the Instr function will begin to look for the embedded phrase.
For example
TThe syntax is
Microsoft.VisualBasic.UCase(Phrase)
Microsoft.VisualBasic.LCase(Phrase)
TFor example,
Chr(charcode)
Asc(Character)
TThe 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.
Table 13.1
Style Value Named Constant Buttons Displayed
0 vbOkOnly Ok button
TWe can use named constants in place of integers for the second argument to make the
programs more readable. In fact, Visual Basic 2010 will automatically show up a list of
named constants where you can select one of them.
Examples:
TyourMsg 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 13.2 shows
the values, the corresponding named constant and buttons.
Table 13.2
Value Named Constant Button Clicked
1 vbOk Ok button
7 vbNo No button
Example 13.5
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
MessageBox.Show("You have clicked the OK button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub
TTo make the message box looks more sophisticated, you can add an icon beside the
message. There are four types of icons available in Visual Basic 2010 as shown in Table 13.3
Table 13.3
Value Named Constant Icon
16 vbCritical
3 vbQuestion
48 vbExclamation
64 vbInformation
Example 13.6
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim testMsg As Integer
testMsg = MsgBox("Click to Test", vbYesNoCancel +
vbExclamation, "Test Message")
If testMsg = 6 Then
MessageBox.Show("You have clicked the yes button")
ElseIf testMsg = 7 Then
MessageBox.Show("You have clicked the NO button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub
The input box will appear as shown in the figure below when you press the command button
Lesson 14 : The Math functions
We have learned how to VB2010 can perform arithmetic functions using standard
mathematical operators. However, for more complex mathematical calculations, we need to
use the built-in math functions in VB2010. There are numerous built-in mathematical
functions in Visual Basic which we will introduce them one by one.
The syntax is
Math.Abs(number)
*The Math keyword here indicates that the Abs function belong to the Math class. However,
not all mathematical functions belong to the Math class.
The syntax is
Math.Exp(number)
Example:
Example:
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Example 14.3
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Math.Log(num1)
Label1.Text = num2
End Sub
Example 14.4
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim num as integer
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.
* The Math keyword indicates that the Round function belongs to the Math class.
Example 15.1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click,
Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format(8972.234, "General Number")
Label2.Text = Format(8972.2, "Fixed")
Label3.Text = Format(6648972.265, "Standard")
Label4.Text = Format(6648972.265, "Currency")
Label5.Text = Format(0.56324, "Percent")
End Sub
Example 15.2
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click,
Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format(8972.234, "0.0")
Label2.Text = Format(8972.2345, "0.00")
Label3.Text = Format(6648972.265, "#,##0.00")
Label4.Text = Format(6648972.265, "$#,##0.00")
Label5.Text = Format(0.56324, "0%")
End Sub
Figure 15.2
Format (Now, "General date") Formats the current date and time.
Format (Now, "Long Date") Displays the current date in long format
Format (Now, "Long Time") Display the current time in long format.
Format (Now, "Short Time") Display the current time in short format.
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"
Example 16.1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = Format(Now,"General Date")
Label2.Text = Format(Now, "Long Date")
Label3.Text = Format(Now, "short Date")
Label4.Text = Format(Now, "Long Time")
Label5.Text = Format(Now, "Short Time")
End Sub
Format (expression,style)
Table 16.2 Some of the user-defined format functions for date and time
Format Explanation
Example 16.2
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click,
Button2.Click, Button3.Click
Label1.Text = Format(Now, "M")
Label2.Text = Format(Now, "MM")
Label3.Text = Format(Now, "MMM")
Label4.Text = Format(Now, "MMMM")
Label5.Text = Format(Now, "dd/MM/yyyy")
Label6.Text = Format(Now,"MMM,d,yyyy")
Label7.Text = Format(Now, "h:mm:ss tt")
Label8.Text = Format(Now, "MM/dd/yyyy h:mm:ss tt")>
End Sub
The code
Private Sub BtnCalculate_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
BtnCalculate.Click
Const LX As Integer = 100
Const BN As Integer = 500
Const SD As Integer = 200
Const HD As Integer = 80
Const HM As Integer = 300
Const AM As Integer = 150
Dim sum As Integer
Figure 17.1
Here is another example
Example 17.2
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Const large As Integer = 10.0
Const medium As Integer = 8
Const small As Integer = 5
Dim sum As Integer
If CheckBox1.Checked = True Then
sum += large
End If
Figure 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.
The code
The output
Figure 17.3
* The above program uses the CheckedChanged event to respond to the user selection by
checking a particular checkbox, 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)
Figure 18.1
The Code
Dim strColor As String
Private Sub RadioButton8_CheckedChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
RadioButton8.CheckedChanged
strColor = "Red"
End Sub
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 2010 by using the Groupbox control under
the containers categories. After inserting the Groupbox 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
The code
Dim strColor As String
Dim strSize As String
First, start a new project in Visual Basic 2010 and name it with any name you like. Here we
use 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. This
engine is the WebBrowser control, located on the Toolbox on the left side. Set its size
property to 600,400. Next, drag a text box and place it at the top of the WebBrowser control,
this serves as 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.
End Class
Now run the program , type in any URL and click the Go button. You will be able to browse
any web page you want.
Figure 19.2: The Runtime Interface
Since Visual Basic evolved into a fully OOP language under the VB.net framework, shape
controls are no longer available. Now the programmer needs to write code to create various
shapes and drawings. Even though the learning curve is steeper, the programmer can write
powerful code to create all kinds of graphics. You can even design your own controlsVisual
Basic 2010 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 VB interface.
21.1 Creating the Graphics Object
Before you can draw any graphic on a form, you need to create the Graphics object in
vb2010. A graphics object is created using a CreateGraphics() method. You can create a
graphics object that draws to the form itself or a control. For example, if you wish to draw to
the form, you can use the following statement:
*Always use Dim to define the object. Using me instead of Form1 because it is not allowed
in Visual Basic 2010.
Or if you want the graphics object to draw to a picturebox, you can write the following
statement:
You can also use the text box as a drawing surface, the statement is:
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.
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
defines the width of the drawing line.
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.
In this section, we will show you how to draw a straight line on the Form. First of all, launch
Visual basic 2010 Express. In the startup page, drag a button into the form. Double click on
the button and key in the following code.
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim myGraphics As Graphics = me.CreateGraphics
Dim myPen As Pen
myPen = New Pen(Brushes.DarkMagenta, 10)
myGraphics.DrawLine(myPen, 10, 10, 100, 10)
End Sub
The second created the Graphics object and the third and fourth line create the Pen object.
The fifth draw a line on the Form using the DrawLine method. The first argument use the Pen
object created by you, the second argument and the third arguments define the coordinate the
starting point of the line, the fourth and the last arguments define the ending coordinate of the
line. The general syntax of the Drawline argument is
Method 1
Use 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 syntax is:
myGrapphics.DrawRectangle(myPen, X, Y, width, height)
*myGraphics is the variable name of the Graphics object and myPen is the variable name of
the Pen object created by you. X, Y is the coordinate of the upper left corner of the rectangle.
The code
Dim myPen As Pen
myPen = New Pen(Drawing.Color.Blue, 5)
Dim myGraphics As Graphics = Me.CreateGraphics
myGraphics.DrawRectangle(myPen, 0, 0, 100, 50)
Method 2
Create a rectangle object first and then draw this rectangle using the DrawRectangle method.
The syntax is as shown below:
myGraphics.DrawRectangle(myPen,myRectangle)
You can also create a rectangle object using a one-line code as follows:
myGraphics.DrawRectangle(myPen, myRectangle)
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. In addition, other DashStyles values are Dash, DashDot, DashDotDot and Solid.The following
code draws a rectangle with the blue dotted line.
Figure 22.1
If you change the DashStyle value to DashDotDot, you can draw rectangles with different
border, as shown in Figure 22.2.
The possible values of the line DashStyle of the Pen are listed in the table below:
Figure 23.1
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
complete the job.
On the other hand, we can also draw an ellipse with the DrawEllipse method without first
creating a rectangle. We shall illustrate both methods.
In the first method, let's 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:
myGraphics.DrawEllipse(myPen, myRectangle)
* Assume you have also already created the Graphics object myGraphics.
Example 23.1(a)
Dim myPen As Pen
myPen = New Pen(Drawing.Color.Blue, 5)
Dim myGraphics As Graphics = Me.CreateGraphics
Dim myRectangle As New Rectangle
myRectangle.X = 10
myRectangle.Y = 10
myRectangle.Width = 200
myRectangle.Height = 100
myGraphics.DrawEllipse(myPen, myRectangle)
Figure 23.2
The second method is using the DrawEllipse method without creating a rectangle object. Of
course, you still have to create the Graphics and the Pen objects. The syntax is:
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.
Example 23.2(a)
Dim myPen As Pen
myPen = New Pen(Drawing.Color.Blue, 5)
Dim myGraphics As Graphics = Me.CreateGraphics
Dim myRectangle As New Rectangle
myRectangle.X = 10
myRectangle.Y = 10
myRectangle.Width = 100
myRectangle.Height = 100
myGraphics.DrawEllipse(myPen, myRectangle)
Example 23.2(b)
Dim myPen As Pen
myPen = New Pen(Drawing.Color.Blue, 5)
Dim myGraphics As Graphics = Me.CreateGraphics
myGraphics.DrawEllipse(myPen, 10, 10, 100, 100)
In order to draw text on the screen, we can use the DrawString method. The syntax is as follows:
*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 the upper left corner of the Text.
You can create the Font object in Visual Basic 2010 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:
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:
Example 24.1
Dim myGraphics As Graphics = Me.CreateGraphics
Dim myFont As Font
Dim myBrush As Brush
myBrush = New Drawing.SolidBrush(Color.DarkOrchid)
myFont = New System.Drawing.Font("Verdana", 20,
FontStyle.Underline)
myGraphics.DrawString("Visual Basic 2010", myFont, myBrush,
10, 10)
Run the program above and you can see the following output:
Figure 24.1
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)
You can also add an InputBox which let the user enter his or her message then display the
message on the screen.
Example 24.2
Dim myGraphics As Graphics = Me.CreateGraphics
Dim myFont As Font
Dim myBrush As Brush
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry
Form", "Enter your message here", 100, 200)
myBrush = New Drawing.SolidBrush(Color.DarkOrchid)
myFont = New System.Drawing.Font("Verdana", 20,
FontStyle.Underline)
myGraphics.DrawString(userMsg, myFont, myBrush, 10, 10)
The syntax to defines the points of a polygon with vertices A1, A2, A3, A4…….An is as
follows
After declaring the points, we need to define a point structure that group all the points
together using the following syntax:
Dim myPoints As Point() = {A1, A2, A3,....,An}
.Finally, create the graphics object and use the DrawPolygon method to draw the polygon
using the following syntax:
where myPen is the Pen object created using the following syntax:
Figure 25.2
25.2: Drawing Pie
In order to draw a pie, you can use the DrawPie method of the graphics object. As usual, you
need to create the Graphics and the Pen objects. The syntax for drawing a pie is:
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 sweeps 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.
Figure 25.3
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 intelligence will display the colours and
enter the period after the Color key word.
Example 26.1
Dim myPen As Pen
Dim myBrush As Brush
Dim myGraphics As Graphics = Me.CreateGraphics
myPen = New Pen(Drawing.Color.Blue, 5)
myBrush = New SolidBrush(Color.Coral)
myGraphics.DrawRectangle(myPen, 0, 0, 150, 150)
myGraphics.FillRectangle(myBrush, 0, 0, 150, 150)
Figure 26.1
26.2 Drawing and Filling an Ellipse
The syntax to fill a ellipse with the colour defined by the brush object is:
Example 26.2
Dim myPen As Pen
Dim myBrush As Brush
Dim myGraphics As Graphics = Me.CreateGraphics
myPen = New Pen(Drawing.Color.Blue, 5)
myBrush = New SolidBrush(Color.Coral)
myGraphics.DrawEllipse(myPen, 0, 0, 150, 150)
myGraphics.Ellipse(myBrush, 0, 0, 150, 150)
Figure 26.2
26.3 Drawing and Filling a Polygon
The syntax to fill a polygon with the colour defined by the brush object is:
myGraphics.FillPolygon(myBrush, myPoints)
Example 26.3
Dim myPen As Pen
Dim myBrush As Brush
Dim A As New Point(10, 10)
Dim B As New Point(100, 50)
Dim C As New Point(120, 150)
Dim D As New Point(60, 200)
Dim myPoints As Point() = {A, B, C, D}
myPen = New Pen(Drawing.Color.Blue, 5)
myBrush = New SolidBrush(Color.Coral)
Dim myGraphics As Graphics = Me.CreateGraphics
myGraphics.DrawPolygon(myPen, myPoints)
myGraphics.FillPolygon(myBrush, myPoints)
Example 26.4
Dim myPen As Pen
Dim myBrush As Brush
myPen = New Pen(Drawing.Color.Blue, 5)
myBrush = New SolidBrush(Color.Coral)
Dim myGraphics As Graphics = Me.CreateGraphics
myGraphics.DrawPie(myPen, 30, 40, 150, 150, 0, 60)
myGraphics.FillPie(myBrush, 30, 40, 150, 150, 0, 60)
Figure 26.4
Lesson 27 : Using Timer
In this lesson, we shall show you how to use the timer in Visual Basic 2010. The timer is
used to manage events that are time-related. For example, you can use the timer to create a
clock, a stopwatch, a dice, animation and more.
First of all, start a new project in Visual Basic 2010 and select a new Windows Application.
You can give the project any name you wish, we named 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 control tool Box. 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 the middle
center. Lastly, you shall also set the Interval property of the Timer control to 1000, which
reflects a one-second interval(1 unit is 1 millisecond).
Label1.Text = TimeOfDay
To create the clock, click on the Timer control and insert the code above, as shown below:
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.
Running the program produces a dice with fast changing numbers which stop at a certain
number. The interface is shownin Figure 27.3
Figure 27.3
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.
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 a rightward motion. The interface is shown below:
Figure 28.1
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:
In aforementioned code, 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 ticks, or every 0.1
seconds 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:
Timer1.Enabled = False
To animate the PictureBox object, we insert a command button and key in the following
code:
Timer1.Enabled = True
Figure 28.2
Computer-based Database management systems 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. Database management systems are 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
Visual Basic 2010 uses ADO.NET to handle databases. ADO.NET is Microsoft’s latest
database technology which can work with many other advanced database management
systems such as Microsoft SQL server. In this lesson, we will develop codes that make use of
Microsoft SQL Server 2008, therefore you need to have Microsoft SQL Server 2008 installed
on your PC, otherwise, you can download it from http://www.microsoft.com/en-
us/download/details.aspx?id=1695. Besides, you might want to download Microsoft SQL
Server 2008 Management Studio Express, the SQL database management system that allows
you to create and manage databases.
To begin building the database project in Visual Basic 2010, launch Visual Basic 2010. You
can name your project as Database Project 1 or whatever name you wish to call it. Next,
change the default form’s Text property to Contacts as we will be building a database of a
contact list. There are a few objects in ADO.NET that are required to build the database.
There are:
SqlConnection- to connect to a
data source in SQL Server
DataTable -to store data for
navigation and manipulation
DataAdapter- to populate a
DataReader
The aforementioned objects belong to the System.Data and the System.XML namespace.
Therefore, we have to reference them in the beginning before we can work with them. To
reference the ADO.NET object, choose project from the menu then select Database Project 1
properties to display the project properties. Next click the References tab to show the active
references for the project, as shown in Figure 29.1
Figure 29.1
Under imported namespaces, make sure system.data, System.Data.Sqlclient is selected,
otherwise, check them. Having done that you need to click the Save All button on the toolbar
and then return to the Visual Basic 2010 IDE.
We shall proceed to create the connection to the database source file in the next lesson.
Visual Basic 2010 Lesson 30-
Creating Connection to
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:
MyCn.ConnectionString = “Data Source=lenovo-4903350b\mssmlbiz;
AttachDbFilename=C:\Program Files\Microsoft SQL
Server\MSSQL.1\MSSQL\Data\Test.mdf; ” & _
“User Instance=True;Integrated Security=SSPI”
* You need to change the reference to the SQL server (lenovo-
4903350b\mssmlbiz) 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()
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:
MyDatAdp.Fill(MyDataTbl)
After filling up the DataTable , we need to write code to access the data. To
access data in the DataTable means that we need to access the rows in the
table. We can achieve this by using the DataRow object. For example, we
can write the following to access the first row of the table and present the
data via two text boxes with the name txtName and txtState respectively:
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:
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