Thursday, December 11, 2008

USING CHECK BOX

The Check box is a very useful control in Visual Basic 2008. It allows the user to select one or more items by checking the checkbox/checkboxes concerned. For example, in the Font dialog box of any Microsoft Text editor like FrontPage, there are many checkboxes 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, you may create a shopping cart where the user can click on checkboxes that correspond to the items they intend to buy, and the total payment can be computed at the same time as shown in Example.

Private Sub BtnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCalculate.Click
Const LX As Integer = 100
Const BN As Integer = 500
Const SD As Integer = 200
Const HD As Integer = 80
Const HM As Integer = 300
Const AM As Integer = 150
Dim sum As Integer

If CheckBox1.Checked = True Then
sum += LX
End If

If CheckBox2.Checked = True Then
sum += BN
End If

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

If CheckBox5.Checked = True Then
sum += HM
End If

If CheckBox6.Checked = True Then
sum += AM
End If
Label5.Text = sum.ToString("c")



Example2:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Const large As Integer = 10.0
Const medium As Integer = 8
Const small As Integer = 5
Dim sum As Integer

If CheckBox1.Checked = True Then
sum += large
End If

If CheckBox2.Checked = True Then
sum += medium
End If

If CheckBox3.Checked = True Then
sum += small
End If
Label5.Text = sum.ToString("c")

Example3:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Bold)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Bold)

End If
End Sub

Private Sub CheckBox2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox2.CheckedChanged
If CheckBox2.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Italic)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Italic)

End If
End Sub

Private Sub CheckBox3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox3.CheckedChanged
If CheckBox2.Checked Then
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Underline)
Else
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Underline)

End If
End Sub



* The above program uses the CheckedChanged event to respond to the user selection by checking a particular checkbox, it is similar to the click event. The statement
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Italic)
will retain the original font type but change it to italic font style.
TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Italic)
will also retain the original font type but change it to regular font style. (The other statements emply the same logic)

FUNCTIONS PART V - FORMATTING DATE AND TIME

1. Formatting Date and time using predefined formats
Date and time can be formatted using predefined formats and also user-defined formats. The predefined formats of date and time are shown in Table


*) 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:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = Format(Now, "General Date")
Label2.Text = Format(Now, "Long Date")
Label3.Text = Format(Now, "short Date")
Label4.Text = Format(Now, "Long Time")
Label5.Text = Format(Now, "Short Time")
End Sub

The output is shown in the diagram below:


2. Formatting Date and time using user-defined formats
Beside using the predefined formats, you can also use the user-defined formatting functions. The general format of a user-defined for date/time is

Format (expression,style)



Example:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click

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

End Sub

The output is shown in the diagram below:

FUNCTIONS PART IV - FORMATTING FUNCTIONS

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

(i) The format of the predefined Format function is

Format (n, “style argument”)

where n is a number and the list of style arguments is given in Table


Example:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format(8972.234, "General Number")
Label2.Text = Format(8972.2, "Fixed")
Label3.Text = Format(6648972.265, "Standard")
Label4.Text = Format(6648972.265, "Currency")
Label5.Text = Format(0.56324, "Percent")
End Sub

The Output window is shown below:


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

Format (n, “user’s format”)

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


Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format(8972.234, "0.0")
Label2.Text = Format(8972.2345, "0.00")
Label3.Text = Format(6648972.265, "#,##0.00")
Label4.Text = Format(6648972.265, "$#,##0.00")
Label5.Text = Format(0.56324, "0%")
End Sub

The Output window is shown below:

FUNCTIONS PART III - MATH FUNCTIONS

We have learned how to Vb2008 can perform arithmetic functions using standard mathematical operators. However, for more complex mathematical calculations, we need to use the built-in math functions in VB2008. There are numerous built-in mathematical functions in Visual Basic which we will introduce them one by one.

1 The Abs function
The Abs return the absolute value of a given number.

The syntax is

Math. Abs (number)

* The Math keyword here indicates that the Abs function belong to the Math class. However, not all mathematical functions belong to the Math class.
 

2 The Exp function
The Exp of a number x is the exponential value of x, i.e. ex . For example, Exp(1)=e=2.71828182

The syntax is Math.Exp (number)

Example:

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

Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Math.Exp(num1)
Label1.Text = num2

End Sub

3 The Fix Function
The Fix function truncate 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:

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

Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Fix(num1)
Label1.Text = num2

End Sub

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

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

5. The Log Function

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

Example:

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

Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Math.Log(num1)
Label1.Text = num2

End Sub

* The logarithm of num1 will be displayed on label1

6. The Rnd( ) Function

The Rnd is very useful when we deal with the concept of 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:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim num as integer

Randomize( )

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

Label1.Text=Num

End Sub

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

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

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim num1, num2 As Single
num1 = TextBox1.Text
num2 = Math.Round(num1, 2)
Label1.Text = num2

End Sub

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

FUNCTIONS PART II

We have learned about the basic concept of function as well as the MsgBox and InputBox functions in Lesson 12. I. In fact, I have already shown you 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.

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

Mid(phrase, position,n)

where

*
phrase is the string from which a part of text is to be retrieved.
*
position is the starting position of the phrase from which the retrieving process begins.
*
n is the number of characters to retrieve.

Example 2:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myPhrase As String
myPhrase = Microsoft.VisualBasic.InputBox("Enter your phrase")
Label1.Text = Mid(myPhrase, 2, 6)
End Sub

* In this example, when the user click 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. The diagrams are shown below:


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

Trim(“Phrase”)

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

Example:

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

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

Ltrim(“Phrase”)

.For example,

Ltrim (“ Visual Basic”)= Visual basic

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

Rtrim(“Phrase”)

.For example,

Rtrim (“Visual Basic ”) = Visual Basic

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

Instr (n, original phase, embedded phrase)

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

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

*The function returns a numeric value.

You can write a program code as shown below:

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

Label1.Text = InStr(1, "Visual Basic", "Basic")
End Sub

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

The format is

Microsoft.VisualBasic.UCase(Phrase)

Microsoft.VisualBasic.LCase(Phrase)
For example,

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

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

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

Chr(charcode)

and the format of the Asc function is

Asc(Character)

The following are some examples:

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

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

sage box. The Style Value will determine what type of command buttons appear on the message box, please refer Table 10.1 for types of command button displayed. The Title argument will display the title of the message board.

FUNCTIONS PART I

A function is similar to a normal procedure but the main purpose of the function isto 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, the built-in functions (or internal functions) and the functions created by the programmers.

The general format of a function is
FunctionName (arguments)

The arguments are values that are passed on to the function.

In this lesson, we are going to learn two very basic but useful internal functions of Visual basic , i.e. the MsgBox( ) and InputBox ( ) functions.
1. MsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he /she can continues. This format is as follows:

yourMsg=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box, please refer ton Table 12.1 for types of command button displayed. The Title argument will display the title of the message board.
Table Style Values


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

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

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

are the same.

yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values are determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general declaration section. Table 12.2 shows the values, the corresponding named constant and buttons.
Table Return Values and Command Buttons


Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
MessageBox.Show("You have clicked the OK button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub

To make the message box looks more sophisticated, you can add an icon besides the message.


Example 2:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim testMsg As Integer
testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")

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



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

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

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

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

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

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

The parameters remain the same.

Example:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim userMsg As String


userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry Form", "Enter your messge here", 500, 700)

If userMsg <> "" Then
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub

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

USING While ...End While Loop

The structure of a While….End While is very similar to the Do Loop. it takes the following format:

While condition

Statements

End While

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:
The structure of a While….End While is very similar to the Do Loop. it takes the following format:

While condition

Statements

End While

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.