Introduction to Visual Basic

47
Introduction to Visual Basic • Event-driven programming – The interface for a VB program consists of one or more forms, containing one or more controls (screen objects). – Form and control has a number of events that it can respond to. Typical events include clicking a mouse button, type a character on the keyboard, changing a value, etc. – Event procedure

description

Introduction to Visual Basic. Event-driven programming The interface for a VB program consists of one or more forms, containing one or more controls (screen objects). - PowerPoint PPT Presentation

Transcript of Introduction to Visual Basic

Page 1: Introduction to Visual Basic

Introduction to Visual Basic

• Event-driven programming– The interface for a VB program consists of one

or more forms, containing one or more controls (screen objects).

– Form and control has a number of events that it can respond to. Typical events include clicking a mouse button, type a character on the keyboard, changing a value, etc.

– Event procedure

Page 2: Introduction to Visual Basic

Text Box

• Properties:– Bound/Unbound, Enabled, Locked, Multiline,

Password Char, ScrollBar, Text• Properties can be set at the design time or at

the run time using codes.• To refer to a property:

– ControlName.PropertyName– Ex. Text1.Text

Page 3: Introduction to Visual Basic

Demo

Num1

Num2

Sum =

Control propertiesEvent: Click, MouseMove, FormLoad, etc.Event proceduresSum: text3.text=CStr(CDbl(text1.text)+CDbl(text2.text))VB Constant: vbGreen, vbRed

Page 4: Introduction to Visual Basic

VB Projects

• A VB project consists of several files. Always create a project folder and keep all project files in the folder.– Project file: extension .vbp– Form modules:

• .frm• .frx: Graphics and other binary data.

Page 5: Introduction to Visual Basic

Configure VB IDE

• Tools/Options– Editor: Require Variable Declaration

• Option Explicit– Editor Format, General, Docking,

Environment, Advanced• Debug

– View/Watch Window

Page 6: Introduction to Visual Basic

Introductory VB Topics – Appendix C

• Declaring variables– DIM, PUBLIC, PRIVATE, STATIC, CONST– Boolean, Integer, Long, Single, Double, Currency, Date,

Variant, Object– Ex.: DIM dblIntRate AS Double

• Variable scope– Local: declared in a procedure– Global: declared in a general section, or with Public

(referring a variable declared in other form may require form name to qualified that variable. Ex. Form1.PubVar)

• Data conversion– CStr, Ccur, CDbl, Cint, CLng, CSng, Val, etc.– VB .NET: Convert class

Page 7: Introduction to Visual Basic

IF Statement

• IF condition THEN statements [ELSEIF condition-n THEN [elseifstatements] [ELSE [elsestatements]]] End If

Page 8: Introduction to Visual Basic

Select Case Structure

• SELECT CASE testexpression[CASE expressionlist-n

[Statements][CASE ELSE

[elsestatements]END SELECT

Page 9: Introduction to Visual Basic

Select Case Example• SELECT CASE temperature

CASE <40Text1.text=“cold”

CASE 40 to 60Text1.text=“cool”

CASE 60 to 80Text1.text=“warm”

CASE ELSEText1.text=“Hot”

End Select

Page 10: Introduction to Visual Basic

Loop

• FOR index – start TO end [STEP step][statements][EXIT FOR]NEXT indexDO [{WHILE| UNTIL} condition][statements][EXIT DO]LOOP

Page 11: Introduction to Visual Basic

Do While/Do UntilPrivate Sub Command1_Click()Dim counter As Integercounter = 0Do While counter <= 5 Debug.Print counter counter = counter + 1LoopText1.Text = counterEnd Sub

Private Sub Command2_Click()Dim counter As Integercounter = 0Do Until counter > 5 Debug.Print counter counter = counter + 1LoopText1.Text = counterEnd Sub

Page 12: Introduction to Visual Basic

Procedures• Tools/ Add Procedure

– Sub procedure• To call a sub procedure SUB1

– SUB1 Argument1, Argument2,…– CALL SUB1(Argument1, Argument2, …)

– Function• Private Function tax(salary)• tax = salary * 0.1• End Function

– VB .NET• Private Function tax(salary)• Return salary * 0.1• End Function

Page 13: Introduction to Visual Basic

Call by Reference Call by Value

• ByRef– Default– The address of the item is passed. Any changes

made to the passing variable are made to the variable itself.

• ByVal– Only the variable’s value is passed.

Page 14: Introduction to Visual Basic

ByRef, ByVal examplePrivate Sub Command1_Click()

Dim myStr As String

myStr = Text1.Text

ChangeText myStr

Text1.Text = myStr

End Sub

Private Sub ChangeTextRef(ByRef strInput As String)

strInput = "New Text"

End Sub

Page 15: Introduction to Visual Basic

VB User Interface Objects• Form• Menu:

– DropDown, PopUp• InputBox• MsgBox• Standard Controls:

– Text Box, List Box, Option Button, Check Box, Command Button, Frame, etc.

• Other Controls:– Project/Components

Page 16: Introduction to Visual Basic

Form

• Modeless form: Other forms can receive input focus while this form remains active.

• Modal form: No other form can receive focus while this form remains active.– Formname.Show vbModal– Ex. Do you want to save the change?

• FormName.Hide or Me.Hide• Unload formName or Unload Me• Form level variables

Page 17: Introduction to Visual Basic

Form Events• Events occur to a form as it is loaded:

– Initialize: When a form instance is created from a class.– Load: Form is loaded into memory. Use this event for

initialization code.– Activate/Deactivate

• Events occur to a form as it is unloaded:– QueryUnload: Are you sure you want to close?– Unload: End-of-processing code– Terminate

Page 18: Introduction to Visual Basic

DropDown Menu

– Select the form– Select Tools/MenuEditor– The caption and name properties are required– Use an & to specify an access key in the

caption. Ex. &File, Sho&s– Write a event procedure for each menu item.

Page 19: Introduction to Visual Basic

• Tools/MenuEditor– Uncheck Visible box

• Activated by right click the control.• MouseUp event

– vbLeftButton - 1– vbRightButton – 2

• Use form’s PopUpMenu method to call the popup menu.

PopUp (Shortcut) Menu

Page 20: Introduction to Visual Basic

PopUp Code ExamplePrivate Sub Command1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)

If Button = vbRightButton Then

form1.PopupMenu mnuPop

End If

End Sub

Private Sub mnuPopSub_Click()

MsgBox ("hello there")

End Sub

Page 21: Introduction to Visual Basic

InputBox

cname = InputBox("Please enter your name:")

If cname = vbNullString Then

MsgBox ("customer click cancel")

Else

Text1.Text = cname

End If

Page 22: Introduction to Visual Basic

MsgBox

• MsgBox(prompt[, buttons] [, title])• Buttons:

– Group 1: vbOKonly, vbOKCancel, vbAbortRetryIgnore, vbYesNoCancel, vbYesNo, vbRetryCancel

– Group 2: vbQuestion, vbExclamation, vbInformation, vbCritical

Page 23: Introduction to Visual Basic

MsgBox

• MsgBox return values:– vbOK – 1– vbCancel – 2– vbAbort – 3– vbRetry – 4– vbIgnore – 5– vbYes – 6– vbNo - 7

Page 24: Introduction to Visual Basic

MsgBox Code Example

Dim returnVal As Integer

returnVal = MsgBox("erase text box 1", vbYesNo+vbQuestion)

If returnVal = vbYes Then

Text1.Text = ""

End If

Page 25: Introduction to Visual Basic

Working with Controls

• Properties– Setting properties at design time– Setting properties at run time

• Methods: controls have very few methods– Move Ex. Text1.Move 2000,2500 (1440 twips/inch)– SetFocus

• Events: click, DblCLick, Change, GotFocus, LostFocus, Mouse Events (down, up, move), Key events(down, up, key press), Validate

Page 26: Introduction to Visual Basic

Text Box

• Useful properties– Locked: read only– Password Character– Multiline– ScrollBar– SelText: holds the currently selected text

• Useful events– Change– Validate

Page 27: Introduction to Visual Basic

Validate Event Code Example

Private Sub Text1_Validate(Cancel As Boolean)

If CInt(Text1.Text) < 0 Then

Cancel = True

MsgBox (“Pls enter a positive number!")

End If

End Sub

Page 28: Introduction to Visual Basic

Check Box ExamplePrivate Sub CheckBox1_Click()

If CheckBox1.Value = 1 Then

MsgBox ("checkbox1 checked")

Else

MsgBox ("checkbox1 unchecked")

End If

End Sub

Note: CheckBox’s Value - vbChecked, vbUnchecked

Page 29: Introduction to Visual Basic

Option Button

• Option buttons must be grouped together inside a container such as a frame or a form.

• When the user selects an option all other options in the same group are deselected.

• Option Button’s value: True/False.

Page 30: Introduction to Visual Basic

Frame Control

• Draw the frame first.• Next single-click the control to activate it,

then move the mouse pointer inside the frame to where you want to place the control.

• Controls in a frame should move with the frame.

Page 31: Introduction to Visual Basic

Frame ExamplePrivate Sub Option1_Click()If Option1.Value Then Text1.Text = "opt1"End IfEnd SubPrivate Sub Option2_Click()If Option2.Value Then Text1.Text = "opt2"End IfEnd SubPrivate Sub Option3_Click()If Option3.Value Then Text1.Text = "opt3"End IfEnd Sub

Page 32: Introduction to Visual Basic

List Box

• Useful properties– List: array of strings that correspond to the text for the

items shown in the list. Must include a subscript.– ListCount– ListIndex: The 0-based index of the currently selected

item. If the 4th item is selected, the index is 3.– Text: selected list item.

• Methods– AddItem– Clear

Page 33: Introduction to Visual Basic

List Box ExamplePrivate Sub Form_Load()List1.AddItem "Dates"List1.AddItem "Brocoli"List1.AddItem "Oranges"List1.AddItem "Tomatoes"List1.AddItem "Apples"End SubPrivate Sub List1_Click()Text1.Text = List1.List(List1.ListIndex)

orText1.Text=List1.TextEnd Sub

Page 34: Introduction to Visual Basic

Data Control

• Database Name• Record Source• Bind field to text box

– Data source– Data field

Page 35: Introduction to Visual Basic

OLE Control

• Embedding an OLE object at design time:– Click Create New– Select the OLE object

• Linking an OLE object at design time:– Click Create From File– Select the object– Click LINK

• Insert OLE object at run-time– Ex. OLE1.InsertObjDlg

Page 36: Introduction to Visual Basic

Components

• Project/Components

Page 37: Introduction to Visual Basic

Arrays

• Declaring arrays– Dim arrayName(lowerBound To upperBound)

As dataType• Dynamic arrays:

– Ability to change the size of an array at run time.

– Use dynamic arrays when the size is unknown at design time, or it varies from one time to another.

Page 38: Introduction to Visual Basic

Declaring Dynamic Arrays

• Declare the array to be dynamic by omitting the lower and upper bounds in the Dim statement.

• Later, when the program needs a certain number of elements in the array, use the ReDim statement to assign the array size.

• Each time a ReDim is executed, the values currently stored in the array are lost. To keep those data, use the Preserve keyword.

Page 39: Introduction to Visual Basic

Dynamic Array Example

Dim StudentAge()

….

ReDim StudentAge(1 to TotalStudents)

Page 40: Introduction to Visual Basic

Control Arrays

• A set of controls of the same type that all have the same name distinguished by a subscript. They share the same events, and therefore share the code in the event procedure.

• Createing a control array:– Add control with the same name.

• Add or delete control elements at run time:– Load/Unload

Page 41: Introduction to Visual Basic

Error Handling• On Error GoTo errorhandler (a label)• Built-in Err object properties:

– Number – Error number– Source – Name of VB ile in which error occurred– Description – error message

• Continue the program execution:– Resume: returns execution to the statement that caused

the error.– Resume Next– Resume label: Jumps to the line containing the label.– Exit Sub

• Debug: Debug.Print varName

Page 42: Introduction to Visual Basic

Error Handling Example

Private Sub cmdDivide_Click()On Error GoTo DivideErrorHandlerlalAnswer.Caption=CStr(CDbl(Text1.text)/CDbl(Text2.Text))Exit SubDivideErrorHandler:MsgBox(CStr(Err.Number) & “: “ & Err.Description)Exit SubEnd Sub

Page 43: Introduction to Visual Basic

Object• Creating objects from a class

– Declare an object variable with keyword New.• Dim emp as New clsEmployee• Emp.Ename=“Peter”• Emp.Jobcode=1

– Declare an object variable without New. • Object must be created in program using Set.• Dim emp as clsEmployee• Set emp = New clsEmployee• Or set it to an existing object:

– Assume emp2 is an existing object: Set emp = emp2

• Deleting an object: Set objName = Nothing

Page 44: Introduction to Visual Basic

Collections

• Collections are used to store lists of objects.• More flexible than array:

– No need to declare the number of objects in a collection, no need to ReDim.

– Objects can be added, deleted at any position.– Object can be retrieved from a collection by a

key.• A collection’s name usually end with a “s”.

Page 45: Introduction to Visual Basic

Using Collections• Define a collection:

– Ex. Private Customers as New Collection• Methods:

– ADD: Add object to a collection• Dim Customer as New clsCustomer• Customers.Add(Customer)• Add an object with a key:

– Customers.Add(Customer, Customer.CID)

– Item: Retrieve an object from a collection with a position index (base 1) or with a key.

• Set Customer = Customers.Item(1)• Set Customer = Customer.Item(“C101”)

– Count: Return the number of objects in a collection.– Remove: Delete an object with a position index or key.

Page 46: Introduction to Visual Basic

Iterating Through a CollectionDim Customer as clsCustomerDim Indx as LongFor Indx = 1 to Customers.Count

set Customer = Customers.Item(Indx)… class operations …

Next IndxFor Each Customer in Customers… class operations …Next Customer

Page 47: Introduction to Visual Basic

Enumerations

• Provide a way to associate meaningful names with a sequence of constant values.

• Define an enumeration using an Enum statement.– Private Enum seasonOfYear– Spring = 1– Summer = 2– Fall= 3– Winter = 4– End Enum– Dim Sales(Spring to Winter) as Double