63
Visual Basic 2 Manipulating data types Exceptions Tooltips

Visual Basic 2 Manipulating data types Exceptions Tooltips

  • View
    226

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Visual Basic 2 Manipulating data types Exceptions Tooltips

Visual Basic 2

Manipulating data types

Exceptions

Tooltips

Page 2: Visual Basic 2 Manipulating data types Exceptions Tooltips

Index of projects in this ppt

• Digitizer (digit extractor)

• Numeric operator practice form

• Exception handling in operator form

• Book order form

• The calculator (GUI only at this point)

Page 3: Visual Basic 2 Manipulating data types Exceptions Tooltips

Some asides and remarks• Formatting your program: VB will automatically format (indent,

capitalize etc.) your code.• VB is not case sensitive. • VB is not a “free-format” language. • VB “Instructions” are typed starting at the beginning of the line and

may not spill over unless you use the space-underscore continuation chars.

• Your VB program is a “class”, and code beginning the class definition and ending it appear at the start and end of your code, pasted in by the VB IDE: don’t mess with this.

• The VB IDE will also paste in a lot of code, (not visible by default, but NECESSARY!) which we will learn somewhat to edit, above the code you typically write.

• BE CAREFUL: Don’t delete code above (or below) your subroutines.

Page 4: Visual Basic 2 Manipulating data types Exceptions Tooltips

What should you be able to do?

• Find the VB icon, launch VB and edit/create a VB application.• Give your application a different name than the default.• Run (in the debugger) your application at any time during

development.• View the toolbox.• Add a control (or two) to your form.• View the properties.• Edit properties for your control like TEXT and NAME.• Use VB conventions for naming controls.• Open the code view.• Recognize datatypes and declare your variables appropriately in the

proper location of the code view.

Page 5: Visual Basic 2 Manipulating data types Exceptions Tooltips

Continued…

• Have a messagebox pop up on form load (or form click)?

• Do you understand the real (single, double) and string datatypes somewhat?

• Do you understand the idea of the event-handling subs whose code we have been writing? (which events they handle, why they have certain names, and so on)

• Perform some simple arithmetic on values entered and display the result.

Page 6: Visual Basic 2 Manipulating data types Exceptions Tooltips

Format specifiers for conversions of numbers to strings

• VB provides format specifications:• “N” or “n” for number, 2 decimal places given unless you

specify otherwise.• “P” or “p” for percentage. You may optionally specify

additional decimal places.• “D” or “d” for Integer only. You may optionally specify

places.• “C” or “c” for currency (dollar sign and 2 decimal places)• Value.toString(“N0”) converts value to a string with 0

decimal places.• Value.toString(“P3”) converts value to a string

“percentage” with three decimal places, as in “%5.678”• VB has date formatting which we’ll discuss another time.

Page 7: Visual Basic 2 Manipulating data types Exceptions Tooltips

Suggestions

• At the top of the application there’s a line of code:

Public class …• At the bottom there’s a related line:End class• Don’t edit these areas!!!• You may wish to bookmark my page or our class

ppt pages.• You may wish to save my ppts – or parts of it –

locally and use cut/paste to steal bits of code.

Page 8: Visual Basic 2 Manipulating data types Exceptions Tooltips

A few types in VB

1. Integer, short and long are all integers (positive, negative – and zero – whole numbers).

2. Decimal, Single, double are reals which may have a fractional part

3. String (we type it with “” quotes in a vb program. Labels and textboxes contain string data)

4. Char (a single unicode char)5. Boolean ( a true or false value)6. Date

Page 9: Visual Basic 2 Manipulating data types Exceptions Tooltips

Some Types with their storage sizes in bytes

Decimal

single

16

4

Integer

long

4

8

Date

Boolean

8

2

Byte

char

1

2

Page 10: Visual Basic 2 Manipulating data types Exceptions Tooltips

Remarks on real types with their storage sizes in bytes

• Note that single requires 4 bytes = 32 bits=2 words of storage. Double requires 64 bits =2(32 bits)=8 bytes.

• Decimal requires 16 bytes.

• In a program where high precision was not a critical issue but program storage requirements were important, which real datatype should be used?

Page 11: Visual Basic 2 Manipulating data types Exceptions Tooltips

Some arithmetic operators

• +,-,* and / and ^ are real number operators. ^ is the exponential operator.

• & is the string concatenatation operator• \ is the integer division operator which yields the

integer quotient -note!!! It is a backslash!!!• Mod is the modulus (remainder) operator for

integers.• The usual precedence rules apply and

parentheses must be used to override precedence

Page 12: Visual Basic 2 Manipulating data types Exceptions Tooltips

Some examples using various operators

• 2^5 is 2*2*2*2*2 or 32

• 12345 mod 5 is 0 (integer remainder)

• 12345\100 is 123 (integer quotient)

Page 13: Visual Basic 2 Manipulating data types Exceptions Tooltips

Most people need more practice with the integer operators \ and mod

• The /10 operation has what effect on an integer in general? consider what happens with 1234\10

• The mod 10 operation yields what value for an integer? Consider 1234 mod 10

• Can you say anything, in general, about what an integer mod 2 will be? Consider the two calculations, 123 mod 2 and 654 mod 2

• How about a value mod 5? Consider the two calculations, 123 mod 5 and 678 mod 5

Page 14: Visual Basic 2 Manipulating data types Exceptions Tooltips

A practice form

• Let the user enter a 5 digit number.

• Display the 5 digits in 5 separate labels or textboxes.

• How do you get the “one’s place” of a number like 54837?

• How do you prepare the input value to proceed to get the 2nd, 3rd, (and so on ) digits?

Page 15: Visual Basic 2 Manipulating data types Exceptions Tooltips

The digitizer

Page 16: Visual Basic 2 Manipulating data types Exceptions Tooltips

If you rename your form

• If you rename the form itself, you may get an error in debug. VB may not know which form should be executed (since form1 is missing). When it prompts with an error, “submain was not found” click on the error and select the start form from the list it presents. In this screenshot, I gave the form “somename”

Page 17: Visual Basic 2 Manipulating data types Exceptions Tooltips

Remarks 0n The digitizer

• We’ll learn to do this a few different ways. In this example, I did it practicing \ and mod operations.

• The same functionality could be provided by chopping up the string which was entered into separate characters.

• Later in the semester we could do this with much longer input values

• How do you limit the size of the input textbox data?

Page 18: Visual Basic 2 Manipulating data types Exceptions Tooltips

A nicer GUI for the digitizer form

Page 19: Visual Basic 2 Manipulating data types Exceptions Tooltips

A form to practice operations

Page 20: Visual Basic 2 Manipulating data types Exceptions Tooltips

Build the form

• The form has 3 labels (2 for input, 1 for output)

• It has 2 textboxes for numeric input

• It has 5 buttons.

• Add these components and set their properties.

Page 21: Visual Basic 2 Manipulating data types Exceptions Tooltips

The subroutines

• For each button-click event declare appropriate variables (either Integer or Double) and two strings. Get the two strings:

• For real division, eg., start with:Dim A, B, C As Double Dim s1, s2 As String s1 = txtBox1.Text s2 = txtBox2.Text

Page 22: Visual Basic 2 Manipulating data types Exceptions Tooltips

real-division… continued

• For the real-division button, now compute and display the result:

A = Decimal.Parse(s1)

B = Decimal.Parse(s2)

C= A / B ‘real division operator

lblAns.Text = c.ToString("N5")

Page 23: Visual Basic 2 Manipulating data types Exceptions Tooltips

Completed Real division sub example (and a preview of coming attractions)

Private Sub btnDiv_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiv.Click

Dim A, B, c As Double Dim s1, s2 As String s1 = txtBox1.Text s2 = txtBox2.Text Try ‘coming attractions part A = Decimal.Parse(s1) ‘this could cause a problem B = Decimal.Parse(s2) c = A / B lblAns.Text = c.ToString("N") Catch numexception As FormatException lblAns.Text = "format error" End Try End Sub

Page 24: Visual Basic 2 Manipulating data types Exceptions Tooltips

Handling exceptions: note error message due to input data error

Page 25: Visual Basic 2 Manipulating data types Exceptions Tooltips

Aside on Short-cut operators

• VB provides short cuts to operations in the same fashion that C++ and Java do.

• If your assignment statement has syntax:

Value = Value + stuff

• You can also write

Value += stuff.

• -, *, /, \ , ^ (and even string concat operator &) have similar short-cut forms.

Page 26: Visual Basic 2 Manipulating data types Exceptions Tooltips

Short-cut operators• Value = Value – stuff becomes• Value -=stuff• Value = Value * stuffbecomes• Value *= stuff• Convert the following so the assignments use the

abbreviated operator notation.1. Value = Value \ stuff2. Value = Value / stuff3. Value = Value & stuff4. Value = Value mod stuff

Page 27: Visual Basic 2 Manipulating data types Exceptions Tooltips

A form with group boxes and calculations

Page 28: Visual Basic 2 Manipulating data types Exceptions Tooltips

Messagebox appears for data error: Can you spot the error?

Page 29: Visual Basic 2 Manipulating data types Exceptions Tooltips

The clear button: note use of “with” operator which speeds up processing… Note also

how to set the form focus

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click

With Me

.txtTitle.Clear()

.txtPrice.Clear()

.txtDiscount.Clear()

.txtQuantity.Clear()

.txtExtendedPrice.Clear()

.txtDiscountPrice.Clear()

End With

Me.txtQuantity.Focus() ‘give this control the focus

End Sub

Page 30: Visual Basic 2 Manipulating data types Exceptions Tooltips

The calculate button function. You’ll have to add the try catch formaterror part

Private Sub CalcButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalcButton.Click

Dim q As Integer Dim p As Double Dim ep, d, dp As Double With Me

try q = Integer.Parse(.txtQuantity.Text) p = Decimal.Parse(.txtPrice.Text) ep = q * p d = 0.15 * ep ’15% is the discount dp = ep – d .EtxtExtendedPrice.Text = ep.ToString("C") ‘use currency format for output

display . txtDiscount.Text = d.ToString("C") .txtDiscountPrice.Text = dp.ToString("C") catch ex as formatexception ‘do something with messagebox end tryEnd With

End Sub

Page 31: Visual Basic 2 Manipulating data types Exceptions Tooltips

Book order form

• Notice that some textboxes are read-only.

• Complete the form as an exercise.

Page 32: Visual Basic 2 Manipulating data types Exceptions Tooltips

Hotkeys: Keystrokes also effect action

• Note underlined letters on buttons.

• Striking alt-hotkey will also navigate to the indicated form.

• Use & in front of the letter to use for navigation purposes when you define button text.

• For example, exitbtn text is “E&xit”

Page 33: Visual Basic 2 Manipulating data types Exceptions Tooltips

You will often have to edit an existing project

• Instead of selecting NEW Project, select OPEN project, which opens a file dialog box

Page 34: Visual Basic 2 Manipulating data types Exceptions Tooltips

Editing an existing project: You can also select the project (solution file) from the list when the

development environment loads (VB2005 express)

Page 35: Visual Basic 2 Manipulating data types Exceptions Tooltips

More forms: programming pointers

• There could be many forms in a single application. That’s one reason it is important to write whichForm.close() as in

Me.close()• Similarly, the various forms can all have buttons

and textboxes which may even have the same names.

• In Object-oriented languages, a field of a class is accessed using the notation: classInstance.fieldName

Page 36: Visual Basic 2 Manipulating data types Exceptions Tooltips

Good programming practice, continued

• The name of the form (as in Me) can be used to specify which components you mean. Here’s an improved version of subroutine clear_click:

Private Sub clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clear.Click

With Me

.input.Clear()

.output.Clear()

end with

End Sub

Page 37: Visual Basic 2 Manipulating data types Exceptions Tooltips

With/end with

Use a with/end structure to code multiple property changes on a given component. This runs faster than coding the name on every line. We’ll see more examples later.

Syntax is

With compName

…..

End with

Page 38: Visual Basic 2 Manipulating data types Exceptions Tooltips

A list of good programming pointers

• Comment – comments will help more than you think, next time you open and try to work on an application

• Name appropriately: use names like btnClear, txtInput, lblOutput, and so on. The names help us remember what the components are supposed to do.

• Code readability: Tabbing, proper indentation. VB does handle this somewhat for you, and it makes code more readable.

Page 39: Visual Basic 2 Manipulating data types Exceptions Tooltips

more programming pointers for VB

• Save, and build/debug frequently, watching for errors. It is much easier to fix problems in a small or recently-working application than it is to debug a large, error-ridden application.

• Don’t let your form become too cluttered: maybe you need more than one form?

• Keep components orderly, with importance and order following reading orientation (top to bottom, left to right). We will discuss navigation through a form (via tab and focusing another time).

Page 40: Visual Basic 2 Manipulating data types Exceptions Tooltips

More on properties and settings

• You can “select” multiple components on your form by selecting one, and using alt or ctl to select another (and another) or by selecting a several components using the mouse. (Click and draw a “box” around them).

• If you go to the properties window, the properties displayed are shared by all the components and you can set them as you want them. BorderStyle or font would be examples of properties you might want to set. Properties which appear empty are not shared.

Page 41: Visual Basic 2 Manipulating data types Exceptions Tooltips

Setting control properties: font

Page 42: Visual Basic 2 Manipulating data types Exceptions Tooltips

Keyboard vs mouse access

• Special naming conventions will provide shortcut/hot keys for button selection.

• Use the & when providing button text to mark the hotkey:

• For a button btnOK, if text is set to &OK instead of OK then ‘O’ is the hot key

• Text on btnExit should be E&xit instead of exit ( to set ‘x’ as the key)

Page 43: Visual Basic 2 Manipulating data types Exceptions Tooltips

An accept button• By setting the acceptbutton property of the form

you can specify a key to act as the “accept” key. When the user hits “enter” this key is fired.

Page 44: Visual Basic 2 Manipulating data types Exceptions Tooltips

Form Cancel button can similarly be set

Page 45: Visual Basic 2 Manipulating data types Exceptions Tooltips

Tabs and focus

• On a window form, one control has the focus. Tabbing from control to control changes the focus.

• You can ask for the focus for a component in a sub with the code

compName.focus()• Controls which can have focus have a TabStop property

which you can set to true (or false). Setting the property to true means focus will stop here when you tab to here.

• A Tabindex property determines the index of tab ordering of each control. Focus will start on the control with tabindex set to 0. You can set the next tab focus control’s index to 1, and so on.

Page 46: Visual Basic 2 Manipulating data types Exceptions Tooltips

Tabs and focus: select view/tab order to display the current tab ordering

Page 47: Visual Basic 2 Manipulating data types Exceptions Tooltips

Click the controls in the order you’d like tabbed focus to move. Esc or view/tab order again to

make numbers disappear when done

Page 48: Visual Basic 2 Manipulating data types Exceptions Tooltips

Form position

• Upper left is where windows defaults to form position.

• Setting start position of the form to some other spot will change this

Page 49: Visual Basic 2 Manipulating data types Exceptions Tooltips

Setting form start position property to center screen

Page 50: Visual Basic 2 Manipulating data types Exceptions Tooltips

Tooltips popup windows indicate control use

• You can add a tooltip component to your form.

• If you add a tooltip, each control has a new property – the tooltip that should display.

• Selecting the tooltip property allows you to enter some text to display in the tip

Page 51: Visual Basic 2 Manipulating data types Exceptions Tooltips

Aside on the component tray

• Tooltips appear in a component tray.• This is an area “under” your design window view

containing components that have no visual display at run time.

• Timers and printers, eg., will also go in the component tray

Page 52: Visual Basic 2 Manipulating data types Exceptions Tooltips

Tooltips appear in a component tray (below designer window) which contains components that

have no visual display at run time.

Page 53: Visual Basic 2 Manipulating data types Exceptions Tooltips

Our tip on the accept button pops up when we run the application and pause at this control

Page 54: Visual Basic 2 Manipulating data types Exceptions Tooltips

An exercise: the calculator GUI

Page 55: Visual Basic 2 Manipulating data types Exceptions Tooltips

Building the Calculator GUI

• The calculator has 3 group boxes, a textbox, and a bunch of buttons.

• Text in the read-only textbox at the top of the form is right-aligned. (see next slide)

• Use the align/resize layout menu to get the calculator buttons all properly lined up.

Page 56: Visual Basic 2 Manipulating data types Exceptions Tooltips

Align text right

Page 57: Visual Basic 2 Manipulating data types Exceptions Tooltips

Using the layout menu: select buttons then align/resize

Page 58: Visual Basic 2 Manipulating data types Exceptions Tooltips

Complete the Calculator (note: you are not yet ready to program all the functionality)

Page 59: Visual Basic 2 Manipulating data types Exceptions Tooltips

TextAlign, BorderStyle, AutoSize

• You may wish to set autosize so a label can resize to hold a longer string.

• You may wish to place a border around a label.

• You may wish to align text in a label or a textbox

Page 60: Visual Basic 2 Manipulating data types Exceptions Tooltips

BorderStyle

• Borderstyle (in properties for your label) may have the value:

1. None (no border)

2. Fixed Single (1 pixel border)

3. Fixed 3D (recessed “3d” border)

Page 61: Visual Basic 2 Manipulating data types Exceptions Tooltips

Selecting text alignment: default is top left

Page 62: Visual Basic 2 Manipulating data types Exceptions Tooltips

The three borderstylesnote: autosize off in label 1 (alphabet

truncated)

Page 63: Visual Basic 2 Manipulating data types Exceptions Tooltips

Autosize defaults to true