Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to VB6 Week 3 3/16/2004 PPCC - Introduction to VB6

Similar presentations


Presentation on theme: "Introduction to VB6 Week 3 3/16/2004 PPCC - Introduction to VB6"— Presentation transcript:

1 Introduction to VB6 Week 3 3/16/2004 PPCC - Introduction to VB6
Copyright ©2004, Tore Bostrup PPCC - Introduction to VB6

2 Review: Input Validation
Typical things to validate Empty inputs (example "") Input that is only blank spaces (example " ") Input that will not convert to the correct data type (example "seven") Values that are not allowed (example: a divisor of 0) 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

3 Review: Input Validation
Typical things to validate Empty inputs and input that is only blank spaces can be done in one test The Trim$() function removes leading and trailing spaces If Trim$(Text1.Text) = "" Then Input that will not convert to the correct data type The IsNumeric() function checks if an expression can be evaluated as a Numeric value If Not IsNumeric(Text1.Text) Then Values that are not allowed If CInt(Text2.Text) = 0 then 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

4 Review: Input Validation
Real Input Validation code If Trim$(Text1.Text) = "" Or Trim$(Text2.Text) = "" Then MsgBox "You must specify both Dividend and Divisor" Exit Sub ElseIf Not IsNumeric(Text1.Text) _ Or Not IsNumeric(Text2.Text) Then MsgBox "Only Numeric values are allowed" Else If CInt(Text2.Text) = 0 Then MsgBox "You can't divide by 0" End If 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

5 Review: Accessing Controls on the Form
In order to access a control on a form, we specify the name of the control. Usually, we do this to access one of the control's properties, so we also specify the property following a period: MsgBox "Hello " & Text1.Text 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

6 Review: Accessing Controls on the Form
We can also use a fully qualified control name: For instance Form1.Text1.Text The pseudo-variable Me is a reference to the form that the code belongs to: Me.Text1.Text Typing Me. brings up all the available properties and methods (procedures) for the form, including all the controls, allowing us to type in a partial name or scroll through a list of available selections 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

7 Review: Properties, Methods, and Events
We have already used both some Properties (Text1.Text, Label1.Caption) and some Events – or rather Event Procedures or Event Handlers (Command1_Click(), Form1_Load()) But what are "Methods"? 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

8 Review: What are Methods
A Method is simply a procedure (Sub or Function) that exists in a form's code (or in an object's code) that is available* to be referenced. * available to other code modules, objects, or applications 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

9 Review: Form and Control Properties
Forms and Controls have several Properties - most of which can be accessed and/or changed both during design and in code. Many form and control properties describe visual aspects of the form/control For example, a Label’s Caption property determines what text it displays 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

10 Form Properties Click in an empty area of the form, and review the properties window Appearance 0 – Flat or 1 – 3D A remnant from old Windows 3.x, determines if form has simulated shading and also determines form’s default background color 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

11 Form Properties Form Properties, contd. BackColor
Form’s Background Color Color values staring with &H80… are system colors referring to Windows Color Scheme. When the scheme changes, the form’s background color is affected also. Colors values starting with &H00… are specific colors with a 24-bit RGB values and can be decoded as follows: Values in the least significant byte (two rightmost hex digits) describe the amount of Red The next byte describe the amount of Green The third byte described the amount of Blue &H00BBGGRR 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

12 Form Properties Form Properties, contd. BorderStyle
0 – None, 1 – Fixed Single, 2 – Sizable, 3 – Fixed Dialog, 4 – Fixed ToolWindow, 5 – Sizable ToolWindow For a Form, this property not only determines what the form’s border should look like, but it controls to some extent what the form looks like and how it behaves. Caption = "Approximations of PI" The Caption is the Form Title (the text displayed in the form’s title bar) 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

13 Form Properties Form Properties, contd. Height, Left, Top, Width
These define the position (Left, Top) and size (Height, Width) of the form The coordinates used by VB6 are called TWIPS One TWIP is 1/1440 of a logical inch (logical, because the screen size and resolution affects the actual size). 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

14 Form Properties Form Properties, contd. ScaleMode
0 – User, 1 – Twip, 2 – Point, 3 – Pixel, 4 – Character, 5 – Inch, 6 – Millimeter, 7 – Centimeter Changes the units used for coordinates Pixels can be useful when maximum resolution is sought Point is good for text sizing English & metric size units are good for representing physical scale Twips are default and the most used scale, but suffers from the fact that not all twips values can be represented since 1 twip is (almost always) less than what can be displayed 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

15 Form Properties Form Properties, contd.
ScaleHeight, ScaleLeft, ScaleTop, ScaleWidth These represent the "usable area" of the window, and NOT the position and size of the form in some specific scale. ScaleHeight is the form Height minus space for the title bar and borders. Note that controls aligned to form’s top or bottom may also affect the usable space. ScaleWidth is similar to ScaleHeight – it represents the form’s Width minus space for the form’s borders. BUT – you can also SET these values, and that does not affect the actual size of the form, it simply provides a User scale for coordinates INSIDE the form. It also changes the ScaleMode property to 0 – User. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

16 Form Properties Form Properties, contd.
ScaleHeight, ScaleLeft, ScaleTop, ScaleWidth ScaleLeft and ScaleTop simply defines the coordinate for the leftmost and topmost position visible on the form. Normally this would be 0, but a negative value could be used to simplify creation of a "margin". Specifying Top/Left = 0 for controls in a form where ScaleTop/ScaleLeft is negative automatically puts them at the "margin" offset from the edge of the usable area. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

17 Form Properties Contd. FillColor and FillStyle Font FontTransparent
This is the color and style for shapes drawn on the form Font The font name, style, size, and effects for text on the form. The Form’s Font settings become the default Font settings for controls added to the form, but doesn’t change the fonts of existing controls. FontTransparent This determines if background colors or images will be displayed around text on the form. However, this doesn’t affect text in controls on the form. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

18 Form Properties Contd. ForeColor Icon
The Foreground Color – I.e. color of text and lines drawn on the form (but not on controls added to the form) Icon Define the Form’s Icon. Specify the fully qualified path of an Icon file (.ico) to assign an icon, or use the […] browse button. The icon will be shown in the form’s Title Bar, as well as in the task bar. If no icon is selected, a default VB "Form" icon is assigned. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

19 Form Properties Contd. LinkMode and LinkTopic MaxButton and MinButton
These are for using DDE. The DDE technology is obsolete, and not much used in today’s applications. DDE tends to make applications error-prone. MaxButton and MinButton Controls availability and display of Max and Min Buttons 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

20 Form Properties Contd. MouseIcon and MousePointer
The MousePointer allows you to select from a number of standard cursors, or to use a Custom cursor (defined in either an Icon or a Cursor file - .ico, .cur) Most of the different cursors are used to indicate some action, so don’t go wild with this… Icon files often don’t have a clear visual definition of the actual "point" of the cursor, so if you want to use an Icon file make sure you test this out 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

21 Form Properties Contd. Moveable
True (default) means the form can be moved by the user. False means that the user can not move the form. However, you can still move the form in code. Personally, I dislike windows that do not give me (as the user) full control, so I recommend against changing this value (leave as True). 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

22 Form Properties Contd. Picture
You can assign a background picture to a form. While this can make an application look better, it can also distract from the application content. If you use this, make sure your window does not get too "busy". Also, make sure controls and background picture do not "compete" for attention or obscure each other. Supported picture formats are: .bmp, .dib (device independent bitmap), .gif, .jpg, .wmf (windows metafile), .emf (enhanced metafile), .ico, .cur Pictures in the Metafile format will be resized to fit the form window. The other formats do not. Since they are all some form of bit-mapped formats, they are fixed size. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

23 Form Properties Contd. ShowInTaskbar
True – Form will have an icon in the taskbar when visible. False – There will not be an icon in the taskbar for this form. Be careful when "hiding" forms from the task bar. This is best used only when the form is shown as a Modal form (blocks the application – it has to be dealt with first). 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

24 Form Properties Contd. StartUpPosition 0 – Manual (Default)
Uses Top, Left properties of form 1 – CenterOwner A form can be launched as "owned" by another form. If this is the case, it will be centered over the owner form. If this setting is used and there is no owner specified, the screen will be centered on the desktop. 2 – CenterScreen The form will be shown in the center of the screen. 3 – Windows Default Documentation states: "Position in upper-left corner of screen" 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

25 Form Properties Contd. StartUpPosition, contd.
3 – Windows Default, contd. There is a bug when developing in the SDI mode (Tools, Options menu) – window reverts to Manual when run. Documentation says it will launch the form at the top left of the screen, but the behavior (when it works) is to pick the next "cascade" position on the screen. Cascade positions: First window at 0, 0 Next window offset by adding 330 twips to previous (Tested with VB6 SP5 in MDI mode on Win2k SP4) 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

26 Form Properties Contd. Tag WindowState
This is simply a property that the developer can use to keep information (a string value) in a form WindowState 0 – Normal Show window at its defined size (Width, Height) and at its StartUpPosition setting and coordinates (Top, Left) 1 – Minimized Show the window minimized to the task bar 2 – Maximized Show the window maximized to fill the screen 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

27 Some Control Properties
.Text vs. .Caption Some controls have a .Text property while others have a .Caption property. The .Text property may usually be used for the user to provide some INPUT to the app, the .Caption property is only used to display a text. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

28 Some Control Properties
Enabled (True/False) Determines if the control is allowed to react to input or user manipulation. For Instance: If not Enabled, a TextBox will for instance have its contents grayed out, and the user will not be able to select it or enter text into it. A CommandButton that is not enabled will be grayed out and not react to mouse clicks. Play with some other controls to see how they react… 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

29 Some Control Properties
Some other useful TextBox Properties: Alignment – Justify contents Left, Right, or Center BackColor – Background color inside textbox Font – Font name, style, size, etc. for text ForeColor – Color of the text in the text box Locked – Allows selecting, etc. but not changing MaxLength – Limit the maximum length of the input MultiLine – Allow multiple lines of text (word wrap or scroll) PasswordChar – Display this instead of entered characters ScrollBars – Display scrollbars in TextBox ToolTipText – Display a brief hint when cursor rests over control Visible – Set to False to hide a control from view 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

30 Some Control Properties
CommandButton Style Standard "text" button or Graphical with an Icon Picture Used to specify icon when Style is Graphical MaskColor and UseMaskColor Specifies what color in the icon should be considered transparent (mask color) and whether mask (transparency) should be used when style is Graphical. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

31 Some Control Properties
Timer Interval The time between Timer1_Timer() events measured in milliseconds. Maximum value is (just over 1 minute) If Interval = 0, the timer is not active Enabled Turn Timer On and Off 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

32 Some Control Properties
ListBox and ComboBox Columns Define columns in the List, Use a tab (vbTab) character to separate between columns IntegralHeight – Resize to only show full rows of text ItemData (List of values) A value (Long) that can be assigned to each item in the list MultiSelect (ListBox only) Allow selection of more than one list item, and how to select Sorted – Allows automatic (alphabetic) sort of list Style ListBox: Put a checkbox on each item to indicate if selected ComboBox: Type of ComboBox – try each setting… 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

33 Some Control Properties
File, Directory, and Drive These are specialty controls and not in much use anymore, but they illustrate how events may drive interaction between controls The File control is like a ListBox that lists the file names in a folder specified by the Path property The Directory control shows a directory tree opened to the folder specified in the Path property The Drive control is like a ComboBox that lists the drives on the system. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

34 Some Control Properties
By selecting a Drive, we can change the path for the Directory control, and by selecting a different directory, we can change the path for the File control. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

35 Some Control Properties
File Control Pattern File Name Patterns to display ReadOnly, System, Hidden Include files with these attributes 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

36 Exercise Create a New Project
Add a DriveListBox control, a DirListBox, a FileListBox, a Label and a TextBox to the form. Form Name: "FileList", Caption: "File List" Label Caption: "File Name Pattern" TextBox Name: "txtPattern", Text: "" 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

37 Exercise Your form should look something like this: 3/16/2004
PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

38 Exercise We want to "wire" the controls up so that:
When we change the drive, we want the DirListBox to show directories on the selected drive When we select another directory, we want the FileListBox to display the files in that directory When we change the File Pattern, we only want to show files that match the new pattern 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

39 Exercise Use the Drive1_Change() event to change the Dir1.Path
Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Use the Dir1_Change() event to change the File1.Path Private Sub Dir1_Change() File1.Path = Dir1.Path 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

40 Exercise Use the txtPattern_Change() event to change the File1.Pattern property: Private Sub txtPattern_Change() File1.Pattern = txtPattern.Text End Sub Run the application Notice that you have to double-click to actually change the Path property of Dir1 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

41 Designing a User Interface
The Calculator A Menu A TextBox A Label Several Buttons 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

42 Designing a User Interface
Start a new project Set the Form's Properties: Name = "frmCalc" Caption = "Calculator" Icon = Browse for a suitable icon… Size the form to it's approximate target size Click anywhere on the form (not on the title bar) to select it Click the Menu Editor button on the toolbar We will use the Menu Editor to create these menus 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

43 Designing a User Interface
Menu Editor The text displayed in the menu Internal name of menu control entry Menu Entries Indentation control buttons Move to Next menu entry in list 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

44 Designing a User Interface
Menu Editor Start filling in Type "Edit" in Caption Type "mnuEdit" in Name When you hit Enter or click on Next, the list selection moves down to the next (empty) line. This adds a "top level" menu selection – one that is visible on the form in its menu bar 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

45 Designing a User Interface
Menu Editor To add the items that drop down under a top level menu, we add an indentation level by clicking on Notice the four dots in the list Specify Ctrl+C as Shortcut 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

46 Designing a User Interface
The full menu should look like this: Edit Copy Paste View Standard Scientific - (seperator line) Digit grouping Help Help Topics About Calculator Notice: "Standard" is Checked 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

47 Designing a User Interface
Menu Editor Make sure all menu items have a (unique) Name and click OK to close the menu editor and apply the menu to the form. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

48 Designing a User Interface
Next, let's add the TextBox and Label Set the properties for the TextBox: Name = "txtData" Text = "0." Alignment = 1 – Right Justify Set the properties for the Label Name = "lblMem" Caption = "" BorderStyle = 1 – Fixed Single 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

49 Designing a User Interface
Add some buttons: Add "Backspace" button, set its properties: Name = "cmdBackspace" Caption = "Backspace" VB6 has a limitation so we cannot set the foreground (text) color of a button, use an Italic Font instead. Select the button, Copy and Paste it "You already have a control named 'cmdBackspace'. Do you want to create a control array?" Answer NO, we want these particular buttons to be easily identified by their name only. Move it into place, and repeat Paste to get the third "top" button 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

50 Designing a User Interface
Modify the "pasted" buttons: Name = "cmdCE" and "cmdC" Caption = "CE" and "C" Other properties (size, font) are "inherited" through the copy & paste. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

51 Designing a User Interface
Add the "MC" button Name = "cmdMem" Caption = "MC" Font: Italic 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

52 Designing a User Interface
Add the "0" button Name = "cmdDigit" Caption = "0" Select button and Copy & Paste it "You already have a control named 'cmdDigit'. Do you want to create a control array?" Answer YES this time. The original cmdDigit will get Index = 0 and the new button will get Index = 1 Make the new button the "1" button. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

53 Designing a User Interface
Set properties for the "1" button: Move it to its proper location Caption = "1" Do another Paste This time no message comes up because we already have a control array for "cmdDigit" Set Caption = "2" Move to proper location Repeat for button "3" 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

54 Designing a User Interface
Now speeding up a little: Select all three buttons "1", "2", and "3" Copy & Paste Move these into position and change their Captions to "4", "5", and "6" respectively Repeat Paste Move these into position and change their Captions to "7", "8", and "9" respectively 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

55 Designing a User Interface
Exercise: Create the remaining buttons as individual buttons (not control arrays, but using the Copy and Paste method to minimize the effort) Also note that you can change many properties on multiple controls by selecting the ones to change and editing in the Properties window. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

56 Designing a User Interface
Finally, in order to get the three top buttons to match the width of the "keypad" underneath them, we need to experiment with their width and spacing. First, find an approximate size and spacing Next, make sure the Left edge of the first button matches the left edge of the "keypad" Next, try lining up the Right edge of the third top button with the right edge of the keypad You may need to modify the Left property in the properties window to make this work – try increments of 15 when you are close. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

57 Designing a User Interface
Matching outsides, contd. Once you have the Left and Right edges aligned and the sizes reasonable, select the three buttons and click Format > Horizontal Spacing > Make Equal. Your top buttons should now be evenly spaced and matching the outline of the "keypad" 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

58 Designing a User Interface
Let us take a look at the Control Array Select one of the "digit" buttons, for instance button "4" Note how the Properties Window shows "CmdDigit(4) CommandButton" If you did the copying and pasting in order as instructed, each button should have the same index as its Caption. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

59 Designing a User Interface
Control Array Double-click one of the "digit" buttons Notice the Event Handler procedure: Private Sub cmdDigit_Click(Index As Integer) End Sub This means we can use the Index in the procedure txtData.Text = CStr(Index) 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

60 Visual Basic Code Statements
We have seen the following statement types Dim <VariableName> as <Type> [Private] Sub <ProcedureName>[(<ParameterList>)] If <Expression> Then [ElseIf <Expression2> Then] [Else] End If MsgBox <Expression> Assignment statements (<Variable> = <Expression>) Use of Functions: (IsNumeric(<Expression>), Cint(<Expression>), Trim$(<Expression>), etc. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup PPCC - Introduction to VB6

61 Loops There are several types of loops in VB: For-loops Do-loops
While-loops 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

62 For-Loops The simple form is one that increments a variable For i = 1 to 10 MsgBox "i is " & I Next The other type is one that goes through a collection of items – but we haven't learned about that yet… For Each frmX In Forms MsgBox "Found form with Caption=" & frmX.Caption Next 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

63 For-Loops What is the result of this code? Dim x As Integer
Dim i As Integer x = 0 For i = 1 to 3 x = x + 2 Next MsgBox "x is " & x 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

64 Loops Do-loops …or Do [{While | Until} condition] … Loop Do …
Loop [{While | Until} condition] 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

65 Loops While-loops While condition [statements] Wend 3/16/2004
PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

66 Loops The Exit Statement
Exit Do Exit For Exit Function Exit Property Exit Sub The Exit statement provides a way to exit from a specific code structure if the statement is executed. Exiting a loop inside a procedure violates the principle of "invariants" in code, and therefore I discourage it An "invariant" is a condition that can be trusted to be true at a specific point in the code, regardless of how one got there After a loop, a natural invariant would be that the loop exit condition should be true. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

67 Loops Best Practice Instead of using a hodgepodge of different loop constructs, select a few that you will use in your code. Use both forms of the For … Next loop Use either Do-loops or While-loops – not both If you choose to use Do-loops Determine if you will use the loop criteria at the top of the loop (my preference) or at the end of the loop Use either While or Until conditions – not both Using Until condition is equivalent to While NOT condition 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

68 Select Case We have seen that the IF statement can be used to check a value, and that we can use ELSEIF constructs to create multiple independent criteria. This works well for one or two comparisons, but gets more difficult when we want to compare a single expression to multiple values. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

69 Select Case The statement Select Case does just that: Select Case x Case 0 'Code to run if x=0 Case 1 'Code to run if x=1 Case 2 'Code to run if x=2 Case else 'Code to run otherwise End Select 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

70 Select Case Variations: Select Case x Case 0, 3 '… Case 4 to 8
Case Is < 0 End Select 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

71 Select Case Full syntax: SELECT CASE <Expression>
Case <Expression>, <Expression> To <Expression>, Is <ComparisonOperator> <Expression> There can be any number (1+) of Case statements in a Select Case A single Case statement can have a list of match conditions, separated by commas The <Expression> in the Select Case is compared to each of the Case expressions until a match is found 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

72 Operator Precedence Operator Precedence refers to the "priority" of different operators in an expression, and determines the order in which operations are performed: X = is calculated as: 3, plus 5, plus 2 X = * 2 is calculated as: 5, times 2 (=10), 3, plus 10 * has a higher operator precedence than + 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

73 Operator Precedence Appendix A in the book contains the Operator Precedence table 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

74 Operator Precedence Arithmetic operators are evaluated first, next the Comparison operators, and last the Logical Operators * NOTE: All Comparison operators have the same precedence Also see 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

75 Arrays Some times we have data about multiple items
Instead of creating variables like: Weight1, Weight2, Weight3, etc. we can create an ARRAY: Dim arrWeight(10) As Single arrWeight(3) = … etc. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

76 Arrays When we dimension an Array, we specify the UPPER BOUND for the array The LOWER BOUND for an array is 0 unless otherwise specified. Dim arrWeight(10) As Single Contains 11 items – arrWeight(0) to arrWeight(10) each containing a variable of type Single 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

77 Arrays Variations: Specify the LOWER BOUND:
Dim arrWeight(1 to 10) As Single Create an array of UNKNOWN number of items: Dim arrWeight() As Single Redim [Preserve] arrWeight(nItems) As Single 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

78 Arrays Variations: Variant Arrays – A Variant can be any type – that also means it can be an Array: Dim varrWeight As Variant Redim varrWeight(nCount - 1) Some functions return a Variant Array (for example Split()). 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

79 Arrays Determining the Array Size:
LBound(arrWeight) gives the Lower Bound, I.e. 0 if not otherwise specified UBound(arrWeight) gives the Upper Bound For i = LBound(arrWeight) To UBound(arrWeight) MsgBox "Weight of item " & i & " is " & arrWeight(i) Next 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

80 Arrays There is a statement that allows us to specify that the DEFAULT LOWER BOUND shall be 1 instead of 0: Option Base 1 This is NOT considered a good practice! Get used to starting with 0 and incrementing until Count – 1. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

81 Data Type Conversion Already presented. 3/16/2004
PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

82 Variable Naming Conventions
It is common to assign variable names a type prefix, for example: s str String i, n int Integer l lng Long b bool Boolean f sgl Single r dbl Double v var Variant c byt Byte Etc. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

83 Object Reference Variables
When we deal with things that are OBJECTS, such as Forms, Controls, and other types of objects, we use something called Object Reference Variables. For example (frmX is an Object Reference Variable): Dim frmX as Form For Each frmX in Forms MsgBox "Found form with Caption=" & frmX.Caption Next 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

84 Object Instantiation We Instantiate an Object by creating a New Instance of the Class that defines the Object: Dim frmX as Form1 'Instantiate a new copy of Form1 Set frmX = New Form1 Then we can work with it: frmX.Show 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

85 Object Instantiation It is possible to have an object automatically instantiated, but this is not usually considered good practice Dim frmX As New Form1 We can use it right away: frmX.Show 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

86 Object Instantiation Objects fall under the principle of "Your mother doesn't work here" So – Clean Up after yourself: (If you Open It, Close It) If you Create It, Destroy It Set frmX = Nothing When using Dim … As New …, the destruction is not "permanent" – attempting to use it will re-instantiate it (another copy). 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

87 Object Instantiation Some Objects have Open and Close methods (or similar) This is the case for database objects In that case, the sequence should be: Instantiate (Set objX = New Object) Open (objX.Open …) … use Close (objX.Close) Destroy (Set objX = Nothing) 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

88 String Manipulation String Functions Asc, Chr CStr, Str Filter
Format, FormatDateTime, FormatCurrency, FormatNumber, FormatPercent Instr, InstrRev LCase, UCase Left, Right Len, LenB 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

89 String Manipulation String Functions, Contd. StrComp
LTrim, RTrim, Trim Mid Replace Space, String Split, Join StrReverse 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

90 String Manipulation String Functions, Contd. Option Compare Like Lset
Specify Default Type of Comparison Like String Comparison operator Lset Statement 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

91 String Manipulation VB makes it relatively easy to perform String Manipulation by providing a rich set of string functions. For Example Left$(<string>, <length>) Right$(<string>, <length>) Mid$(<string>, <frompos>, <length>) Len(<string>) Instr([<startpos>,] <string>, <findstring>) 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

92 String Functions Most VB String functions that return string variables exist in two "versions" One that returns a strongly typed String Function named is postfixed with a $ sign: Chr$(<Expression>) Not available in VBScript! One that returns a Variant string The same function name without the $ sign Chr(<Expression>) Difference is when the <Expression> is Empty 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

93 String Manipulation VB also provides ways to compare strings in different ways: Case Sensitive comparisons ("A" <> "a") Case Insensitive comparisons ("A" = "a") Performing simple "pattern" matching 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

94 String Comparisons Option Compare {Binary | Text | Database}
This statement controls how string functions that include a compare parameter behave when that parameter is not specified. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

95 String Comparisons Comparison Types Binary Text
Comparison is case sensitive and is based on the underlying character codes in the string Text Comparison is case-insensitive Comparison uses the computer's configured locale's (country/language) collating (sort) order to determine whether two characters are considered equal (for example A=a, Ê=ê, Ø=ø, etc.) 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

96 String Comparisons Comparison Types, contd. Database
Comparison is based on the MS Access database's settings, by default it is case-insensitive While allowed in a VB6 application, this is intended for MS Access VBA (code written in MS Access). 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

97 String Comparisons Like Operator result = string Like pattern
If string matches pattern, result is True; if there is no match, result is False. If either string or pattern is Null, result is Null. The behavior of the Like operator depends on the Option Compare statement. The default string-comparison method for each module is Option Compare Binary. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

98 String Comparisons Pattern Matching with the Like operator
string Like pattern pattern may contain Characters in pattern Matches in string ? Any single character * Zero or more characters (any) # Any single digit [0-9] [charlist] Any single character in charlist [!charlist] Any single character NOT in charlist 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

99 String Comparisons Pattern Matching, contd.
[charlist] can use ranges: [A-Za-z0-9] If you want to match against any of the special characters ?, *, #, [, or ] Place them in []: sText Like "[[][*][]]" Returns TRUE if sText is "[*]" Useful for partial matching: If sLastName Like "Bost*" Then 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

100 String Comparisons Create a small test app to play with pattern matching: New Project Label, Caption: "String" TextBox, Name: "txtString", Text: "1 for all* and all for 1" Label, Caption: "Pattern" TextBox, Name: "txtPattern", Text: "#*#" CommandButton, Name: "cmdLike", Caption: "Like?" Label, Name: "lblResult", Caption: "" Private Sub cmdLike_Click() lblResult.Caption = CStr(txtString.Text Like txtPattern.Text) End Sub 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

101 String Manipulation LSet Statement
The LSet statement Left aligns a string within a string variable when the two variables are strings LSet stringvar = string …Or copies a variable of one user-defined type to another variable of a different user-defined type when the variables are user-defined types LSet varname1 = varname2 LSet is not commonly used. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

102 String Functions Asc(string), Chr(charactercode) iAsciiCode = ASC("A")
Gives us the ASCii code of the first character in the parameter passed to the function. sChar = Chr$(65) Returns a string containing the character whose ASCII code is specified in the parameter to the function. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

103 String Functions CStr(expression), Str(number)
These convert the expressions in their parameters to String expressions CStr takes any type except Null as a parameter Str only works with numbers, and adds a leading space when the number is positive. Str only accepts the decimal point (.) as decimal separator – Use CStr() for applications that should work with other languages/in other countries. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

104 String Functions CStr, continued: If expression is CStr returns
Boolean A string containing True or False Date A string containing a date in the short date format of your system Null A run-time error Empty A zero-length string ("") Error A string containing the word Error followed by the error number Other numeric A string containing the number 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

105 String Functions Filter(sourcearray, matchstr[, include[, compare]])
Compares each element in the sourcearray against the matchstr, and returns an array that contains only the elements that include (include = True or not specified) or do not include matchstr. The compare parameter specifies the type of comparison to be performed 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

106 String Function Filter, Contd. compare can be: Constant Val
Description vbUseCompareOption NO LONGER AVAIL! -1 Performs a comparison using the setting of the Option Compare statement vbBinaryCompare Performs a binary comparison vbTextCompare 1 Performs a textual comparison vbDatabaseCompare 2 Microsoft Access only. Performs a comparison based on information in your database 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

107 String Functions Format, FormatDateTime, FormatCurrency, FormatNumber, FormatPercent VB provides several functions to format data of various types as strings. The most versatile is Format() itself – it gives the user control over the format to be presented With an explicit format specification, international considerations are not considered FormatDateTime, FormatCurrency, FormatNumber, FormatPercent use the configured local Date/Time formats, currency symbol, decimal and thousands separators, etc. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

108 String Functions Format(expression, format[, firstdayofweek[, firstweekofyear]]]) expression is the value to convert to a string format is the string that specifies the formatting of the returned string This can be a "named" format, for instance "Long Date", "Currency", or a user-specified string where different characters have special meaning 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

109 String Functions Format(expression, format[, firstdayofweek[, firstweekofyear]]]) firstdayofweek use local setting (vbUseSystem), or specify weekday number (vbSunday to vbSaturday) firstweekofyear These are mostly used in week number calculations, etc. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

110 String Functions Format, contd. firstdayofweek vbUseSystem
Use NLS API Setting (local default) vbSunday 1 Sunday (Default) vbMonday 2 Monday vbTuesday 3 Tuesday vbWednesday 4 Wednesday vbThursday 5 Thursday vbFriday 6 Friday vbSaturday 7 Saturday 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

111 String Functions Format, contd. firstweekofyear vbUseSystem
Use NLS API setting (local default) vbFirstJan1 1 Start with week in which January 1 occurs (default) vbFirstFourDays 2 Start with the first week that has at least four days in the year vbFirstFullWeek 3 Start with the first full week of the year 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

112 String Functions Instr([startpos,] string, findstring[, compare])
Instr searches for findstring in string starting from startpos (if specified), and returns the character position where a match starts. compare specifies the type of comparison to use 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

113 String Functions InstrRev(string, findstring[, startpos[, compare]])
InstrRev is similar to Instr, but it searches for findstring in string starting from the end of the string and working itself forward, and returns the character position where a match starts.. If startpos is specified, matching starts with that position. startpos = -1 or not specified means start from end of string (same as default). compare specifies the type of comparison to use 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

114 String Functions LCase(expression), UCase(expression)
These convert the characters in the expression strings to Lower Case and Upper Case respectively. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

115 String Functions Left(expression, charactercount), Right(expression, charactercount) These return the substring consisting of the charactercount leftmost/rightmost characters in expression 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

116 String Functions Len(expression), LenB(expression)
Len returns the length (number of characters) in the string specified LenB returns the number of BYTES in the string specified. If the string is a Unicode string, then LenB(sUnicodeStr) = 2*Len(sUnicodeStr) LenB is only used in special cases, typically with a few API's 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

117 String Functions StrComp(string1, string2[, compare])
compare is the same as seen before StrComp compares the two string and returns If StrComp returns string1 is less than string2 -1 string1 is equal to string2 string1 is greater than string2 1 string1 or string2 is Null Null 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

118 String Functions LTrim(string), RTrim(string), Trim(string)
LTrim removes leading spaces from a text (Left Trim) RTrim removes trailing spaces from a text (Right Trim) Trim removes both leading and trailing spaces 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

119 String Functions Mid(string, start[, length])
Mid returns a substring of string, starting with the character at position start, and containing length number of characters. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

120 String Functions Replace(expression, find, replace[, start[, count[, compare]]]) Replaces the first count occurrences of the find substring in expression with the replace string, starting from the start position and using the compare type of match, returning the string starting from the start position. Default start is 1 Default count is –1 (meaning all) Default compare is Binary if Option Compare is not defined, follows Option Compare otherwise. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

121 String Functions Space(number), String(number, character)
Space creates a string containing the specified number of spaces String creates a string containing the specified number of the character parameter. The character parameter can be a string (uses the first character of the string) or a character code. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

122 String Functions Split(expression[, delimiter[, limit[, compare]]])
Split creates an array of expression text fragments that are separated by delimiter in expression. The limit parameter specifies the (maximum) number of array elements to be returned, and therefore limit – 1 splits actually takes place. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

123 String Functions Join(sourcearray[, delimiter])
Join creates a string from the sourcearray array of strings by placing delimiter between each element in the array. An array (arrTell) ("Tell", "Me", "More") joined by the statement sJoined = Join(arrTell, " ") Results in the string "Tell Me More" in sJoined. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

124 String Functions StrReverse(expression)
The string result of expression is reversed, I.e. "abc" becomes "cba". 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

125 String Manipulation Exercise
You have received a mailing list with names entered in different ways. There are no middle names in the list, but some names include titles, etc. The titles may be: "Mr.", "Mrs.", "Ms." at the beginning of the string ", Jr." or ", Sr." after the name Names may be entered as [Title] First Last[Title] [Title] Last, First[Title] 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

126 String Manipulation Exercise
Our job is to write a subroutine that receives the name string as one parameter, and outputs the name into four separate TextBoxes txtPrefix, txtFirst, txtLast, txtSuffix We also need to create a "test harness" for the subroutine In this case, a project with a form that allows us to type in an arbitrary name entry, calls the subroutine, and contains the TextBoxes for the output. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

127 String Manipulation Exercise
You will at least use Like with pattern matching as well as Instr, Left, and Mid, and you can also make good use of Select Case See Sample Project NameSplit[2] for code 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

128 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup
3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

129 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup
3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

130 More controls (Option Button, CheckBox, Frame)
Look at a typical Print dialog box: Option Buttons Checkboxes Frames 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

131 More controls (Option Button, CheckBox, Frame)
A CheckBox can be Checked, Unchecked, and Disabled Any number of CheckBoxes can be in any state An Option Button can be selected or unselected Only ONE Option Button within the same container can be selected Selecting another Option Button will unselect the previously selected Option Button in the group (on the same container) 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

132 More controls (Option Button, CheckBox, Frame)
Frames are used for "visual grouping" of related input controls. Frames are Containers – meaning that you can place other controls on it 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

133 Containers Containers are controls (or windows) that can contain other controls (members) Place a control on a container, and move the container – the member controls follow the container. Container Controls: PictureBox Frame Tabbed Dialog CoolBar 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

134 Excercise Create a New Project (Standard EXE)
Place three Option Buttons on the form Run the project Select one of the option buttons Select another Now stop the application 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

135 Excercise Add a Frame to the form
Place three Option Buttons on the Frame Drag the frame to a different position Run the project Select one of the option buttons outside the Frame Select one of the option buttons inside the Frame Select another option button outside the Frame Select another option button inside the Frame Now stop the application 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

136 Excercise Select the Frame in Design view Copy and Paste onto form
Notice how the Member Controls were included 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

137 Excercise Option Buttons Best Practice
Name Option Buttons that are in a single group with the same name (i.e. make them a control array) The easiest way to do this is by creating the first Option Button in the group, naming it and setting any other common properties, and then use Copy & Paste to create the other Option Buttons in the group. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

138 Control Arrays We already saw an example of a Control Array in the Calculator user interface Multiple controls (of same type) with the same name, distinguished by an Index property Share a single set of Event Handler procedures with an Index parameter supplied Index does not need to be a set of contiguous values! 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

139 Control Array Exercise
Create a New Project Add a Label, a TextBox and a CommandButton Label Name: "Label1", Caption: "Character" TextBox Name: "txtChar", Text: "" CommandButton Name: "cmdIsBitSet", Caption: "Is Bit n Set?" 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

140 Control Array Exercise
Add an Option Button Name: "optBitNo", Caption: "Bit 0" Copy the Option Button and Paste Answer YES to create a Control Array Move the new Option Button to its location Modify Caption to "Bit 1" Repeat Paste & Move new option button Modify Caption to "Bit X" where X is 1 greater than in the previous option button's caption. Repeat until you have 8 option buttons 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

141 Control Array Exercise
Add a second label Name: lblResult Caption: "" 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

142 Control Array Exercise
Double Click the button in design mode You should be in the code window inside Private Sub cmdIsBitSet_Click() End Sub Enter the code: If miBitMask and ASC(txtChar.Text) <> 0 Then lblResult.Caption = "True" Else lblResult.Caption = "False" End If 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

143 Control Array Exercise
But we don't have a variable named miBitMask… Drop down the control selection in code window and select (General) Type in (under Option Explicit): Private miBitMask As Integer 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

144 Control Array Exercise
Next, we need some code to set the bitmask: Double click one of the Option Buttons in the form designer, or drop down the control selection combo in the code window and select optBitNo This brings up the Click event for the options 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

145 Control Array Exercise
Add the following code: Private Sub optBitNo_Click(Index As Integer) miBitMask = 2 ^ Index End Sub This results in the bitmask being set when we click one of the options. 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

146 Control Array Exercise
Two things remain: Initializing the bitmask and option Input Validation 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

147 Control Array Exercise
Initializing the bitmask and option We should set one of the options as selected By setting it in the Form_Load event (code), we ensure that miBitMask also gets initialized Private Sub Form_Load() optBitNo(0).Value = True End Sub 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

148 Control Array Exercise
Input Validation Make sure txtChar.Text is not empty A space is a valid character for this app, so we should not Trim() the text Private Sub cmdIsBitSet_Click() If txtChar.Text = "" Then MsgBox "You must first specify a character" Exit Sub End If … the remainder of the code is already entered 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

149 Control Array Exercise
Run the application Enter a character Select a bit number Click "Is Bit N Set?" Try a few subsequent characters with Bit 0 selected We get TRUE for every one! We have a BUG in our APP!!! 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

150 Control Array Exercise
What is the problem: Is our miBitMask value incorrect? Is our IF-test wrong? 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

151 Control Array Exercise
It turns out that our IF-test is wrong because of OPERATOR PRECEDENCE. If miBitMask And Asc(txtChar.Text) <> 0 Remember: Arithmetic operators are evaluated first, next the Comparison operators, and last the Logical Operators So we get: 1: Asc(txtChar.Text) <> 0 => True 2: miBitmask (=1) And True (-1) => 1 3: 1 is different from False (0), and the expression is therefore considered True Add parentheses to enforce order of operations If (miBitMask And Asc(txtChar.Text)) <> 0 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup

152 Control Array Exercise
Instead of using the statement miBitMask = 2 ^ Index in the optBitNo_Click event, we could set the Index properties of each of the options to the corresponding value: 1, 2, 4, 8, 16, 32, 64, 128 and use miBitMask = Index Try it! 3/16/2004 PPCC - Introduction to VB6 Copyright ©2004, Tore Bostrup


Download ppt "Introduction to VB6 Week 3 3/16/2004 PPCC - Introduction to VB6"

Similar presentations


Ads by Google