Presentation is loading. Please wait.

Presentation is loading. Please wait.

VISUAL BASIC PRESENTATION

Similar presentations


Presentation on theme: "VISUAL BASIC PRESENTATION"— Presentation transcript:

1 VISUAL BASIC PRESENTATION
Made Easy

2 Lecture 1 - What's Visual Basic About?
This lecture focuses on the main components of the Visual Basic environment. By the end of this session you should be able to navigate competently and use many of the functions that are important in the development of an application.

3 Applications of Vb software
Visual Basic is used to develop 'rapid applications' inside a windows environment Visual Basic is a high level programming paradigm. Its concepts are based upon Event driven programming. The environment to edit, delete and write code as well as develop windows based applications is known as the 'Integrated Development Environment' (IDE). Visual basic can do the following; Develop commercial applications, for example databases and the internet Links to other products such as Word, Excel and Access Multimedia applications

4 The Visual Basic Integrated Development Environment

5 IDE Cont…. From the diagram it can be seen that the IDE is divided into separate areas or 'windows'. We have the Toolbox control which allows us to add objects on to Form window. We can change the properties using the properties windows for all the objects on the form. We can also edit/create the event handlers using the Code Window. When creating applications in Visual Basic it is quite common to use multiple forms, modules etc. The project explorer window is used to keep track of all the additional files used.

6 TOOL BOX COMPONENTS OF A TOOL BOX EXPLAINED

7 Control Description Pointer Provides a way to move and resize the controls form PictureBox Displays icons/bitmaps and metafiles. It displays text or acts as a visual container for other controls. TextBox Used to display message and enter text. Frame Serves as a visual and functional container for controls CommandButton Used to carry out the specified action when the user chooses it. CheckBox Displays a True/False or Yes/No option. OptionButton Option Button control which is a part of an option group allows the user to select only one option even it displays multiple choices. ListBox Displays a list of items from which a user can select one. ComboBox Contains a Textbox and a List Box. This allows the user to select an item from the dropdown List Box, or to type in a selection in the Textbox.

8 HScrollBar and VScrollBar
These controls allow the user to select a value within the specified range of values Timer Executes the timer events at specified intervals of time DriveListBox Displays the valid disk drives and allows the user to select one of them. DirListBox Allows the user to select the directories and paths, which are displayed. FileListBox Displays a set of files from which a user can select the desired one. Shape Used to add shape (rectangle, square or circle) to a Form Line Used to draw straight line to the Form Image used to display images such as icons, bitmaps and metafiles. But less capability than the Picture Box Data Enables the use to connect to an existing database and display information from it. OLE Used to link or embed an object, display and manipulate data from other windows based applications. Label Displays a text that the user cannot modify or interact with.

9 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
View Code View Object Toggle Folders Project Name Forms Folder Form & modules Palitha Baddegama , Computer Resource Centre, Hingurakgoda

10 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Name Property Must begin with a letter Can contain letters, numbers, and the underscore character only Must not contain punctuation characters or spaces ,,; ,:) Must not exceed 40 characters Palitha Baddegama , Computer Resource Centre, Hingurakgoda

11 Hungarian Notation Use the three-character IDs shown in Figure 1-10
Object First three Characters Ex: Form frm frmAddtion Command Button cmd cmdStart Label lbl lblEnd Text Box txt txtFirst Menu mnu mnuExit Check box chk chkChoice Combo box cmb cmbFont Palitha Baddegama , Computer Resource Centre, Hingurakgoda Figure 1-10

12 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Statements Procedures Event Procedures Sub Procedures General Procedures Functional Procedures Comments Using single quotation (‘) REM Palitha Baddegama , Computer Resource Centre, Hingurakgoda

13 Visual Basic's 6 Most Common Programming Statements
Statement type Examples Declarations - define the name, type and attributes of all program variables Dim Num as Integer ' declares a variable "Num" to be an Integer Dim vals(5) as Double ' declares an array of 5 Doubles named "vals" Assignment - set values for the variables Num = Num/10 ' after the assignment Num is set to 1/10th of its former value HiString = "Hello " + "World" ' value of HiString is set to "Hello World" Conditionals - do operations depending on the value of one or more variables if Num > 0 then Num = Num * 2 ' Basic logic building block Select Case .... End Case 'Case block simplifies GUI programming Iterations - control looping for repeated operations for i = 1 to 5 'For-loop counts through a precise number of steps while ( val(i) > val(imin) ) 'While loops as long as condition remains True Subroutines - calls on functions and subroutines Private Sub Form_Load() 'A subroutine does not return a value Private Function Digit() ' A function returns a value Special statements - used to implement unique features Set MyObject = Your Object 'Set statement assigns object references Print #FileNum, MyObject.Text 'I/O statements like Print, Input Line

14 Mathematical function Example
Arithmetic Operators Operator Mathematical function Example ^ Exponential 2^4=16 * Multiplication 4*3=12,   (5*6))2=60 / Division 12/4=3 Mod Modulus(return the remainder from an integer division) 15 Mod 4=3     255 mod 10=5 \ Integer Division(discards the decimal places) 19\4=4 + or & String concatenation "Visual"&"Basic"="Visual Basic" Palitha Baddegama , Computer Resource Centre, Hingurakgoda

15 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Conditional Operators Operator Meaning = Equal to > More than < Less Than >= More than and equal <= Less than and equal <> Not Equal to Palitha Baddegama , Computer Resource Centre, Hingurakgoda

16 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Logical Operators Operator Meaning And Both sides must be true or One side or other must be true Xor One side or other must be true but not both Not Negates truth Palitha Baddegama , Computer Resource Centre, Hingurakgoda

17 Variable and Data Types
Variable Names The following are the rules when naming the variables in Visual Basic It must be less than 255 characters No spacing is allowed It must not  begin with a number Period is not permitted Reserved Word not allowed Ex. Sub, Private, End Palitha Baddegama , Computer Resource Centre, Hingurakgoda

18 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Data Types Integer Long Integer Floating point Currency Byte Single Double Numeric String Date Boolean Object Variant Palitha Baddegama , Computer Resource Centre, Hingurakgoda

19 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Numeric Data Types Type Storage  Range of Values Byte 1 byte 0 to 255 Integer 2 bytes -32,768 to 32,767 Long  4 bytes -2,147,483,648 to 2,147,483,648 Single E+38 to E-45 for negative values E-45 to E+38 for positive values. Double 8 bytes e+308 to E-324 for negative values E-324 to e+308 for positive values. Currency -922,337,203,685, to 922,337,203,685, Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use +/ (28 decimal places). Palitha Baddegama , Computer Resource Centre, Hingurakgoda

20 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Nonnumeric Data Types  Data Type Storage Range String(fixed length) Length of string 1 to 65,400 characters String(variable length) Length + 10 bytes 0 to 2 billion characters Date 8 bytes January 1, 100 to December 31, 9999 Boolean 2 bytes True or False Object 4 bytes Any embedded object Variant(numeric) 16 bytes Any value as large as Double Variant(text) Length+22 bytes Same as variable-length string Palitha Baddegama , Computer Resource Centre, Hingurakgoda

21 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Variable Scope There are three levels of scope: project-level (also called "global" or "application" scope; the variable is accessible to all procedures in all modules of the project) module-level (the variable is accessible to all procedures in the module in which it is declared) local-level (the variable is accessible only to the procedure in which it is declared) Palitha Baddegama , Computer Resource Centre, Hingurakgoda

22 The Code Window The Code window is little more than a text editor with which you write the programming statements that tie the application together. An alternative technique to view the code is to double click anywhere on the form or the object and view the code for that particular object. The diagram shows the Code Window for the form Example Private Sub txtJAN_KeyPress(KeyAscii As Integer) Call TEST(KeyAscii, txtFEB) End Sub

23 Code window cont…. When you or another user compiles or runs the source program, VB translates the program into an executable program. You cannot make changes directly to an executable program. If you see bugs when you run the program, you must change the source application (which might contain multiple files in the project) and rerun or recompile the source.

24 The Project Explorer Window
Gives you a tree-structured view of all the files in the application. Microsoft changed the formal name from Project window to Project Explorer window

25 The Properties Window The property window represents an objects associated properties. Each property of a control such as a Label, command button etc. has its own unique set of properties. A different list appears in the Properties window every time you click over a different Form window object. The Properties window describes properties (descriptive and functional information) about the form and its controls. Many properties exist for almost every object in Visual Basic. The Properties window lists all the properties of the Form window's selected control. The property window is activated by pressing the shortcut key F4.

26 Running the Application
To run the application F5

27 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Variable Scope Module1 Public X as Integer Form Form2 Dim Y as Integer Dim Z as Integer Sub procedure 1 () Dim A as Double . End Sub Sub procedure 3 () Dim C as Double . End Sub Sub procedure 2 () Static B as Double . End Sub Palitha Baddegama , Computer Resource Centre, Hingurakgoda

28 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
MsgBox ( ) Function A=MsgBox(Prompt, Style Value, Title) Example: A=MsgBox( "Click OK to Proceed", 1, "Startup Menu")             A=Msgbox("Click OK to Proceed". vbOkCancel,"Startup Menu") Palitha Baddegama , Computer Resource Centre, Hingurakgoda

29 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Style Values Button Layout Value Short Description vbOKonly Displays the OK button. vbOKCancel 1 Displays the ok and cancel button. vbAbortRetryIgnore 2 Displays the Abort , Retry , Ignore vbYesNoCancel 3 Displays Yes , No and Cancel button vbYesNo 4 Displays the Yes / No button vbRetryCancel 5 Displays the retry and Cancel buttons Palitha Baddegama , Computer Resource Centre, Hingurakgoda

30 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Return Values and Command Buttons Value Named Constant Button Clicked  1 vbOk Ok button 2 vbCancel Cancel button 3 vbAbort Abort button 4 vbRetry Retry button 5 vbIgnore Ignore button 6 vbYes Yes button 7 vbNo No button Palitha Baddegama , Computer Resource Centre, Hingurakgoda

31 testmsg = MsgBox("Click to test", 1, "Test message")
testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message") Palitha Baddegama , Computer Resource Centre, Hingurakgoda

32 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
The Icons displayed in the message box are here Value Named Constant Icon  16 vbCritical 32 vbQuestion 48 vbExclamation 64 vbInformation Palitha Baddegama , Computer Resource Centre, Hingurakgoda

33 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
InputBox( ) Function A=InputBox(Prompt, Title, default_text, x-position, y-position) B= InputBox("What is your message?", "Message Entry Form", "Enter your message here", 500, 700) Palitha Baddegama , Computer Resource Centre, Hingurakgoda

34 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
The numeric functions a) Int Int(2.4)=2, Int(4.8)=4, Int(-4.6)= -5, Int(0.032)=0 and so on. b) Sqr Sqr(4)=2, Sqr(9)=3 and etc. c) Abs Abs(-8) = 8 and Abs(8)= 8. d) Exp Exp(1)=e1 = e) Fix and Int Fix(-6.34)= -6 while Int(-6.34)=-7 f) Round Round (7.2567, 2) =7.26 g) Log Log 10= Palitha Baddegama , Computer Resource Centre, Hingurakgoda

35 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Len (“welcome to VB tutorial”) = 22 Right ("Visual Basic", 4) = asic Left ("Visual Basic", 4) = Visu Ltrim ("  Visual Basic")= Visual basic Rtrim ("Visual Basic      ") = Visual basic Trim ("   Visual Basic      ") = Visual basic Mid ("Visual Basic", 3, 6) = sual B Instr (1, "Visual Basic"," Basic")=8 Chr (65)=A, Chr (122)=z, Chr (37)=% , Asc (“B")=66, Asc(“&")=38 Palitha Baddegama , Computer Resource Centre, Hingurakgoda

36 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Date format Format Syntax Result Format(Now,"m/d/yy") 10/02/09 Format(Now,"dddd,mmmm,dd,yyyy") Friday,October 02, 2009 Format(Now,"d-mmm") 02-Oct Format(Now,"mmmm-yyyy") October -2009 Format(Now,"hh:mm AM/PM") 09:36 AM Format(Now,"h:mm:ss a/p") 09:40 a Format(Now,"d-mmmm h:mm") 20-October 09:41 Palitha Baddegama , Computer Resource Centre, Hingurakgoda

37 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Number format Number = Format Syntax Result Format(Number,"# # # #.# #") 456.68 Format(Number,".# #") Format(Number," ") Format(Number," ") Format(Number,"# # # # #.# # # # #") Format(Number,"# # # # #.0000") Palitha Baddegama , Computer Resource Centre, Hingurakgoda

38 Format (n, "style argument")
Format ( , "General Number") Format (8972.2, "Fixed") Format ( , "Standard") Format ( , "Currency") Format ( , "Percent") Palitha Baddegama , Computer Resource Centre, Hingurakgoda

39 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Control Structures Looping While -Wend Do while-Loop Do-Loop while Do Until-Loop Do-Loop Until For next Branching IF IF Then IF Then – End IF IF Then Else – End IF IF Then Else IF Nested IF Select Case Goto Palitha Baddegama , Computer Resource Centre, Hingurakgoda

40 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Branching IF Then Condition True Statement1 False Palitha Baddegama , Computer Resource Centre, Hingurakgoda

41 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
IF Then – End IF Condition True Statement 1 Statement 2 Statement 3 Statement 4 …………….. Statement n False Palitha Baddegama , Computer Resource Centre, Hingurakgoda

42 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
IF Then Else – End IF Condition True Statement 1 Statement 2 Statement 3 Statement 4 …………….. Statement n False Statement 1 Statement 2 Statement 3 Statement 4 …………….. Statement n Palitha Baddegama , Computer Resource Centre, Hingurakgoda

43 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
IF <Condition> Then Statement 1 Statement 2 Statement 3 …………….. Statement n A Else Statement 1 Statement 2 Statement 3 …………….. Statement n B End IF Statement 1 Statement 2 Statement 3 …………….. Statement n C Palitha Baddegama , Computer Resource Centre, Hingurakgoda

44 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
IF Then Else IF Condition True Statement 1 Statement 2 Statement 3 …………….. Statement n False Condition True False Statement 1 Statement 2 Statement 3 …………….. Statement n Statement 1 Statement 2 Statement 3 …………….. Statement n Statement 1 Statement 2 Statement 3 …………….. Statement n Palitha Baddegama , Computer Resource Centre, Hingurakgoda

45 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
IF <Condition> Then Statement 1 Statement 2 …………….. Statement n A ElseIF <Condition> Then Statement 1 Statement 2 …………….. Statement n B Else Statement 1 Statement 2 …………….. Statement n C End IF Statement 1 Statement 2 …………….. Statement n D Palitha Baddegama , Computer Resource Centre, Hingurakgoda

46 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Nested Loop Condition True Statement 1 Statement 2 Statement 3 …………….. Statement n False Condition True False Statement 1 Statement 2 Statement 3 …………….. Statement n Statement 1 Statement 2 Statement 3 …………….. Statement n Statement 1 Statement 2 Statement 3 …………….. Statement n Palitha Baddegama , Computer Resource Centre, Hingurakgoda

47 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
IF <Condition 1> Then Statement 1 Statement 2 …………….. Statement n A Else IF <Condition 2> Then Statement 1 Statement 2 …………….. Statement m Else Statement p B C Palitha Baddegama , Computer Resource Centre, Hingurakgoda End IF Statement 1 Statement 2 …………….. Statement q D

48 Select Case Select case TestExpression Case Value1 Statement1
………………… Case Else Else Statements End Select

49 GoTo Statement Label : Goto Label or

50 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Looping While -Wend Condition Statement 1 Statement 2 Statement 3 ……………… Statement n True While Condition Statement 1 Statement 2 …………….. Statement m Wend False Palitha Baddegama , Computer Resource Centre, Hingurakgoda

51 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Do While - Loop Condition Statement 1 Statement 2 Statement 3 ……………… Statement n True Do While Condition Statement 1 Statement 2 …………….. Statement m Loop False Palitha Baddegama , Computer Resource Centre, Hingurakgoda

52 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Do – Loop While Statement 1 Statement 2 Statement 3 ……………… Statement n Condition Do Statement 1 Statement 2 …………….. Statement m Loop While Condition True False Palitha Baddegama , Computer Resource Centre, Hingurakgoda

53 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Do Until - Loop Condition Statement 1 Statement 2 Statement 3 ……………… Statement n True Do Until Condition Statement 1 Statement 2 …………….. Statement m Loop False Palitha Baddegama , Computer Resource Centre, Hingurakgoda

54 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Do – Loop Until Statement 1 Statement 2 Statement 3 ……………… Statement n Do Statement 1 Statement 2 …………….. Statement m Loop Until Condition Condition True False Palitha Baddegama , Computer Resource Centre, Hingurakgoda

55 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
For Next For counter = start To end [ Step] [ statements 1 ] [ statements 2 ] Next [ counter ] counter Required in the For statement. Numeric variable. The control variable for the loop. start Required. Numeric expression. The initial value of counter. end Required. Numeric expression. The final value of counter. step Optional. Numeric expression. The amount by which counter is incremented each time through the loop. statements Optional. One or more statements between For and Next that run the specified number of times. Next Required. Terminates the definition of the For loop. Palitha Baddegama , Computer Resource Centre, Hingurakgoda

56 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
For i = 1 To 7 Print “Visual Basic” Next i For - for loop  i use i as our integer start value = 1  To between start and stop value stop value = 7 Next - go to next step (if i > 7 then end for loop) i=1 Visual Basic i=2 Visual Basic i=3 Visual Basic i=4 Visual Basic i=5 Visual Basic i=6 Visual Basic i=7 Visual Basic Palitha Baddegama , Computer Resource Centre, Hingurakgoda

57 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
For i = 0 To 9 Print i Next i i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 Palitha Baddegama , Computer Resource Centre, Hingurakgoda

58 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Private Sub Command1_Click() Dim i As Integer Dim j As Integer For i = 1 To 5 For j = 1 To 7 Print i Next j Next i End Sub ; Inner Loop Outer Loop 21 35 14 28 7 1 2 5 3 4 Palitha Baddegama , Computer Resource Centre, Hingurakgoda

59 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Private Sub Command1_Click() Dim i As Integer Dim j As Integer For i = 1 To 5 For j = 1 To 7 Print j ; Next j Print Next i End Sub i=3 j=1 j=2 j=3 j=4 j=5 j=6 j=7 i=4 j=1 j=2 j=3 j=4 j=5 j=6 j=7 i=5 j=1 j=2 j=3 j=4 j=5 j=6 j=7 i=2 j=1 j=2 j=3 j=4 j=5 j=6 j=7 i=1 j=1 j=2 j=3 j=4 j=5 j=6 j=7 Inner Loop Outer Loop Palitha Baddegama , Computer Resource Centre, Hingurakgoda

60 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Private Sub Command1_Click() Dim i As Integer Dim j As Integer For i = 1 To 5 For j = 1 To 7 Print i ; Next j Print Next i End Sub i=5 j=1 i=5 j=2 i=5 j=3 i=5 j=4 i=5 j=5 i=5 j=6 i=5 j=7 i=5 i=3 j=1 i=3 j=2 i=3 j=3 i=3 j=4 i=3 j=5 i=3 j=6 i=3 j=7 i=3 i=1 j=1 i=1 j=2 i=1 j=3 i=1 j=4 i=1 j=5 i=1 j=6 i=1 j=7 i=1 i=4 j=1 i=4 j=2 i=4 j=3 i=4 j=4 i=4 j=5 i=4 j=6 i=4 j=7 i=4 i=2 j=1 i=2 j=2 i=2 j=3 i=2 j=4 i=2 j=5 i=2 j=6 i=2 j=7 i=2 Inner Loop Outer Loop Palitha Baddegama , Computer Resource Centre, Hingurakgoda

61 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
For i = 1 To 10 For j = 1 To 10 Print j ; Next j Print Next i For i = 1 To 10 For j = i To 10 Print j ; Next j Print Next i For i = 1 To 10 For j = 1 To 10 Print i ; Next j Print Next i For i = 1 To 10 For j = i To 10 Print i ; Next j Print Next i For i = 1 To 10 For j = 1 To i Print j ; Next j Print Next i For i = 1 To 10 For j = 1 To i Print i ; Next j Print Next i Palitha Baddegama , Computer Resource Centre, Hingurakgoda

62 Palitha Baddegama , Computer Resource Centre, Hingurakgoda
Working with Menus in VB6 Palitha Baddegama , Computer Resource Centre, Hingurakgoda

63 CONTROLS AND THEIR FUCTIONS EXPLAINED
Pointer-For resizing forms and controls (a tool for selection and manipulation of objects Label For changing text such as captions Frames-Purely visual effect (used to group check boxes or option buttons Check Box-For binary options Combo Box-Combination of list box and text box Timers-Can be used to control animations or timing events (often invisible) Picture Boxes-Allows the inclusion of bitmaps, icons on a form Text Boxes-Provide a standard way for accepting user input through the keyboard Command Button-Standard Window command buttons such as 'OK' and 'Cancel'

64 The Form Window The Form window is your primary work area where the visual development of the application is created or modified. The form window shows the main body of the application. The form can be resized to take up the width of the screen. Here objects are placed on to the form such as the command buttons, labels, text boxes, scrollbars, and other controls to form the main elements of the Graphical User Interface

65 Lecture 2 - Objects, Methods and Properties
This lecture focuses on the underlying principles that support Visual Basic programming.

66 Objects During most of the course we will be referring to objects as screen objects such as Labels. command buttons. text boxes. combo boxes other controls. Each object has its own set of properties (associated to the Object). A good example of this is the Label and Text box object properties. For example, the Caption property is used in most controls including the Label, however not in the Text box control (which uses the Text property).

67 Objects cont……. We can also set the property using the code rather than the properties window, the code is inserted inside the Code Window. The general structure to reference an objects property via code is given below: ObjectName.Property An example is illustrated below: Private Sub Form_Load() Form1.Caption = "Ascending Numbers" lblTitle.Caption = "ASCENDING NUMBERS" lblTitle.FontBold = True lblTitle.FontSize = 12 lblNum.Caption = "Enter a number between 1 to 30" & _ " you wish to see in ascending ORDER" lblOutput.Caption = “ " lblOutput.Visible = False lblOutput.FontBold = True cmdOK.Caption = "&OK" End Sub

68 Properties Properties behave like variables, they store the current state of an object as described above, for example colour, size, width etc. Properties of an object can be changed by two main ways: Using the properties window Using Visual Basic Code It is quite straight forward to change the property using the properties window, however, more thought is required to change the property using code. Below we demonstrate the two methods:

69 Properties cont….. Step 1 Highlight the object you wish to change (Label object). Step 2 Select F4 to view the property window, and thus change the Caption property to "Please enter your name" However, when changing the property using code an alternative technique is used. If you have not done programming before this will be new to you. It takes the following format Object.property and values are assigned to it. For example, the following code does exactly the same as the steps illustrated above: Label1.Caption = "Please enter your name" 'General format: Object. Property Here the code takes the object to reference the property. To do this we use the separator (full stop). and we then state the property we wish to change. In this case it is Caption property. Finally we give it a value by using the equals sign =. This is known as the Assignment symbol. The equal sign assigns the statement "Please enter your name" to the objects property (Label1.Caption).

70 Methods Methods are blocks of code which will carry out a task, but the complexity of the task itself is hidden from the user. For example, when heating a meal inside a microwave, we set the timer and then press the Start button, we are not interested how the button works but the outcome of the result, i.e. heated food. In the same way we can use Methods which perform a task instead of writing the task itself and then executing it. Methods behave like procedures and again are associated with the object. These are more commonly described as hidden event handlers which perform particular tasks. For example, the form has a couple of methods of which two are known as show and hide. These two methods are used to display and view multiple forms. We will be looking at these methods later during the course. The syntax for this is shown below and is referenced via the dot character (.): <OBJECT>.<METHOD> Form1.Show

71 Events Visual Basic is based on Event driven programming. This is slightly different if you have programmed in either Pascal or C. The first question is what is an event ?. Well in Visual Basic programming an event is Code used to handle some response inside a control. This is usually termed event handler routines The event is initiated by user action, for example, Click, MouseMove, MouseUp, Load etc. In the example, there is only one object - the command button placed on a form. Inside the object we have some event handler code. The event is called Click. When the user initiates the event by clicking on the command button, the message box displays "Hello world" on to the screen.   The format is: <OBJECT>_<EVENT> 'Forexample:Command1_Click()

72 Events cont…… The format for the code shown is very important when writing code. The underscore character needs to be placed between the object and the event. The parenthesis ( ) indicates that values can be passed in to the Event procedures. The procedure headings are created by default as well as the 'End Sub' to end the routine itself.

73 Other Common Events There are various events that are used inside Visual Basic the following list details the most common events that are used. Most of these will be used throughout the course: Form_Load Event This is one of the most common event handlers and sits behind a form. This event occurs only once in the lifetime of the application. When the form loads the properties can be set at run-time. The Form_Load event occurs when a form is placed in to memory, and is often used to set the initial properties of a form itself. However, there are various events that occur before or after a form is loaded into memory. The sequence is important in relation to the Form_Load event itself. The sequenced events are illustrated below: Initialize>Load>Resize>Paint From the illustration above it is clear that the Initialize event occurs before the Form_Load event and the Resize and Paint events occur after the Form_Load().

74 Lecture 3 - Data types, and variables
This lecture focuses on the different storage capacities of objects inside Visual Basic. This lecture also gives the general understanding for the background principles in VB programming.

75 Naming Conventions The objects on a form or listed in the properties window are given default names such as "Label1, Label2 ...Label3" etc. However, using more meaningful naming conventions for objects such as cmdOK, lblName would suggest that the first object is a command button, and the property is ‘OK’, the second a l label holding the name. This can result in certain ambiguities being resolved. For example: User states a control which is a "option box" and displays the "Sex" of the user. By default the control is named as "Option1" Using correct naming methods the control can be renamed as "optSex" - i.e. the control is a "option button" and holds the "Sex" to be It is important to use the correct naming conventions when writing code

76 Naming Conventions cont…..
Combo Box chk-Checkbox Cmd-Command button Dir-Directory list box Drv-Drive list box Fil-File list box Fra-Frame Frm-Form Grd-Grid Hsb-Horizontal scroll bar Img-Image Lbl-Label Lne-Line Lst-List box Mnu-Menu Ole-OLE client Opt-Option button Pic-Picture box Shp-Shape Tmr-Timer Txt-Text box Vsb-Vertical scroll bar

77 The Visual Basic data types
A data type represents the storage capacity of a variable. Suppose, somebody asks "What is your name" and you reply "Vas" if that is your name. Well, the value "Vas" is stored inside a 'container' somewhere inside your brain. The brain will allocate some storage space to hold the container and therefore can specify the 'holding' value and retrieve it if neccessary inside a container or variable. Visual Basic data types act in a similar way, in which the type of storage amount is determined as to whether the user intends to store numbers, characters or both inside the container. For example, a user may want to store whole numbers to allow this we use a data type called an integer which has the storage capacity only to store integer values only. Data Type Description and Range    Boolean A data type that takes on one of two values only: True or False. Byte 8 bits storage capacity, having the range of any character (from 0 to 255) from the ASCII character set. Currency Used to hold decimal values used for currency functions. The range is from -$922,337,203,685, to $922,337,203,685, (Note: four decimal places ensure that proper rounding can occur. ) Date Holds the date and time values. The date can range from January 1, 100, to December 31,9999. Double precision used for decimal values. The range for this data type is E+308 to E+308 Integer Whole numbers which range from -32,767 to +32,768. The storage capacity for this data type is 2 bytes. Note: cannot be used for decimal calculations LongInteger The data range for an integer is limited, due to its storage capacity. When an integer data type is above its range, there is an over flow and erroneous results occur. LongInteger is more suitable with additional storage capacity and increased range to - 2,147,483,648 to 2,147,483,647. Object A special data type which references objects such as controls and forms. Single Used as alternate data type for double precision known as Single-precision It requires less memory and lower data range from E+38 to E+38 String String data type is an array of characters. Data that consists of 0 to 65,400 characters of alphanumeric data (numeric and alphabetic) Variant Data of any data type and used for control and other values for which the data type is unknown.

78 Variables When storing values into a computer, for example a students name, age etc. We need to assign a data type to store that value. A variable is a container which is assigned some memory to hold the value. The value may be changed during program execution. Therefore, The program will have a place to hold information temporarily for calculations. To hold data that might change due to calculations or state changes within the application, you must declare variables. A variable is a named location that holds data. Dim Statement When declaring variables we use a special statement this is known as the Dim statement. This statement allocates sufficient memory to hold the value of the data, which is associated with the data type. Using the Dim statement to declare two variables (Dim stands for dimension) called Num1 (which will hold numbers) and Name (which will hold alphanumeric characters). The required memory is used to hold the data which is 2 bytes and 256 bytes respectively. Format: Dim variable As DataType

79 Assignment Statement The assignment statement is used to assign values to variables or objects. The symbol used for the assignment statement is the equals “ = " sign. For example: 'Use assignment statement 'to set value of objects properties... Label1.Caption = "Hi there how are you" Command1.Caption = "OK" Label1.FontBold = True 'Use assignment statement 'to set value of variables... Dim Today As Date Today = "12/09/99" Example 2 Text1.Text = "Fred" 'Text1.Text is assigned the value "Fred “ Text2.text = "Smith" 'Text2.Text is assigned the value "Smith" Text1.Text = Text2.text ‘ Contents of text2 is copied onto Text1 ‘ Therefore Text1.Text = "Smith" 'AND Text2.text = "Smith"

80 Option Explicit It is a good idea in Visual Basic to force all variables to be declared. For example using a variable which is undeclared i.e. no dim declaration results in errors occuring within the application during run-time Go to the General and Declarations section of the code window and Type in Option Explicit as shown in the diagram:

81 Reserved Words These are words that are used to create the language structure for VB. The VB language reference provides a listing of these words which must adhere to the syntactic rules of the language. The words form the body of the language itself and are predominantly based upon logic. Most of the Reserved Words have rules and must be defined in the required or correct format. Below are some common Reserved words that are used in Visual Basic. Most of these will be used regularly during the course. CASE SELECT FOR TO

82 LESSON FOUR

83 Label Controls A Label control is used primarily to display information on to a form. By default any label placed on a form. The label properties Property Description CaptionProperty to hold the textual appearance of the object The Label control can respond to a full set of events, however, the label control does not accept user input

84 Label Controls Example of the code used to change the Caption property of a Label: Label1.Caption = "Hello" 'change caption property Label1.FontBold = True 'add bold property Label1.FontSize = 12 'change Font size property

85 Text box The text box is used to allow the user to enter some input. The input can be used to enter values to match the required specification.

86 Text box The caption "Text1" in its caption property
Clearing the Caption property using the properties window or Changing the property using Visual Basic code

87 Clear text caption

88 KeyPress Event Step 1 - Double Click on a text box, to reveal the Code window.  The code window will reveal the name of the object (Text1) and the procedure (Change event). This is illustrated in the diagram below: Step 2 - Select the keypress event by dragging down the list and selecting the event.   This is illustrated in the diagram below:

89 Now enter the following code into the KeyPress event:
Private Sub Text1_KeyPress(KeyAscii As Integer) If (KeyAscii = 13) Then If Text1.Text = "" Then MsgBox "Please enter your name" Else MsgBox "Hi there " + Text1.Text End If End Sub

90 Command button Command buttons are different to labels and text boxes. They are used in the event of user responses to navigate through forms or accept responses.  

91 Command button A command button is placed on to the form. The reason of having this object is that once the user has completed entering their name, they Click on the command button to give control back to the application.

92 Program example Private Sub Command1_Click() If Text1.Text = "" Then
'if text box blank? MsgBox "Please enter the name" 'Display message Else 'if not blank? MsgBox "Hi there " + Text1.Text 'Display message and name End If End Sub


Download ppt "VISUAL BASIC PRESENTATION"

Similar presentations


Ads by Google