1 / 41

Multiple forms & functions & exceptions

Multiple forms & functions & exceptions. Index of projects in this show. Multiple forms Multiple forms (business site) FtoC with error handling Enable/disable buttons. A multiform app with little functionality.

chen
Télécharger la présentation

Multiple forms & functions & exceptions

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. Multiple forms & functions & exceptions

  2. Index of projects in this show • Multiple forms • Multiple forms (business site) • FtoC with error handling • Enable/disable buttons

  3. A multiform app with little functionality • Consider a form (let’s call it frmMain) that can route us to a second form, call it frm2 (which is the close to the default name, anyhow). • The frm2 can route us to frm3. • Suppose all the forms provide buttons to route us back, as well, with main’s back button routing us to frm3. • All the forms have a close button. • The frmMain has a quit button

  4. Here’s frmMain

  5. Here’s frm2 (frm3 looks the same)

  6. Properties & components • Start with frmMain. First click the form to open its properties window (or select this from the view). Make sure it’s name is mainform and the text it displays matches. • Try to run it in debug. Does it work? • You’ll need to select frmMain from the error window you got when the system went to look for a form1 subroutine.

  7. Sub main was not found error

  8. Click the error then select your main form from the list

  9. Buttons on frmMain • Use VB convention to name your buttons. This will also help you remember their names. • I named my buttons quit, closebutton, nextbutton, backbutton (on every form). This is NOT VB convention. • VB has no trouble keeping controls – or any field values - with the same names straight as long as they belong to different classes, in this case, forms. • Set the text display appropriately for your buttons.

  10. Add a form to your project • In the projects menu of the menu bar select addwindowform and then select the window form icon

  11. Add a form to your project

  12. Aside: You can change a form’s associated filename in the solution explorer by selecting the form and editing the filename in its properties.

  13. Naming your forms • I left my form2 and form3 with those default names (and text displays). (Note: These are not VB convention names!) • Add back, next, and close buttons to these forms and set their name properties to btnBack, btnClose and btnNext. Set their text properties to something appropriate. • Use the & symbol when defining button text to mark a hot key. &Back marks ‘B’ as a hot key. E&xit marks ‘x’ as a hot key.

  14. How should it work: next button goes on, back button goes back main form2 form3

  15. More about functionality • Should the user be able to close all the windows? • I don’t think so. Our application would still be running but we couldn’t see (let alone use) it. • If the user wants to close form2 or form3, let him, but show him the main form. • If he wants to close mainform, give him a messagebox display. • User is allowed to select quit from main form to terminate the application

  16. Writing the button code • We already know double-clicking a button will open the code window view and allow us to add code to a stubbed in button_click subroutine. • We know how to close an application: (Me.close() and End do this.) • What we don’t know is how to show and hide forms.

  17. Form methods • formRef.Hide() will hide a form named formRef without disposing of it. (formRef.Close() disposes the form). • formRef.Show() will show a form named formRef.

  18. new • In order to show forms we will need to create a reference to them. • Dim is the correct way to allocate variable storage. • Dim must be used with new to allocate another form as in: Dim myFormRef as new MyForm() (where MyForm is one of your form’s actual names)

  19. Here’s some code for frmMain Private Sub quit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles quitbutton.Click Me.Close() ‘ End …..can’t use this in VB2005 End Sub Private Sub backButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles backButton.Click Dim FormRef As New Form3() Me.Hide() FormRef.Show() End Sub ‘ next button handler is almost the same as back Private Sub closebutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closebutton.Click MessageBox.Show("are you sure you want to close me?", "you'll have nothing to look at", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error) ' Me.Hide() …notice this line is commented out End Sub

  20. Exercise(s) • Complete the code for the other two forms. • You could add functionality. The first form could ask what option the user wishes and route to the appropriate form. • Each form could perform some special operation for the user. • At this point there’s not much we could do on those forms except maybe F to C conversions.

  21. A business site exercise

  22. Pressing any button except exit

  23. exercise • Complete the project. There are just two forms. No matter which function is selected (except exit) the “under construction” form comes up. • Make sure keystrokes work to select action. • Go through and tab-order the buttons. What ordering makes sense?

  24. Exceptions • It often happens that files can’t be read or don’t exist, or that input data is not of the correct type. • For example, our FtoC converter expects a real number to be entered. • Handling exceptions is normally part of the programmer’s job.

  25. Exceptions are handled in Try…catch clauses • The code to handle an exception looks sort of like this Try do some stuff that might have exceptions Catch theException As ExceptionType clean up the mess End Try

  26. Exception types • There are many types of exception. • FormatException would occur if the user did not provide the correct (numeric) format for the input. • ArithmeticException would occur in the case of division by zero, for example. • There are many others!!! • Exception is the grand-daddy of all the others and will catch anything.

  27. Enable/disable buttons

  28. How it works • When a button is clicked, text is added to the listbox and the button is disabled (while the other button is enabled). • And visa versa.

  29. Code for one button Private Sub btnX_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnX.Click btnX.Enabled = False btnY.Enabled = True lst.items.add("button x") End Sub

  30. Your own functions and subroutines • A piece of code that (calculates and) returns a value is called a function. • A piece of code that performs some operations is called a subroutine. • We already know how to use VB stubbed event-handling subroutines. • Here’s an example of our own function.

  31. We revisit FtoC form • Recall Dim fahr,celsius as double Fahr = … Celsius = (5.0/9.0)*(fahr-32) We can package this calculation as a function call. Give the function the fahr value and get back the celsius value. Our code might look like this now: celsius = CValue(fahr)

  32. We revisit FtoC form • Functions and subs that we create must allocate appropriate temp storage for their parameters just as the ones we’ve used so far have done. • In VB, (and Basic, & FORTRAN) the function names themselves must have a type, because the name of the function is used as a variable and assigned a value inside the function. This is how the information calculated is sent back. • (An aside: Intel Assembly, C, C++, Java, and some other languages use the return keyword to send information back to the calling routine.)

  33. We revisit FtoC form: here’s our old code Dim celsius, fahr As Double fahr = Decimal.Parse(input.Text()) celsius = CValue(fahr) output.Text = celsius.ToString("N")

  34. Our new thinking • Get the input (it is a string) • If it is a number (watch out for format exception) go ahead and calculate conversion • Otherwise (catch exception) display some sort of error. • I add a string to hold input: Dim fstring As String

  35. Improved code for calculations Dim celsius, fahr As Double Dim fstring As String fstring = input.Text() Try fahr = Decimal.Parse(fstring) celsius = CValue(fahr) output.Text = celsius.ToString("N") Catch problem As FormatException output.Text = "input error " + fstring End Try

  36. The handled error

  37. We revisit FtoC form • Here’s the completed function: • Functions need an end function. (VB should provide it.) • Functions need to have their type specified (function …As type) • VB supports two mechanisms for returning the function result: • The function name, inside the function, in an assignment can hold & return the result as in someFunction=result • A return statement can be used as in return result • The parameters’ types must be specified. (param As type)

  38. Here’s my function Function celsiusFn(ByVal f As Double) As Double celsiusFn = 5 / 9 * (f - 32) ‘alternatively we could have written ‘return 5 / 9 * (f - 32) ‘this latter is the mechanism used in most programming ‘languages End Function

  39. About parameters Note that the parameter (f in this example) may be passed byVal or byRef, depending whether the function is allowed to modify the value passed in. More on the difference between byVal and byRef later in the course. You can name the parameter whatever you want, but that’s how you must refer to it (call it) in your program. Function or sub parameters have only local scope, which means they “live” only inside the sub or function where they are declared. You should avoid using the same name for dummy parameters as the names of actual variables elsewhere in your program.

  40. Slightly different form

  41. Keeping it short and sweet • We’d prefer to NOT repeat our code. • Code which updates displays or computes values in a fixed way should not be repeated in multiple functions or subroutines. • Try to localize such code as a sub or function and let other subs use it as needed.

More Related