Coding 20of 20Windows 20Forms
Document Sample


Coding of Windows Forms
Applications, and the Transition to
Objects
Objectives
• Understand the basic concepts involved in object-
oriented programming (OOP)
• Understand the meaning of the .NET Framework
• Understand the elements of coding in Visual Basic .NET
• Develop a detailed plan for converting a prototype into a
production application
• Add a MainMenu control
• Add a DateTimePicker control
• Add sequential file output to an application
• Add printed output to an application
• Add help instructions
Understanding Object-Oriented
Programming
• Object
– Any named set of data structures and underlying code
• Visual Basic .NET
– An object-oriented language, designed with and for object-
oriented programming (OOP)
• Properties
– Descriptors of the object
• Methods
– Actions that the object could perform
• Events
– Occurrences external to the object, but to which the object could
respond
Understanding Object-Oriented
Programming (Continued)
• Understanding Objects
– Advantages of programming with objects
• Once created, can be reused
• You do not need to refer to all of its components in order to use it
• Understanding Encapsulation and Information Hiding
– Encapsulation
• Object exposes to the outside world only those elements of its structure and
operations needed by itself or by the outside world to deal with the object
– Information hiding
• Programming language performs much of its lower-level, detail work out of
sight and without programmer’s direct awareness
– Implementation
• Encapsulated, internal data and code of an object
– Interface
• Consists of all aspects of the object accessible to the outside world
Understanding Classes
• Class
– Template for the creation of an object
• Instantiation
– Process of creating an object from a class
• Base class
– Original class
• Derived class
– Class created from base class
Understanding Class Members
• Class members
– Elements or components that make up a class and
that can be seen by the programmer
• Class member types
– Constructors
– Properties
– Methods
– Events
– Fields
– Other objects
Understanding Accessibility
(Access Type)
• Visual Basic .NET supports five levels of accessibility:
– Public
• Entities have no access restrictions
– Private
• Entities are accessible only within the context in which they are
declared
– Protected
• Limits access to the class in which it is declared and to any derived
class
– Friend
• Limits access to the program in which the entity is declared
– Protected Friend
• Provides access to the union of protected access plus friend access
Understanding Scope, Object References,
Shared Members, and Qualified Names
• Scope of an entity
– Portion of code in which the entity is available (accessible) and in which the
programmer can reference the name of the entity without qualification
• Block scope
– Describes a program element available only within the block in which it is
declared
• Procedure scope
– Describes a variable that is declared inside a procedure, but not inside a block
within that procedure, thus making the variable available throughout the
procedure
• Module scope
– Describes an entity that is available throughout the module, class, or structure in
which it is declared
• Namespace scope
– Describes an entity that is available throughout the namespace in which it is
declared
Polymorphism and the Advantages of
Object Oriented Programming (OOP)
• Polymorphism
– The ability of a derived class to alter (override) a property or
method from its base class
• Advantages of OOP
– Objects are reusable
– Any object in your application can be treated as a new base
class and can instantiate other new objects
Introducing the .NET Framework
• Common Language Runtime (CLR)
– Manages code execution at runtime
– Provides services needed by all languages, such as
• Memory management, garbage collection
• Thread management, type safety, and code security
• .NET Framework Class Library
– Collection of over 6000 reusable types, classes, and interfaces
– Entities are grouped into a hierarchical set of namespaces
– System namespaces
• Define commonly used entities that are used by developers in any
language
– Microsoft namespaces
• Language-specific
– Assemblies
• Dynamic link library (.dll) files
Coding Windows Forms Applications in
Visual Basic .NET (Continued)
• Understanding the Structure statement
– Declares a user-defined data structure, consisting of
one or more elements
– Keyword Structure replaces the keyword Type
Declaration of Public Structure Seat
Exploring Structure Variables and Arrays
• Dim pastructSeat(935) As Seat (line 87)
– Creates an array of 936 elements (instances) of type Seat
• Index values of array elements in Visual Basic .NET
– Always begin with 0 and end with the declared upper bound
• Only methods automatically defined for a structure
– Assignment and input/output to a random data file
• Integers declared inside the structure
– Constitute the properties, or attributes, of the class
Understanding Hashing Application
Logic and Coding
• Friendsville International Village
– Has five dining halls, with 17 dining tables in each, and 11 seats
at each table
– Dining hall can hold 935 guests at one sitting (5 * 17 * 11)
– Objective is to randomly assign the 935 seats
• Hashing program
– Randomly selects a number from 1 to 935 and assigns it to each
element of a 935 element array
– Algorithm ensures that no randomly selected number is used
more than once
To Run and Examine the Hashing
Application
1. If necessary, start Visual Studio .NET, and open the
Hashing solution in the
VB.NET\Student\Tut02\Hashing folder
2. Click the Start button to run the program. Click
Button1 to generate the random seat assignments
3. Click Button1 again, and note that the seats are
assigned in a different order, but ListBox2 is still empty.
In fact, click Button1 as often as you like
4. Exit the running application, returning you to the IDE
Adding a MainMenu Control (Task 01)
• To add a MainMenu control:
1. If necessary, click the frmDining.vb [Design] tab at the top of the main window to
display the Windows Form Designer. In the Toolbox, click the MainMenu control,
and drag it onto the form
2. On the form’s menu bar, click Type Here, type &File, and then press Enter
3. In the Type Here box under File, type &Save Seats in File. Press Enter
4. In the same fashion, insert one item for the Tools menu and two items for the Help
menu
5. On the File menu, click Save Seats in File
6. To insert a separator bar, right-click Exit, and click Insert Separator
7. Change the internal name of each menu item to a meaningful name by clicking File
8. Replace the default names in the Tools and Help menus in similar fashion
9. Double-click the Exit menu item
10. Click the Start button to run the MyDining application
Adding a DateTimePicker Control
(Task 02)
• To add a DateTimePicker control:
1. In Form Designer, drag the DateTimePicker control from the
Toolbox onto the form, and place it and size it appropriately
2. Run the newly created MyDining application to see that it
works. Click the drop-down arrow to display a calendar, click
a date, and note that your selected date appears in the control
3. Click File and then click Exit to close the application and return
to the IDE
Navigating Lines of Code
• The Windows Form Designer
– Generated code should be collapsed
• To find an existing procedure
– Press Ctrl+F (the Find key), type the procedure name, and press
Enter
• Find operation
– Used to find a variable or constant or any other segment of code
• To create an event procedure that does not already exist
– Select the object that triggers the event from the Class Name
combo box at the top left of the Code Editor
– Select the event from the Method Name combo box at the top
right of the Code Editor
Navigating Lines of Code (Continued)
• Another way to create or navigate to an existing event
procedure
– Doubleclick the control that triggers the event in the Form
Designer
• To create a user-defined procedure or function
– Place the insertion point on a blank line outside any existing
procedure or function but before the End Class statement (the
last line of code in a form)
– Type your own procedure header
To Move the Code from Button1_Click to
mnuToolsAssignSeats
1. Select all of the code within the Button1_Click procedure. Do not include
the header Private Sub Button1_Click(...) or the End Sub in the selection
2. Press Shift+Delete. This deletes the code from the Button1_Click
procedure and places that code on the Windows Clipboard
3. In the Object combo box at the top left, click mnuToolsAssignSeats
4. In the Event combo box at the top right, select Click
5. Press Shift+Insert. This inserts the code from the Windows Clipboard
6. Run the MyDining program again, click Tools | Assign Seats to see the
seat assignments, and click File | Exit
Deleting Unnecessary Items (Task 05)
• To delete unnecessary items:
1. In the Form Designer, delete ListBox2
2. In the Code Editor, in the mnuToolsAssignSeats_Click procedure, use the Find
operation (by pressing Ctrl+F) to locate and then delete the lines involving
AssignedNum
3. In the Code Editor, in the mnuToolsAssignSeats_Click procedure, delete the entire
section of code involving the search for duplicates
4. Use the Find operation to locate Structure structSeat, and delete the declaration
for DupeNum
5. Use the Find operation to locate the Button1_Click procedure, and delete this
procedure
6. Switch to the Form Designer by clicking the frmDining.vb[Design]* tab, click
Button1 in the Form Designer, and press Delete
7. Run the MyDining program again, click Tools | Assign Seats to see the seat
assignments, and then click File | Exit
Generating a Unique Seat Assignment
List for Each Date (Task 06)
• To generate a unique seat assignment list for each date:
1. Navigate to the mnuToolsAssignSeats_Click procedure; insert Rnd(-
DatePart(DateInterval.DayOfYear, DateTimePicker1. _ Value))
2. Insert the following statement immediately after the statement you
entered in the preceding step: lstSeats.Items.Clear()
3. Insert the following line of code in the DateTimePicker1_TextChanged
event procedure: lstSeats.Items.Clear()
4. Run the MyDining program again. Click Tools | Assign Seats to see
the seat assignments. Change the date in the DateTimePicker control,
click Tools | Assign Seats again. Click File | Exit
Converting House, Table, and Seat Numbers to
Meaningful Names (Task 07)
• First task
– Convert a house number from 0 to 4 into the name of
the house (North, South, East, West, or Harmony)
• Techniques
– Brute force
– Create a string array containing the string values of
House names corresponding to the integers 0
through 4
– Use a Select Case structure
Declaration of structSeat
Fixing the Formatting of the List Box
(Task 08)
• To format list box items:
1. In the Form Designer, change the Font property of lstSeats to
Courier New, if necessary
2. strSeat was constructed in Task 07, but was not properly
formatted. Modify the format of strSeat by formatting each of its
seven concatenated string elements
3. Insert the resulting code, replacing the original formatting
instruction
4. Run the MyDining program again. Click Tools | Assign Seats
to see the seat assignments and see how nicely the output is
displayed. Click File | Exit
Adding Sequential File Output (Task 09)
• Task
– Dining Hall Seat Assigner program must be able to
send a list of seat assignments to an output
sequential file
– Three parts
• Construct a fixed-length string representing the date for seat
assignments.
• Provide a standard Save File As dialog box, for the user to
select the file location and either accept or modify the
proffered filename
• Open the output file, write the contents of lstSeats to that
file, and close the file
Assigning Properties and Displaying
SaveFileDialog1
Adding Printed Output (Task 10)
• To add printed output:
1. In Form Designer, drag the PrintDocument, PageSetupDialog, PrintDialog,
and PrintPreviewDialog controls from the Toolbox and drop them onto the form
2. In the Properties list, set the Document property of the PageSetupDialog,
PrintDialog, and PrintPreviewDialog controls to PrintDocument1
3. In the Code Editor, add a module-level integer variable to point to the next item
in lstSeats
4. The main printing logic occurs in the PrintDocument1_PrintPage() procedure
5. To call the PrintPage event procedure, the user clicks the Print icon in
PrintPreview
6. To activate the PageSetupDialog control, insert the following code into
mnuFilePageSetup_Click: PageSetupDialog1.ShowDialog()
7. To activate the PrintDialog control (for setting up printers), insert the following
code into mnuFilePrinterSetup_Click: PrintDialog1.ShowDialog()
8. Run the MyDining program
Adding Instructions (Task 11)
• To add instructions for the use of the
application:
1. In Form Designer, double-click mnuHelpInstructions to
open the Code Editor for this menu item, or open it using
the Class Name and Method Name combo boxes
1. Run the MyDining program to ensure that the Help system
works. Click Help | Instructions
1. Click File | Exit to return to the IDE
Summary
• Visual Basic .NET
– An object-oriented language
• Advantage of OOP
– Software reuse
• Visual Studio .NET Framework
– Provides numerous namespaces and classes to serve as the foundation
for programs
• Encapsulation
– Achieved through limitations on accessibility and scope
• Variable arrays
– Declared with an upper bound
• User-defined data types in Visual Basic .NET
– Declared with the Structure statement at the module level
– Public by default
Summary (Continued)
• Prototype application converted to a production application by
– Adding missing or incomplete elements
– Applying organizational programming standards and style guidelines
• Task List
– Can assist in managing programmer work effort
• MainMenu control provides
– Menu items
– Click events immediately accessible to the programmer
• DateTimePicker control
– Provides a robust date selection facility
• Initializing Rnd() with a negative random number seed
– Results in a consistent sequence of random numbers for any given
seed
• Visual Basic .NET
– Offers functions for manipulation and parsing of dates
Summary (Continued)
• SaveFileDialog control
– Provides a standard Windows Save File dialog box
• FileOpen(), WriteLine(), and FileClose() functions
– Support sequential file output operations
• Left(), Right(), and Day() functions
– Must be qualified with the Microsoft.VisualBasic namespace
• Controls that support printed output
– PrintDocument component
– PrintPreviewDialog
– PageSetupDialog
– PrintDialog
Get documents about "