Thursday, November 11, 2010

Chapter 4

Decision Structure
Sequence AàBà CàD
Selection If A àC.  Action taken if condition is true.
If … Then statement
Statements execute if certain conditions hold true. 
Syntax:
       If <condition> Then
             Statement 1
             Statement 2
        End If
use relational operators like >, <, =, < >, >=, <=.  The outcome of this testing is Boolean expression (true or false)
 use relational and math operators simultaneously in the if…then statement.  Note: Math operator gets evaluated first.
   e.g. If intX + intY > 0 Then
   lblMessage.Text = “XYZ”
End if
use function calls with relational operators e.g.
If Cint(txtInput.Text)  > 0 Then
   lblMessage.Text = “XYZ”
End if
If…Then…Else statement
One group of statements execute if condition is true, another group of statements execute if condition is false.
Syntax:
       If <condition> Then
             Statement 1
             Statement 2
        Else
             Statement 3
             Statement 4
         End If

If… Then… ElseIf Statement
if…then…else statements. 
Syntax:
       If <condition> Then
             Statement 1
             Statement 2
        ElseIf
             Statement 3
             Statement 4
         Else
             Statement 5
             Statement 6
End If
Nested If statements
An If statement inside another If statement.  The inside statement executes if the first if condition is met.
For a set of statements to execute, both if conditions have to be true.
Logical Operators
Combines two or more relations expressions into a single expression AND Operator:  TT=T, TF=F, FT=F, FF=F i.e. both expressions must be true.
Example:
If Age > 50 AND Weight > 190 Then
      Do a compete checkup.
End If
Other operators: OR, XOR, Not
Short circuit evaluation: AndAlso: Modified And function where the second condition is tested only if the   first condition is true.   
              If <condition 1> AndAlso <condition2> Then: Tests condition 2 only if condition 1 is true
              If <condition 1> and <condition 2> Then: Tests both conditions every time.
Short circuit evaluation: OrElse: Modified Or function where the second condition is tested only if the first condition is false.  This saves time.
If <condition 1> OrElse <condition2> Then: Skips condition 2 if condition 1 is true
If <condition 1> or <condition 2> Then: Tests both conditions every time.

The select case statement
Instead of using multiple if…then…elseif statements you can use a select case statement.
Syntax:
Select Case <TestExpression (e.g. TestScores)>
  Case ExpressionList
                One or more statements
  Case ExpressionList
                One or more statements
  Case Else
                One or more statements
  End Select
Working with strings
Initialize the string variable using string.empty. Ex.: Dim strName As String = string.empty
You can compare two strings using logical operators e.g.
If strName1=strName2 Then
If strName1>strName2 Then
If strName <> “Joe” Then
Convert the string to upper case or lower case
StrNewName=strName.ToUpper() or strName.ToLower()
ToUpper or ToLower does not modify the original string.
control properties e.g. txtInput.Text.ToUpper()
Helpful in string comparisons e.g. to compare Joe with JOE.
IsNumeric function
Accepts string as an argument and returns true if string contains a number
Ex: IsNumeric (“1223”) returns true (notice “1223” is a string)
Ex: IsNumeric(“1A”) returns false
String Length
Returns number of characters in the string
Ex: intNumChars=strName.Length
 You can use it with control properties e.g. txtInput.Text.Length
Trimming spaces from strings.
stringVariable.TrimStart() : Trims leading spaces
stringVariable.TrimEnd(): Trims trailing spaces
stringVariable.Trim(): Trims leading and trailing spaces.
You can use it with control properties e.g. txtInput.Text.Trim()
Substring Method
Substring method returns a part of string.
stringVariable.Substring (start) : Start is the starting position of the substring.
stringVariable.Substring(start, Length): Length is the number of characters to extract.
Remember string positions start at 0 e.g. USA: U is at position 0, S is at position 1, A is at position 2.
Indexof Method
IndexOf searches for a character in a string and returns the position of that character
Ex. stringVariable.IndexOf(“A”) returns the position of A in the string. (In “US of America” it will return 6 -  the first instance of “A”). Returns (-1) if character not found.
Ex. stringVariable.IndexOf (“A”, 7) starts the search for A after the 7th position.
Ex. stringVariable.IndexOf(“A”, 7 , 5) starts the search for A after the 7th position and ends it after 5 characters (or the 12th position)
Make sure you know the length of the string before using indexof.  Position outside of length range will create runtime error.

Message Box
Message box is a pop-up window that displays a message to users
messageBox.Show (message)
messagebox.show(message, caption)
messagebox.show(message, caption, buttons)
messagebox.show(message, caption, buttons, icon)
messagebox.show(message, caption, buttons, icon, defaultButton)
The outcomes of message box can be stored in a variable e.g.
intResult =MessageBox.Show(“Enter number”, “Error”, messageBoxButtons.YesNo)
if intResult = Windows.Form.DialogResult.No then
    Do something
End If
Display multiple lines: Control characters
ControlChars.CrLf inserts a new line
Ex. MessageBox.show(“This is line 1” & controlchars.CrLf & “This is line 2”) 

Chapter 3: Variables and Calculations

Control Property 
controlName.controlProperty = “control Value”
e.g. lblMessage.text=”Hello World” or lblResults.text=6
access the property value by
containerOfTheValue=controlName.controlProperty
e.g. inputA=txtInputA.text or inputB=txtInputB.text
Text boxes: Used for gathering inputs and can be used to display an output  
Syntax to clear an object can = ObjectName.MethodName() e.g.  TextBoxName.Clear()
String   
lblMessage.Text=”Hello ” & “world”
If the string is stored in a text box, remember you can access the string using the text property of the text box (or the label).  So concatenation syntax will be:
lblMessage.Text=”Hello” & txtControlName.Text
To clear the text boxes the procedure is: txtcontrolname.Clear()
The Focus Method: controlName.Focus()
TabIndex property
                  tabIndex property of the control in the properties window. 
tabIndex of 0 gets the cursor first, tabIndex of 1 gets the cursor (or the control). To select tabOrder  use properties window or select tab order on view menu. 

Keyboard shortcuts for buttons:
 E.g. enter E&xit in the text property of the Exit button.

 
1.       Variables and Data Types
General format to declare a variable:
Dim variableName As DataType

Dim (short for Dimension) is a keyword which tells VB that variable is being declared.
VariableName is the programmer (your) designated name
As is a keyword
DataType is one of many possible keywords for the type of value the variable will contain
Example: Dim intLength as Integer
declare multiple variables with one Dim statement e.g. Dim intLength, intWidth, intHeight As Integer
Getting system date and time
Now: Returns current date and time
TimeOfDay: Returns current time
Today: Returns current Date
e.g. Dim dtmSystemDate, dtmSystemTime As Date
dtmSystemDate=Now
dtmSystemTime=TimeOfDay
dtmSystemDate=Today

Variable Scope
Local Variable: A variable declared inside a procedure. Not accessible outside the procedure.
 Global Variable: Variable declared outside any class or procedure.  Accessible everywhere.
Class-level variable: declared inside the class but outside the procedure.  Accessible anywhere within the class.

Mixing data types
Implicit type conversion: If you try to store 5.12 to integer data type, VB rounds off the decimal points and just stores 5
Option Strict On: Disallows narrowing implicit conversion.

Named Constants
Reoccurring consistencies
                Const CONSTANT_NAME As DataType = Value e.g.
                Const dbltip as Double = 0.15

Explicit type conversion
VB provides a set of functions that permit narrowing conversions with Option Strict On.  These functions take an expression as an input and return the converted value. 
1.       CDate(expr) converts string to date e.g.
Dim datHired as Date = CDate(“05/10/2005”)
2.       CDbl(expr) converts string to double e.g.
Dim dblSalary As Double =CDbl(txtPayRate.Text)
3.       CDec(expr) converts expression to decimal
4.       CInt(expr) converts expression to integer
5.       CStr(expr) converts expression to string.  
The Val function: Converts strings to numeric value.  Val (“10”) is 10 but val (“$10”) is 0.  Val(“50$10”) is 50.
Formatting numbers and dates
Formatting allows easy to read displays e.g. putting a $ sign in front of currency, using commas in large numbers.
ToString method converts variable to string.  E.g. lblOutput.Text=intNumber.ToString()
In the parenthesis you can add n (for number e.g. n3), f(for fixed point) , e(for exponential), c(for currency format), or p (for percent format), d(for date e.g. toString(“D”)).

Exception handling
To notify the user of an exception (e.g. wrong data entered),  use message.Show function
Syntax is
MessageBox.Show (“Message”, “Caption”)
Use intellisense to see all the avaialbe options
To catch the exceptions use the following code
Try
try – statements
Catch [exception – type]
            Catch-statements
End try
·         Try statements: contains program statements you would like to execute
·         Catch Statements: contains program statements when exception is thrown.
·         Exception type: Optional statement to specify type of exception you want to catch.

Example:
Try
Dim decSalary as Decimal
                decSalary = CDec(txtSalary.Text)
                MessageBox.Show(“Your salary is “ _
                                & decSalary & “ dollars”)
                Catch
                                MessageBox.Show(“ Please try again,” _
                                & “and enter a number”, “Entry Error”)
End Try

In this case if If CDec throws a cast exception, the try block catches it, jumps to and executes the catch block which displays the error message
Similarly
Try
                Dim decAnnualSalary as Decimal
                Dim intPayPeriods as Integer
                Dim decSalary as Decimal
                decAnnualSalary = CDec(txtAnnualSalary.Text)
                intPayPeriods = CInt(txtPayPeriods.Text)
                decSalary.Text = decAnnualSalary / intPayPeriods
                lblSalary.Text = decSalary.ToString()
                Catch ex as InvalidCastException
                                MessageBox.Show(ex.Message, “Entry Error”)
                Catch ex as DivideByZeroException
                                MessageBox.Show(“Zero Value Not Allowed “ _                                             & “ for Pay Periods”)
End Try

Group boxes and load event Procedure
A GroupBox creates a grouping of controls
Controls are enclosed in a box with a title
GroupBox are related in some way
Controls in a GroupBox have their own tab order
Moving a GroupBox moves its controls with it
Removing a GroupBox also removes all controls within it





Chapter 8: Arrays, Timers, and more


Arrays: Groups of variables that allow you to store sets of data.   All the values stored within an array are called elements, and are all of same data type.  You can access individual elements in an array through a subscript. 
Declaring an array:  Dim arrayName (upperSubScript) As DataType e.g.
Dim  studentGrades (40) As Integer.  This creates an array with 41 elements (0-40).
You can also declare the arrays as
Implicit Array Sizing and initialization: e.g. Dim studentGrades () As Integer = { 20, 40, 60, 80}.  This declares an array of size (4) and upperSubScript (3)
Working with array elements. 
To initialize an array:
studentGrades (0) = 20
studentGrades(1)=40
studentGrades (40)=90
Use in expressions:  Use arrays as you would use normal variables
Pay = intHours (5) * hourlyPay (multiplies the 6 element of the array with hourly pay) intCount(1) +=1  (Adds one to intCount(1) – the second element of the array) or MessageBox.Show(studentGrades(5).ToString()) (displays the 6th element)

Arrays and loops:  Arrays work best with the loops – Loops can automize a lot of processes associated with arrays.  e.g.
Dim intCount as Integer
For intCount = 0 to 9
                studentGrade (intCount) = intCount *20
Next

Dim intCount as integer
For intCount = 0 to 40
                StudentGrade(intCount)=CInt(InputBox(“Enter the grade”))
Next
Array bound checking: If you try to use arrays outside the bounds, it will cause a runtime error.


Accessing array elements:
Using For Each loop
For Each variableName As dataTypeSameAsArrayType In ArrayName

Next
The above syntax starts by storing the 0th element of array in variableName, executes statements, loops, and then stores the next element in the array.
Example:
                For Each intVal As Integer In IntArray
LstShow.items.add(intVal)
Next
Using arrays in loops e.g. calculate sum of array elements.
Dim intVal as integer = 0
For Each intVal As Integer in IntArray
                                intSum +=intVal
Next

Or

Dim intCount As Integer = 0
For intCount = 0 to 100
                intSum +=intArray(intCount)
Next

Finding the largest value in an array

Dim intLargest as Integer = intArray(0)
For Each IntVal as Integer in IntArray
                If intVal > intLargest Then
                                intLargest = intVal
                End If
Next
Finding the item in a listBox

For each strCity As String In LstCities.Items
                If StrCity = txtCity.Text Then
                                lblResults.Text = “City was found”
End if
Next


Determining the number of elements in the array
arrayName.Length gives the number of elements
e.g. For intCount = 0 to (intValues.Lenght -1)
                Messagebox.show(intValues(intCount))
Next
Total the values in an array
You do.
Calculating the average value in  a numeric array
You do
Find the lowest and highest value
You do
Copying one arrays contents to another
For intCount = 0 to (intOldValues.Length-1)
                intNewValues(count)=intOldValues(count)
Next
Sorting arrays
Array.Sort (ArrayName)
Searching an array
Found = false
position = 0
Do while found is false and subscript < arrays length
                If array(subscript) = searchValue Then
                                Found=True
                                Position=subscript
                End if
                Subscript +=1
End While
Multidimensional arrays
Dim sngScores (2,3) as Single   (2,3) = number of rows, number of columns.


Chapter 7

Multiple forms:  Most applications will have multiple forms.  To add the second form to your application follow the procedure below:
Rename the existing form
Startup object: A startup object may be a form or a procedure named main. 
Modal Vs. Modeless forms:

Modal Form: Forms which have to be closed before you can shift focus to any other application or the form
frmForm2Instance.showDialog()  will create a modal form

Modeless form:  Allows to shift focus between multiple forms. (e.g. word help – shift focus between word and help form)
frmForm2Instance.show()  will create a modeless form

Closing a form: Me.Close().   Closes the form and removes the forms visual parts from the memory.

Hide the form: Me.Hide().  Makes the form invisible but does not remove from the memory.

Common Events associated with the forms:
Form Load: Form load event handler. 

Activated Event: When focus is shifted from one application (e.g. A) to another application (e.g. B).  Then activated event of application B occurs.   You can create activated event in the code view à class name drop-down list, and select formname events.

FormClosing Event: Executes right before the form closes (e.g. are you sure you want to close the form?)
Example:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

If MessageBox.Show("Are you sure?", "Confirm!!!", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
        e.Cancel = False
Else
        e.Cancel = True  'Do not close the form.
End If

End Sub
FormClosed: Executes after the form has been closed. 
Accessing objects and variables on a different form.
 To qualify the name of the object, precede it with the form where it was created.  E.g. form1.text1TextBox.Text means text1TextBox on form1.  Same is true for public functions and procedures also.

Standard Modules:  A standard module contains code and procedures that are used by other files in a project.
To add a new module, Go to project menu à add new item à module or simply project à add module
A private object in the module can only be accessed by statements in the same module.  To access contents of modules outside the module, use public identifier.

Menus:  You have seen menus in most office applications.  A menu system is a collection of commands organized in one or more drop-down menus. 
Enable or disable a menu item by selecting visible to true or false in the properties window.
Select short cut from setting the shortcut option in the properties window. 

chapter 6


Procedures: 
A procedure is a specified series of actions, acts or operations which have to be executed in the same manner in order to always obtain the same result under the same
In VB there are two types of procedures:
                Procedure: Collection of statements that perform a task.  For example an event handler.
                Function: Collection of statements that performs a task and then return a value e.g. CInt, IsNumeric.
Creating Procedures.
Function
Function <FunctionName> (ByVal X as Integer, ByVal Y As Integer ) As Integer
Statement one
Statement two
Statement three
Return Result
End Function

SubProcedure
Sub <SubName> (ByVal X as Integer, ByVal Y As Integer )
Statement one
Statement two
Statement three
End Sub
Variables inside the procedures. 
are local variables and are destroyed when the procedure ends.
To declare variables that will retain their value even after the procedure ends, declare static variables

Static VariableNameABC  As DataType

Now every time the procedure is called, the variableNameABC will hold/retain the value which can be accessed next time the procedure is called.  However, remember that the variableNameABC is still local and only accessible within the procedure.
Calling procedures
Functions can be called directly by the program by writing the procedure name and specifying the arguments being passed.   a function returns a value which needs to be used or stored in a variable.
e.g. intSquareOfTwoNumbers=calculateSquare(cInt(txtInput.Text))

Sub procedures can be called directly from the program by writing the procedure name and the arguments being passed.
e.g. call DisplayText(txtInput.text, txtName.Text).  Call keyword is optional.

Passing values to the procedure.
Procedures sometimes need information or data for carrying out their operations.  These are passed as arguments when calling the procedure.  The data can be input from the textbox, the value stored in a variable, a constant, a string, etc.
Passing value (ByVal):
A copy of argument is passed.  Any changes to the passed argument does not change the original values.
Passing reference (ByRef): The link to original arguments is passed.  Any changes made to the parameter variable are actually performed on the original argument.
e.g.        Dim strUserName As String
                GetName(strUserName)
                MessageBox.Show(“Your Name is” & strUserName

                Sub GetName (ByRef strName as String)
                strName=InputBox(“Enter your Name”)
                End Sub

chapter 5


Input Boxes: For quick and easy way to enter data without textboxes.  Input boxes are similar to messageBoxes and have ok and cancel button. 

InputBox (Prompt, [ , Title] [, Default value to show in the input field] [, Xpos] [, Ypos])

results of input box in a string variable e.g. strInputName=InputBox(params)

Listbox control
Add item:                                            LstName.items.add(“Something”)
Insert item:                                        LstName.items.insert(Position, “Something”)
Count items in the list box:          intNumber=LstName.Items.Count
Index of items:                                 Start at 0 and go upto n-1
Access the item:                               strEmpName=LstName.Items(position)
Convert data type:                          strName=LstName.Items(0).ToString()
intAge=cInt(lstAge.Items(0))
Exception handling:                        If index is out of range it will throw an exception.  try and catch statement.
Try
                StrInput = lstName.Items(position).ToString()
Catch ex As Exception
                MessageBox.Show (ex.Message)
End Try

SelectedIndex Property:              The value (position) of selected item. 
intSelectedValue=lstName.selectedIndex
If no item is selected selectedIndex will return -1
lstName.selectedIndex=-1 will unselect everything.
selectedItem Property:                 Contains the item itself. E.g. 
strName=lstName.SelectedItem.ToString()
Sort the items:                                  select the sorted property to True.
Remove items:                                 LstName.Items.Remove(“Item”)
LstName.Items.RemoveAt(Position)
LstNames.Items.Clear() clears everything.
Search List box for items:             LstNames.Items.Contains(“ABC”) returns true if list box has ABC as one of the items.
Find location of an object:            LstName.Items.IndexOf(“ABC”)


Chapter 1: Introduction to Visual Basic



Computer systems: Hardware and Software
Hardware: Computers physical components.Major components: CPU, Memory, Secondary storage, Input devices, Output devices.Software: Set of instructions to run the computer.System e.g. OS
Applications e.g. MS Office
Programs and programming languages
Program: A set of instructions that a computer follows.
Algorithm: A set of well defined steps for performing a task
Procedural programming VS. Object oriented programming
Procedural: Programs made of one or more procedures.
Object oriented: Uses real world objects called classes in software.
  Objects have attributes or properties (height, color, weight) and methods (actions that object perform sit, stand, eat) 

Visual Basic:
GUI: Interaction with computer is thru visual controls.
Event driven programming: The action is initiated when an event occurs


Control Terms
Label - displays text the user cannot change
TextBox - allows the user to enter text
Button – performs an action when clicked
CheckBox – A box that is checked or unchecked with a mouse click
Form - A window that contains these controls
Controls have names for identification and manual manipulation.
Naming Rules for controls
Always follow a pretext to make naming easier.
Control name must start with a letter.  No spaces, special symbols, or punctuation characters.
Controls have properties and each property has a value.  E.g. txtResults.visible=true means that visible property of text box results is set to true.


Keywords: Words with special meaning to Visual Basic (e.g., Private, Sub)


Programmer-defined-names: Names created by the programmer (e.g., sngGrossPay, btnClose)


Operators: Special symbols to perform common operations (e.g., +, -, *, and /)


Remarks: Comments inserted by the programmer – these are ignored when the program runs (e.g., any text proceeded by a single quote)


Syntax: Rules that must be followed when constructing a method.

The programming process
Steps to develop application
Define the purpose of the application
Purpose:Input:Process:Output:
Design the user interface 
Make a list of controls needed and their default value
Form     FormName         FormDescription              FromValue
Label     LabelName         LabelDescription              LabelText
Button  ButtonName      ButtonDescription           ButtonText
List out the methods needed
Create a flow chart or pseudocode of each method
Write the code for event procedure
Run and correct the errors.