Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 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

3 Demo Num1 Num2 Sum = Control properties Event: Click, MouseMove, FormLoad, etc. Event procedures Sum: text3.text=CStr(CDbl(text1.text)+CDbl(text2.text)) VB Constant: vbGreen, vbRed

4 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.

5 Configure VB IDE Tools/Options –Editor: Require Variable Declaration Option Explicit – Editor Format, General, Docking, Environment, Advanced Debug –View/Watch Window

6 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

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

8 Select Case Structure SELECT CASE testexpression [CASE expressionlist-n [Statements] [CASE ELSE [elsestatements] END SELECT

9 Select Case Example SELECT CASE temperature CASE <40 Text1.text=“cold” CASE 40 to 60 Text1.text=“cool” CASE 60 to 80 Text1.text=“warm” CASE ELSE Text1.text=“Hot” End Select

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

11 Do While/Do Until Private Sub Command1_Click() Dim counter As Integer counter = 0 Do While counter <= 5 Debug.Print counter counter = counter + 1 Loop Text1.Text = counter End Sub Private Sub Command2_Click() Dim counter As Integer counter = 0 Do Until counter > 5 Debug.Print counter counter = counter + 1 Loop Text1.Text = counter End Sub

12 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

13 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.

14 ByRef, ByVal example Private 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

15 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

16 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

17 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

18 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.

19 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

20 PopUp Code Example Private 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

21 InputBox cname = InputBox("Please enter your name:") If cname = vbNullString Then MsgBox ("customer click cancel") Else Text1.Text = cname End If

22 MsgBox MsgBox(prompt[, buttons] [, title]) Buttons: –Group 1: vbOKonly, vbOKCancel, vbAbortRetryIgnore, vbYesNoCancel, vbYesNo, vbRetryCancel –Group 2: vbQuestion, vbExclamation, vbInformation, vbCritical

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

24 MsgBox Code Example Dim returnVal As Integer returnVal = MsgBox("erase text box 1", vbYesNo+vbQuestion) If returnVal = vbYes Then Text1.Text = "" End If

25 Working with Controls Properties –Setting properties at design time –Setting properties at run time Methods: controls have very few methods –MoveEx. 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

26 Text Box Useful properties –Locked: read only –Password Character –Multiline –ScrollBar –SelText: holds the currently selected text Useful events –Change –Validate

27 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

28 Check Box Example Private 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

29 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.

30 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.

31 Frame Example Private Sub Option1_Click() If Option1.Value Then Text1.Text = "opt1" End If End Sub Private Sub Option2_Click() If Option2.Value Then Text1.Text = "opt2" End If End Sub Private Sub Option3_Click() If Option3.Value Then Text1.Text = "opt3" End If End Sub

32 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 4 th item is selected, the index is 3. –Text: selected list item. Methods –AddItem –Clear

33 List Box Example Private Sub Form_Load() List1.AddItem "Dates" List1.AddItem "Brocoli" List1.AddItem "Oranges" List1.AddItem "Tomatoes" List1.AddItem "Apples" End Sub Private Sub List1_Click() Text1.Text = List1.List(List1.ListIndex) or Text1.Text=List1.Text End Sub

34 Data Control Database Name Record Source Bind field to text box –Data source –Data field

35 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

36 Components Project/Components

37 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.

38 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.

39 Dynamic Array Example Dim StudentAge() …. ReDim StudentAge(1 to TotalStudents) …

40 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

41 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

42 Error Handling Example Private Sub cmdDivide_Click() On Error GoTo DivideErrorHandler lalAnswer.Caption=CStr(CDbl(Text1.text)/CDbl(Text2.Text)) Exit Sub DivideErrorHandler: MsgBox(CStr(Err.Number) & “: “ & Err.Description) Exit Sub End Sub

43 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

44 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”.

45 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.

46 Iterating Through a Collection Dim Customer as clsCustomer Dim Indx as Long For Indx = 1 to Customers.Count set Customer = Customers.Item(Indx) … class operations … Next Indx For Each Customer in Customers … class operations … Next Customer

47 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


Download ppt "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."

Similar presentations


Ads by Google