1 / 63

Visual Basic 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). Some asides and remarks.

betty_james
Télécharger la présentation

Visual Basic 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Visual Basic 2 Manipulating data types Exceptions Tooltips

  2. 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)

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

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

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

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

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

  8. A few types in VB • Integer, short and long are all integers (positive, negative – and zero – whole numbers). • Decimal, Single, double are reals which may have a fractional part • String (we type it with “” quotes in a vb program. Labels and textboxes contain string data) • Char (a single unicode char) • Boolean ( a true or false value) • Date

  9. Some Types with their storage sizes in bytes

  10. 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?

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

  12. 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)

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

  14. 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?

  15. The digitizer

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

  17. 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?

  18. A nicer GUI for the digitizer form

  19. A form to practice operations

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

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

  22. 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")

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

  24. Handling exceptions: note error message due to input data error

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

  26. Short-cut operators • Value = Value – stuff becomes • Value -=stuff • Value = Value * stuff becomes • Value *= stuff • Convert the following so the assignments use the abbreviated operator notation. • Value = Value \ stuff • Value = Value / stuff • Value = Value & stuff • Value = Value mod stuff

  27. A form with group boxes and calculations

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

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

  30. 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 try End With End Sub

  31. Book order form • Notice that some textboxes are read-only. • Complete the form as an exercise.

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

  33. You will often have to edit an existing project • Instead of selecting NEW Project, select OPEN project, which opens a file dialog box

  34. Editing an existing project: You can also select the project (solution file) from the list when the development environment loads (VB2005 express)

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

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

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

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

  39. 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).

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

  41. Setting control properties: font

  42. 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)

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

  44. Form Cancel button can similarly be set

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

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

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

  48. Form position • Upper left is where windows defaults to form position. • Setting start position of the form to some other spot will change this

  49. Setting form start position property to center screen

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

More Related