2: Exceptions and User Interfaces - PowerPoint PPT Presentation

1 / 45
About This Presentation
Title:

2: Exceptions and User Interfaces

Description:

Structured Exception Handling. 2.1 User Interface Design. User interface interacts with the user ... 2.6 Structured Exception Handling. A runtime error is the ... – PowerPoint PPT presentation

Number of Views:67
Avg rating:3.0/5.0
Slides: 46
Provided by: kip50
Category:

less

Transcript and Presenter's Notes

Title: 2: Exceptions and User Interfaces


1
2 Exceptions and User Interfaces
2
Overview
  • User Interface Design
  • Input Validation
  • ImageList and ToolBar Controls
  • ListView Control
  • TreeView Control
  • Structured Exception Handling

3
2.1 User Interface Design
  • User interface interacts with the user
  • Analyze needs of users
  • consider first time users, intermediate users,
    and experienced users
  • Task-Based Approach
  • design program in terms of tasks it will perform
  • use-case scenarios describe interactions between
    program and users

4
Use Case Display Detail Information
  • Steps
  • User enters full or partial description of an
    item
  • Program locates and displays a list of items
    matching the description
  • User selects an item from the list
  • Program displays detailed information on the item

5
Designing Forms
  • Avoid clutter
  • Use AcceptButton and CancelButton
  • Restrict user's choices
  • Use TabControl to partition groups of controls
  • Use AutoScroll to add scroll bars to a form
  • Use TreeView for hierarchical information
  • Use ListView for multicolumn information

6
Using Microsoft Office as a Model
  • Menu tips
  • Use drop-down menus
  • Duplicate button commands with menu commands
  • Include File and Help menu commands
  • Include Edit, View, and Windows submenus
  • Use elipsis (...) when launching a submenu
  • Use standard shortcut keys
  • Wizards
  • lead users through series of predetermined steps
  • simplify users' decisions

7
2.2 Input Validation
  • General principles
  • try to anticipate and prevent errors
  • error checking can be at each tier of a
    Three-tier application
  • restrict user's ability to input bad data

8
Four Validation Approaches
  • Trap user keystrokes within each input control
  • Prevent user from moving away from an input
    control when invalid input found
  • Validate each control separately as user moves
    away
  • Perform validation after user inputs values into
    all form controls

9
Trapping Keystrokes
  • KeyPress event
  • e.Handled property
  • e.KeyChar property
  • Private Sub txtPatientID_KeyPress( _
  • ByVal sender As System.Object, _
  • ByVal e As System.Windows.Forms.KeyPressEventArgs
    ) _
  • Handles txtPatientID.KeyPress
  • Examples
  • If Not Char.IsLetter(e.KeyChar) Then _
  • e.Handled True
  • If Char.IsControl(e.KeyChar) Then Exit Sub

10
Keyboard Validation
  • Hands-on example
  • User enters a patient ID number
  • Program validates using KeyPress and TextChanged
    event handlers

11
Handling the Validating Event
  • Leave event
  • user moves away
  • Validating event
  • code checks contents of control
  • Validated event
  • fired after Validating event handler finds no
    error
  • CausesValidation property
  • determines whether a Validating event will be
    fired

12
Name and Age Input
  • Hands-on example
  • User enters last name and age
  • validates both values
  • Person class checks Age range
  • Displays events as they are fired

13
ErrorProvider Control
  • Hands-on tutorial
  • Displays exclamation mark icon next to controls
    having invalid input
  • Only one ErrorProvider needed on a single form

14
Calling SetError
  • Call SetError if you detect bad data in the
    control
  • Private Sub txtLastName_TextChanged(ByVal sender
    _
  • As Object, ByVal e As System.EventArgs) _
  • Handles txtLastName.TextChanged
  •  
  • If txtLastName.Text.Length 0 Then
  • errProvider.SetError(CType(sender, Control), _
  • "Last name cannot be blank")
  • End If
  • End Sub

Pass a blank value to hide the error icon
15
Handling Two Events
  • Handle both TextChanged and Leave to reduce
    duplicate code
  • Private Sub txtLastName_TextChanged(ByVal sender
    _
  • As Object, ByVal e As System.EventArgs) _
  • Handles txtLastName.TextChanged, _
  • txtLastName.Leave
  •   etc.

16
2.3 ImageList and ToolBar Controls
  • ImageList control stores images in a form
  • ToolBar control is a container for buttons
  • joined to an ImageList control
  • ButtonClick event handler
  • Private Sub tlbMain_ButtonClick( _
  • ByVal sender As System.Object, _
  • ByVal e As System.Windows.Forms._
  • ToolBarButtonClickEventArgs) _
  • Handles tlbMain.ButtonClick
  • e.Button.Text property
  • e.Button.Tag property

17
Simple ToolBar
  • Hands-on tutorial SimpleToolBar
  • Demonstrates ImageList and ToolBar controls
  • Output

18
2.4 ListView Control
  • Common in MS-Windows applications
  • Flexibility and power
  • rows and columns
  • columns can be resized and moved
  • click events
  • text alignment options
  • list items stored in a collection
  • user can edit list items

19
ListView (cont)
  • Creating Column Headings
  • use Detail view
  • Columns property page
  • Sample
  • lvwContacts.Columns.Add("Name", 150,
    HorizontalAlignment.Left)

20
ListView (cont)
  • ListViewItem class
  • defines appearance, behavior, and data associated
    with each row in a ListView
  • table format, large icons, small icons, or list
  • Creating a ListViewItem
  • Adding columns
  • using the SubItems collection
  • Changing font styles

21
Contacts ListView
  • Hands-on tutorial ListView1
  • Fills a ListView control with employee contact
    information

22
Useful ListView Techniques
  • Responding to ItemCheck event
  • fired when user clicks on an item's CheckBox
  • Selecting items
  • fired when user selects one or more items
  • Removing items
  • call the Items.Remove method
  • Other ListView features
  • (tables listing properties and events)

23
Removing ListView Items
  • Hands-on example ListView2
  • User selects items with checkboxes
  • removes all selected items
  • Editing capability is automatic

24
2.5 TreeView Control
  • Suited to hierarchical information
  • Each element is a node
  • type TreeNode
  • belongs to the Nodes collection
  • Travel Tree example

25
Basic TreeView Techniques
  • Add nodes
  • With tvwTravel
  • .Nodes.Add("Air")
  • .Nodes.Add("Land")
  • .Nodes.Add("Water")
  • End With
  • Expand the tree
  • tvwTravel.ExpandAll() 'expand all subtrees
  • aNode.Expand() 'expand one node's subtree

26
Basic TreeView Techniques
  • Insert multiple nodes
  • Dim nodeArray(2) As TreeNode
  • nodeArray(0) New TreeNode("Air")
  • nodeArray(1) New TreeNode("Land")
  • nodeArray(2) New TreeNode("Water")
  • tvwTravel.Nodes.AddRange(nodeArray)
  • Use BeginUpdate and EndUpdate to suspend and
    resume drawing of the tree while adding nodes

27
Basic TreeView Techniques
  • Get most recently selected node
  • Dim aNode As TreeNode tvwTravel.SelectedNode
  • Sort a tree
  • tvwTravel.Sorted True
  • Remove a node
  • tvwTravel.Nodes.Remove(tvwTravel.SelectedNode)
  • Remove a subtree
  • tvwTravel.SelectedNode.Nodes.Clear()
  • Insert node just before the selected node
  • With tvwTravel
  • Dim index As Integer .SelectedNode.Index
  • .Nodes.Insert(index, New TreeNode("Space"))
  • End With

28
Contact Categories
  • Hands-on tutorial TreeViewContacts
  • Fills a TreeView with a list of categories for
    name and email contacts
  • user can insert and remove entries
  • tree maintains itself in alphabetical order

29
Disk Directory TreeView
  • Hands-on example DirectoryTree
  • Displays a disk directory in a TreeView control
  • System.IO.DirectoryInfo class
  • Uses recursion
  • method calls itself

30
2.6 Structured Exception Handling
  • A runtime error is the result of a thrown
    exception
  • specifically, an unhandled exception
  • severe error that would cause the program to
    behave erratically if not dealt with
  • Two types of exceptions
  • those caused by faulty programming logic
  • those caused by events outside the programmer's
    control
  • Better than ad-hoc error handling methods
  • which were unreliable because they relied on
    skills of individual programmers

31
What is Structured Exception Handling?
  • Programs can respond to exceptions
  • allow program to resume gracefully after an error
  • called handling an exception
  • Common Language Runtime (CLR)
  • internal mechanism for exception handling
  • Interaction between two parts of a program
  • one part of a program can only detect an error
  • another part knows what to do about it

32
Base Exception Classes
  • SystemException
  • also known as runtime exceptions
  • typically caused by programmer errors
  • ApplicationException
  • application programs derive new exception types
    from this class
  • IOException
  • caused by file and stream I/O errors

33
Integer Conversion Example
  • User inputs an integer into a TextBox
  • Calls Convert.ToInt32
  • which throws a System.FormatException

34
IOException Class Hierarchy
35
Try...Catch...Finally Statement
  • Syntax
  • Try
  • try-block
  • Catch optional filters
  • catch-block
  • additional Catch blocks...
  • Finally
  • finally-block
  • End Try

Optional
36
Alternate Execution Paths
The Finally block is optional
37
Integer Conversion Example
  • Handles exception thrown by ToInt32 method
  • Try
  • Dim n As Integer
  • n Convert.ToInt32(txtInput.Text)
  • stsMessage.Text "OK"
  • Catch
  • stsMessage.Text "That's not an Integer!"
  • End Try

38
Averaging Test Scores
  • Hands-on example
  • User inputs a series of test scores
  • Program calculates average
  • handles exceptions, identifies invalid score
  • Error message example

39
Handling File Exceptions
  • Hands-on example
  • User enters a file name
  • Operations
  • program attempts to read the file
  • program attempts to write to the file
  • throws exceptions

40
Propagating Exceptions
  • Happens when exception is not caught immediately
  • Exception chains backward through method calls
  • Becomes unhandled if no Catch clause is found

41
Business Tier
  • Throw exceptions at this level
  • Catch exceptions at this level
  • Do not generate any output to the user
  • let the Interface layer do that

42
Designing Your Own Exception Types
  • Do this when...
  • your exception needs to hold custom information
  • exception class name is self-documenting
  • Inherit from ApplicationException
  • Example
  • Public Class PropertyException
  • Inherits System.ApplicationException
  • Private mBadValue As String
  • Sub New(ByVal message As String, _
  • ByVal badVal As String)...
  • Public ReadOnly Property BadValue() As String...

43
Testing PropertyException
  • Hands-on example
  • User inputs property values, which are assigned
    to a Student object.
  • Exceptions caught
  • PropertyException
  • InvalidCastException

44
Exception-Handling Tips
  • Prevent exceptions before they are thrown
  • Entire Try block might not execute
  • Catch specific exceptions first, catch general
    exceptions last
  • Throw predefined .NET exceptions when possible
  • Your exception classes should inherit from
    ApplicationException

45
The End
Write a Comment
User Comments (0)
About PowerShow.com