Table of Contents
Advanced Business Programming with C# 2005 byDonald L. Voils Electronic & Database Publishing, Inc. 2007 (1675 pages) ISBN:9780979359101
With particular emphasis placed upon the creation of GUI business programs, this introductory guide covers the writing of business programs using C# from Microsoft Visual Studio .NET 2005.
Table of Contents Advanced Business Programming with C# 2005 Preface Lecture 1 - Introduction to Business Programming Lecture 2 - C# Language Fundamentals Lecture 3
- Methods in C#, Text File I/O and Structures
Lecture 4
- Classes in C#
Lecture 5
- Class Extensions and Polymorphism
Lecture 6
- Operator Overloading
Lecture 7
- Interfaces
Lecture 8
- Arrays and Collections
Lecture 9 - String, String Builder, Char and Regex Classes Lecture 10 - Handling Exceptions Lecture 11 - Generics in C# Lecture 12 - Delegates and Events Lecture 13 - Building Windows Applications and Event Driven Programming Lecture 14 - File Input/Output and Object Serialization Lecture 15 - Accessing Data with ADO.NET List of Tables
file:///D|/1/final/toc.html [01.12.2007 04:47:30]
Back Cover
Back Cover Lecture Objectives: This electronic book presents lectures that may be used in a college or university semester class dealing with the writing of business programs using C# from Microsoft Visual Studio . NET 2005. The major programming emphasis is upon the creation of GUI business programs. Prerequisite requirements: These lectures assume that the student already has taken business courses including accounting. Since this is an advanced business programming course, it is assumed that the student has experience in programming business applications using the C++ programming language.
file:///D|/1/final/backcover.html [01.12.2007 04:47:31]
Advanced Business Programming with C# 2005
Advanced Business Programming with C# 2005 By Donald L. Voils Business revolves around the world and computers make it happen. Copyright © 2007 Don Voils ISBN-13 978-0-9793591-0-1 ISBN-10 0-9793591-0-4 Published by: White Feather Publishing 12524 Shoreline Line Drive Suite 301 Wellington, Florida USA 33414 There are examples included in each lecture. However if you would like separate copies of the examples, the graphics, the Excel spreadsheets or the Access databases used in some of the exercises, email: dvoils@adelphia. net for shipping and handling costs. Dedication These lectures are dedicated to the many students from all over the world who have studied these lectures and the many other lectures that I have written. These lectures are also dedicated to my wife Connie without whose unending support none of this would have been possible. Finally I would like to dedicate these lectures to those of my ancestors who were here in the USA prior to the immigration of the many peoples from all over the world. May the Great Spirit watch over you as long as the grass grows and the river flows. Pawnee Proverb
file:///D|/1/final/BBL0001.html [01.12.2007 04:47:31]
Preface
Preface Lecture Objectives: This electronic book presents lectures that may be used in a college or university semester class dealing with the writing of business programs using C# from Microsoft Visual Studio .NET 2005. The major programming emphasis is upon the creation of GUI business programs. Prerequisite requirements: These lectures assume that the student already has taken business courses including accounting. Since this is an advanced business programming course, it is assumed that the student has experience in programming business applications using the C++ programming language. In addition the student should be familiar with the following programming concepts: ●
●
Structure programming: ❍
Sequence,
❍
Selection
❍
Repetition
❍
Modularization.
Object oriented programming ❍
Encapsulation
❍
Polymorphism
❍
Inheritance
Software requirements: Since these lectures are based upon Visual Studio .NET 2005, it is assumed that the student has access to this software. In addition UML charts will be used and therefore it is assumed that the student has access to Microsoft Visio 2003 Professional or a similar program. The lecture notes: When using these lecture notes, you must have access to an Internet browser that in addition has access to Adobe Acrobat 7.0 or higher. The lecture notes contain links to the C# examples. When viewing the notes, you should have open Visual Studio .NET 2005 in addition to the browser. Visual Studio .NET should be set up and ready to compile and run a C# program. (How to do this will be illustrated later in the lecture notes.) Look at each example very closely to ensure that you understand what the example is attempting to show. Using Select in Adobe Acrobat, copy the program to the Clipboard. After the code has been copied to memory, click on Visual Studio .NET into the current project. Next, click on Ctrl-A followed by Ctrl-V (which pastes the copied code into Visual Studio .NET). When using a console example, the project must be set up to be a console project. When using a Windows example, the project must be set up to be a Windows project. Note: In Visual Studio .NET 2003 Windows projects were only one file. However in Visual Studio .NET 2005, Windows project are three or more files so steps must be taken to take advantage of this fact especially when using the examples listed in each lecture. Some of the examples that are included in the book are one file Windows programs written in Visual Studio .NET 2003. If a console project is created, then the Windows sample can be copied into the project. Note: Some of the examples use Excel spreadsheets, some use graphics while others use Access databases. These samples are not included in this book. If you would like these samples, email:
[email protected]. Note: These lectures are menu driven using Adobe Acrobat bookmarks. It is therefore possible to link from the Table of Contents below to a particular lecture and back. Then within each lecture, it is possible to link to a subsection of that lecture and to the many examples that are added to the end of each lecture. Further, it is possible to link from one lecture to the next lecture.
file:///D|/1/final/BBL0002.html (1 von 2) [01.12.2007 04:47:32]
Preface
file:///D|/1/final/BBL0002.html (2 von 2) [01.12.2007 04:47:32]
Lecture 1: Introduction to Business Programming
Lecture 1: Introduction to Business Programming The Study of the Use of Computers The study of the use of computers has changed significantly over the last twenty five years while I have been working in this field. At first this field of study was mainly devoted to the use of computers to solve business problems. Most of the books and research papers published in the early years were written to serve that use of computers. However during the last ten years, there has been an increased use of computers to solve non business problems. For example a larger and larger amount of time is being devoted to the study of the Internet not only for business but for non business purposes as well. There is becoming an increased use of cell phones and devices like PDAs and electronic devices embedded in machinery like cars which require programming as well. There has been an increased use of computers in the area of graphics, gaming, music, video and for other personal entertainment devices. The field of computer science at some colleges and universities has therefore split into several different approaches to the study of computers specifically: business and non business. The study of the business use of computers can now frequently be found in the School or College of Business. This area of computer science is sometimes called Management Information Systems (MIS) or Computer Information Systems (CIS). Other names are sometimes used to describe this field of study. The study of the non business use of computers can now frequently be found in a separate Department of Computer Science. This CS department is sometimes in the College of Engineering or is sometimes included in the Mathematics Department. The topics studied under this arrangement might include: communications, multimedia, data bases, computer security, software quality assurance, programming languages, operating systems, computer networking and many other topics. The languages used for these courses have varied from machine language to COBOL, Fortran, Pascal, C, C++, Java and now C#. The language C supports structured programming. C++ extended C and the concepts of structured programming to include object oriented programming (OOP). C# extends beyond these styles by adding component oriented and event driven programming using a graphic user interface (GUI). In addition C# adds the ability to easily access database data and to create Internet programs. This course will begin with an introduction to the structured programming and the component oriented side of C#. Next the OOP side will be introduced. This will be followed with the event driven program and then database access. These lectures will not consider C# programming for the Internet. This course is not meant to be an extensive study of program design and development. This course is only an introduction to the subject. If you continue your formal study of business programming, you should take additional courses on this subject. What should be done after taking this class is to take a courses in SRS (Software Requirements Specification), OOA (Object Oriented Analysis), OOD (Object Oriented Design), OOP (Object Oriented Programming), Software Testing, SQA (Software Quality Assurance), Software Security, programming for a network environment and to study Java and C# more in depth. These online course notes are meant to complement any other required texts and to hopefully add materials that will be helpful to the MIS major. The design discussed in the online notes will include more of a discussion of UML (Unified Modeling Language) than you will find in some texts. Since the field of MIS changes so rapidly, you will need throughout your career to continue your education in the field yearly in order to keep up and in order to keep your job. For example, the previous edition of this text dealt with C# 2003. These lectures deal with C# 2005. It is expected that Microsoft will introduce another version shortly: C# 2007.
file:///D|/1/final/BBL0003.html [01.12.2007 04:47:32]
What is Programming?
What is Programming? As a new programmer, it is important for you to: ●
Know that programming is an art which training can improve upon but that you can not become a programmer unless programming is an art that you were given as a human being.
●
Know the company you work for and the internal politics which is as important as the computer concept that you will use.
●
Know and to be able to converse with the business clients, the users and other stakeholders for whom the program is being developed.
●
Know the field for which the program is going to be developed.
●
Know that software is: ❍
a computer program (i.e. code)
❍
the procedures for using the code
❍
❍
the documentation which describes the reasons for creating it, describes the code, and describes how to use it. data to run the code on to test all possibilities
But what is most important for you is the need to: "Know thyself" and you need to ask yourself ●
How do I approach problems?
●
How do I work with others?
●
Which of the 5 phases of software life cycle that will be discussed below do I enjoy most and which do I do well in?
file:///D|/1/final/BBL0004.html [01.12.2007 04:47:33]
The 5 Phases of Software Life Cycle (SLC)
The 5 Phases of Software Life Cycle (SLC) 1. Problem Analysis and Specification Phase (Software Requirements Specifications) 2. Design Phase (Software Design) 3. Coding Phase (Implementation of Design) 4. Testing, Execution and Debugging Phase (Software Testing) 5. Maintenance Phase (Software Maintenance) Note: The approach to software life cycle listed above is sometimes referred to as the "waterfall" approach where one phase follows immediately after the other. Note: Each of these phases produces documents. As the project progresses, these documents will have to be written and then rewritten. Some believe that documentation is so important that when discussing the 5-phases a sixth phase should be added: the documentation phase. Note: Errors in the software system can be created in any one of the 5-phases. Some of the causes of these errors are: ●
faulty system's analysis
●
communication errors between the stakeholders and the developers
●
feature "fluff" where the stakeholders request features that are not needed
●
deliberate deviation from the specifications by the computer system's staff
●
logical design errors
●
coding errors
●
non-compliance with the specifications
●
incomplete and inaccurate testing
●
procedure errors
●
documentation errors
●
errors caused by insufficient time and money devoted to each phase
Note: In a large corporation's information technology dealing with a large project, the specification phase could take 2 months, the design phase could take 4 months, the coding phase could take 3 months and the testing phase could take 3 months. This would be followed with user training that might take 1 month. The maintenance phase starts this process all over so you can see that software development can take a long time and in fact never end. Some projects can take years to complete. In fact some projects can take so long that the reason to begin the project is no longer important and the project is canceled. Note: Although not discussed during this course, a user's manual should be created. Its construction should begin during the first phase and should continue until after the project is completed. Note: Although not discussed in this course, part of the phases should be a training phase both of those who are to create the program as well as those who will use it. In addition some testing should be conducted in each phase
file:///D|/1/final/BBL0005.html (1 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
with the major testing taking place during the Testing Phase. The quality assurance should continue throughout the project. Note: In a software development and maintenance organization, the different types of positions available can be: ●
Software or Systems Quality Assurance Engineer
●
Software or Systems Analysts
●
Software or Systems Designer
●
Programmer
●
Software Tester
●
Software Maintenance Technician
●
Systems Security Engineer
●
and team leaders for each of these groups.
Try to determine which of these positions best meets your qualifications and professional goals. Note: Some new terms have been added that better describe how the SLC is implemented. These terms are: White Box SLC, Grey Box SLC and Black Box SLC. By these terms the following is meant: ●
White Box SLC means that all of the phases of the SLC are done by the IT employees of the company for whom the system is being developed.
●
By Grey Box SLC is meant that some of the phases or parts of a phase are done internally by the IT employees of the company for whom the system is being developed while other phases or parts of these phases are out sourced to other companies like the Coding Phase or the Testing Phase.
●
By Black Box SLC is meant that most if not all of the phases are performed by one or more outside IT companies. While almost the entire project is out sourced, the company's employees may participate somewhat by providing necessary information for the out sourced contractors.
Problem Analysis and Specification Phase In this phase the analyst, the security and the quality assurance engineers attempt to do each of the following and to create software requirements specification documents that address these issues: ●
Obtain a formal statement of the software requirements.
●
Obtain copies of the major reference documents.
●
Determine what platform the final project will run on and what computer language as well as what version of the language the project must be written in.
●
Determine who the users and other stakeholders will be, what type of User Interface (UI) will be required and how often the program will be used.
●
Determine what level of fault tolerance and security will be required and whether the final project will be open to judification in a court of law.
●
Develop benchmarks that will be used to evaluate the final system.
●
Collect sufficient data to be used for testing through the entire project during each of the phases as well as in the Testing Phase.
●
Ask questions of the users, those in management and other stakeholders who will monitor the project to ensure
file:///D|/1/final/BBL0005.html (2 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
that what is truly being requested is understood. ●
Determine whether the specifications must be written in the design phase using one of the formal methods like: Z, VDM, Larch, UML or some other design methodology and if so then the specifications must be written to support that methodology.
●
Write descriptions of the input and output and then show it to the client, the users and other stakeholders for their verification.
●
Write and then rewrite the system specifications as they become better known.
●
Ask the client, the users and other stakeholders after each rewrite whether the newly written specifications are closer to what the real needs are.
●
Ask the clients, the users and other stakeholders whether their stated specifications are a real requirement or whether some of it is "fluff" i.e. something that would just be nice to have.
To be a good analyst you need to have: ●
analytical skills
●
technical skills
●
managerial skills
●
interpersonal and communications skills as the most important skills that are needed
At the end of this course, you need to ask yourself: ●
Do I want to do Problem Analysis and Specification? If you do, then you need to study OOA in more depth and seek to become certified as a Business Analyst.
●
Do I have the necessary skills to be successful doing this phase?
Note: During this course you will prepare a specification document for each programming homework but you will not be required to act as a systems analyst. Note: This phase is sometimes referred to as the System Requirements Specification (SRS) phase. Part of this phase can include an analysis process called: Object Oriented Analysis (OOA) and System Security Specification. Note: As part of the SRS should be a determination and documentation of the training needs of the system users in order to increase the possibility of a successful project. Note: It is recommended that you read the following book: Wiegers, Karl; Software Requirements 2nd Edition; Microsoft Press; Redmond, WA 2003; ISBN 0-7356-1879-8
Design Phase In this phase sometimes be called Object Oriented Design (OOD), the programmer attempts to: ●
Identify the objects in the problem's specification and their data types to identify the data structures and then to create graphics and charts that describe these data structures.
●
Identify the multiple modules needed to solve the problem and then to create a graphical representation that describes the relationships between these modules.
●
Identify the User Interface components (there may be more than one i.e. a customer UI v.s. an employee UI) and design how each of these UIs will appear.
file:///D|/1/final/BBL0005.html (3 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
●
Identify the security components that will be required.
●
Create for each module an algorithm (that is a sequence of steps), that when applied in the programming language, will solve a particular part of the problem.
●
Develop the algorithms so that they are:
●
❍
Definite and unambiguous
❍
Simple
❍
Finite
But most importantly understand that the design should create a program that is well structured and where: ❍
●
program = algorithms + data structures
Develop the design using the Design Tools
At the end of this course, ask yourself: ●
Do I want to do Design? If so, then you should take additional courses in OOD.
●
Do I like to analyze things in their smallest details? If so, then you should study OOA.
●
Do I like to write descriptions of these minute details, to draw pictures of these tiny details and then to describe what I see to others?
●
Do I have the people skills to do the design phase?
Note: The need to off shore programming may decrease in the future because several companies are offering tools that take the designs that are created in UML 2.0+ and converting these design documents into C++ or C# programs as will be demonstrated later when UML charts in Visual Studio .NET 2005 will be used to write the definitions of classes. It is also possible with tools like these to convert C++ or C# program into UML design documents as will be seen later when Visual Studio .NET 2005 is used to convert class definitions into UML documents.
Design Tools Some of the design tools: ●
Abstract Data Type Description (a collection of standardized symbols like UML that illustrate the overall relationships between the major pieces of the program including the data)
●
Human Interface (a collection of sample or potential screens and reports that shows what the user will see.)
●
System Flowcharts (a collection of standardized symbols that illustrate the relationships between all of the programs in the system)
●
Structure Chart (a collection of standardized symbols that illustrate the overall relationships between the major pieces of the program to include the movement of data between the individual modules if any)
●
Flowchart (a collection of standardized symbols that express the logic flow of a program.)
●
Pseudo Code (a mixture of natural language (not necessarily English), terms, symbols and other features commonly used in one or more high-level languages that express the logic flow of a program.
Abstract Data Type Description These descriptions could include data type descriptions using UML data charts like the following: file:///D|/1/final/BBL0005.html (4 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
CustomerRecord -firstName -lastName -accountNumber -currentBalance +addCustomer( ) +modifyCustomer () +changeBalance( ) …
TransactionRecord -accountNumber -transactionAmount -accountType +addTransaction( ) +modifyTransaction () …
Human Interface This may include reports like the following: Southern Warehousing Monthly Accounts Open table as spreadsheet Customer Name
Account Number
Starting Balance
Customer One
1111111
XXXX.XX
XXX.XX
Customer Two
2222222
XXXX.XX
XXXX.XX
Customer Three
3333333
XXXX.XX
XXXX.XX
....
....
....
Totals
Ending Balance
.... $XXXXX.XX
$XXXXX.XX
System Flowchart System flowcharts show the interrelationship between different parts of the total system and the program being written:
file:///D|/1/final/BBL0005.html (5 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
Structure Chart A structure chart shows the modules of the program being written and their relationships and in some cases the movement of data between the modules:
Flowchart Flowcharts show the modules and their interrelationships, the program's logic and the variable names.
file:///D|/1/final/BBL0005.html (6 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
Pseudo-Code Pseudo code show the modules their interrelationships, the programs logic and the variable names but it does this using words: START PROCESS Initialization PROCESS Report Heading Read fname, lname, accout_no, start_balance, transaction_type DOWHILE(More Records) PROCESS Detail Record Read fname, lname, accout_no, start_balance, transaction_type ENDDO PROCESS Report Totals END Initialization total_previous = 0.00 total_current = 0.00 Return
file:///D|/1/final/BBL0005.html (7 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
Report Heading Display Company Name, Report Name, Column Headers Return Detail Line Display name, account_no, start_balance, end_balance Return Case 'D' total_previous = total_previous + start_balance end_balance = start_balance + transaction total_current = total_current + end_balance Return Case 'W' total_previous = total_previous + start_balance end_balance = start_balance - transaction total_current = total_current + end_balance Return Invalid Case Display Error Message Return Detail Record CASEENTRY Opcode CASE 'D' PROCESS Case 'D' CASE 'W' PROCESS Case 'W' Case other PROCESS Invalid Case ENDCASE PROCESS Detail Line Return Report Totals Display total_previous, total_current Return
Coding Phase (Implementation of the Design) In this phase the programmer: ●
Encodes the program modules into the previously selected language and version that was selected in the Specification Phase using the data types, the logic, the modular design, the security issues and the variable names selected in the Design Phase.
●
While creating the modules, writes the code in a: Well structured, documented and stylistic manner
●
Combines the program modules into a complete software system.
●
Ensures the program quality and that the code is correct, readable and understandable by reading the code in each module and in the combined program.
●
Hand verifies the logical correctness and the integration of the various parts of the program by using the sample data generated in the Specification Phase.
file:///D|/1/final/BBL0005.html (8 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC) ●
Translates the program from the source code into machine code using the selected language's compiler to determine if there are any syntax or warning errors.
At the end of the course, ask yourself: ●
Do I want to do Implementation of the Design phase (i.e. do you want to do the Coding Phase? If you do, then you should study OOP.
Well-Structured, Documented and Stylistic Programs The code needs to satisfy the following criteria (This list is sometimes referred to as the developer's requirements to distinguish it from the program requirements): ●
The program should have opening comments.
●
Each module should be documented like the program with opening comments.
●
There should be internal comments that explain each key section of the program and each module.
●
Each module and each variable should use meaningful names. If the name is one word, then it should be in lower case. If a name contains more than one word, then the first word should be in lower case and the first letter of the remaining words should be in upper case while the other letters in these words should be in lower case.
●
The documentation of the program and of each module should be formatted in a style that enhances its readability by meeting the following criteria: ❍
Each program statement should be on a separate line.
❍
Upper and lower case should be used in a way that enhances readability.
❍
❍
❍
The placement of each { symbol and its corresponding } should be listed on separate lines from the other code and listed in the program so that they are vertically aligned. There should be an indentation of the lines that are enclosed within a { and its corresponding } The indentation of statements that are more than one line should be written so that after the first line they are indented more with respect to the first line.
❍
There should be vertical alignment of the names of the variables when they are defined.
❍
There should be blank lines inserted between definitions, declarations, statements, and blocks of code.
❍
❍
❍
The placement of the definitions and declarations of variables should be near the top of the section where they are first used. There should be a separation of the operators from their operands by spaces. The output should be labeled so that the user understands what they are being asked or what they are viewing
Testing, Execution and Debugging Phase This phase is sometimes referred to as the Software Quality Assurance (SQA) phase. By Software Quality Assurance is meant: ●
A systematic, planned set of actions necessary to provide adequate confidence that the software development process or the maintenance process of a software system product conforms to established functional technical requirements as well as with the managerial requirements of keeping the schedule and operating within the budgetary confines.
file:///D|/1/final/BBL0005.html (9 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
In this phase the programmer or the Software Quality Assurance (SQA) staff checks each of the following: ●
Checks for Validation. That is the SQA staff tries to answer the question: "Are we building the correct product?" To do this the QA staff needs to check that the documents, the program modules, etc. to see if they match the requirements of the users and other stakeholders.
●
Checks for Verification. That is SQA staff tries to answer the question: "Are we building the product correctly?" To do this SQA staff needs to check that the product is correct and complete as well as whether the parts are consistent with each other and whether they are consistent with the documents of the preceding phases.
In addition to testing during the Testing Phase, the SQA staff is aware that errors may occur in any of the phases and therefore they test each phase. The SQA staff is aware that errors may occur for various reasons to include: ●
Software Requirements Specifications don't accurately reflect given information or the user's and other stakeholder's needs/requests
●
Logic errors in algorithms
●
Incorrect coding or integration
●
Failure to handle boundary data or test values
The SQA staff knows that there are different kinds of testing types which are required and uses them where appropriate. The SQA staff knows that no matter how much they test the program, there will still be bugs and they strive to keep the number of errors within acceptable limits At the end of the course, ask yourself: ●
Do I want to do Testing, Execution and Debugging? If so, then you may become a member of the Software Quality Assurance or Software Testing group.
●
Do I have the skills to be successful in this area? If so, then you may want to take additional courses in software testing and software quality assurance. In addition you might want to consider becoming a Certified Software Quality Assurance Engineer.
Note: The quality assurance staff might want to consider the purchase of one of the many testing software programs to support the testing process. Note: Testing done by the coding team may not yield quality testing because of their involvement in creating the code. In addition there may also be problems when the testing is conducted by members of the same company as the coding team. Sometimes it is necessary to contract with an outside testing company in order to gain quality testing. Note: One of the major causes of programs not passing the testing process is that the project had difficulty meeting SRS deadlines and staying within budget. Note: One of the problems may be that the program passes the testing phase yet did not meet the SRS. In fact testing may determine that there is a need for recoding of the program and maybe even determine that there needs to be a completely new SRS. Note: This discussion of SQA may seem to imply that software quality assurance does not begin until after the coding has been completed. What should be noted is that, the testing may need to begin as soon as the SRS has been accomplished or even as part of the SRS. Note: The SQA budget may be as much as 20% – 30% of the total cost of the program. It may be determined when considering the costs that the SQA should be handled by an outside SQA firm.
file:///D|/1/final/BBL0005.html (10 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
Note: I recommend that you read the following book: Galin, Daniel; Software Quality Assurance; Pearson Education; London, England; 2004; ISBN 0-201-70945-7
Testing Types Testing consists of many different types of tests to include: ●
Unit tests that include: ❍
●
●
❍
Testing the program components in isolation
❍
Verification that each individual program unit works as designed
❍
Testing for errors to include: syntax errors
■
warning errors
■
linking errors
■
run-time errors
■
logical errors
■
system and data security leaks
❍
Testing that determines if the units combine correctly
❍
Testing the component interfaces and information flow
❍
Testing that determines whether the data moves correctly from one unit to another
System tests that include: Testing that determines whether the overall system is working correctly
Black box (or functional) tests that include: ❍
❍
❍
●
■
Integration tests that include:
❍
●
The most rigorous and time intensive part of the testing and is the most fundamental and the most important
Testing that determines whether the set of test data works. Testing of the output produced for various inputs for correctness without considering the structure of the program component itself. Testing a program unit as if it is a black box that accepts inputs and produces outputs, but ignores the inner workings of the box.
White box (or structural also called glass-box because the tester looks inside of the program components) tests include: ❍
Testing of specific sections of the program to determine if each section is working correctly
file:///D|/1/final/BBL0005.html (11 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC) ❍
Testing the performance by examining the code's internal structure.
❍
Selecting test data carefully so that specific parts of the program units are exercised.
❍
❍
Testing that may include the following of the values from one variable to the next by using the debugger and its jump points. This testing is more expensive that Black Box because the tester looks at the interior workings of each individual part of the program.
Testing is frequently subdivided into two general types: ●
Alpha Testing that is done in-house by staff members (This group is frequently called the Software Quality Assurance or Testing staff.)
●
Beta Testing that is done outside of the company and is done by "real people" where the system developers try to determine: ❍
❍
Is it possible for "real people" to interact with the program as it is designed and meet the system requirements specification? Do "real people" get the correct outputs for specific inputs?
Note: I recommend that you read the following book: Craig, Rick et al; Systematic Software Testing; Artech House Publishers; Boston, MA; 2002; ISBN 1-58053-508-9
Maintenance Phase (Adding Enhancements) As a future programmer, it is important for you to know some of the reasons for the need of the maintenance phase. These reasons can be: ●
that some of the previous phases were done incorrectly.
●
that the original program specifications or the business plan has changed.
●
that because of poor program structure, poor program documentation or poor program style you are required to redo some of the program or all of the program.
●
that the testing did not catch all of the bugs before the release so that some or all of the program needs to be redone‥
●
that marketing or management was trying to hurry the development of the program before it was completed so that they could deliver the product.
It is important for you to know: ●
that the fixing of bugs is difficult, time consuming and never ending.
●
that the process of removing bugs impedes implementation of program enhancements.
●
that some of the reasons that maintenance may fail are: ❍
❍
the code does not agree with the documentation. changes were made to the program but there is no documentation to indicate what or why the changes were made.
It is also important for you to know that this phase can be the:
file:///D|/1/final/BBL0005.html (12 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
●
Largest % of computer center's budget
●
Largest % of programmer's time
●
Largest % of software development costs
●
Only type of IT positions open at some companies
At the end of the course, you need to ask yourself: ●
Do I want to do maintenance?
●
Do I have the skills necessary to do this type of work?
file:///D|/1/final/BBL0005.html (13 von 13) [01.12.2007 04:47:35]
The "Real" 5-Phases
The "Real" 5-Phases Software development should not follow the "waterfall" approach as seems to be implied by the previous section of this lecture. What is really needed is interplay between each of the phases. A reinterpretation of the five phases of software development is shown in the graphic below where each phase is connected to every other phase. This approach is sometimes referred to as "spiral" software development. In addition to having each phase connected to every other phase, Security and Quality Assurance should be connected to every phase as well. The most important feature of this approach is to notice that the Users (and other stakeholders) are central to the phases and that they need to be involved throughout the entire project.
In addition to not following a linear approach to software development, another modification of the five phases utilizing a component library approach is recommended. In this approach components from the company's software library are used if they exist and if not, then new components are created and utilized. This approach is referred to as "component" software development. The following graphic shows the five phases slightly modified to represent this approach:
file:///D|/1/final/BBL0006.html (1 von 2) [01.12.2007 04:47:35]
The "Real" 5-Phases
While using components in the company library is the approach to take, extra care must be taken not to modify these components and therefore to make them unusable to future as well as previously written programs. Again you should consider that security and quality assurance are involved throughout this process. As you progress through these lectures, you should try to develop components that could be used in your future programming. These components could be stored in a dynamic linked library a .dll file like: tools.dll. While the code in this course is in C#, it is possible that some tools developed for this course could be used in C, in C++ or even in Java programs.
file:///D|/1/final/BBL0006.html (2 von 2) [01.12.2007 04:47:35]
CASE Tools
CASE Tools Today, to aid in the development of the 5-phases, CASE tools (i.e. Computer-aided Software Engineering tools) are used. In researching for these lectures, I found the following definition of CASE tools. Definition of CASE tools: CASE tools are computerized software development tools that support the developer when performing one or more of the phases of the software life cycle and/or support software maintenance. In these lecture notes two different CASE tools will be used: Microsoft Visio 2003 © and Microsoft Visual Studio . NET 2005 ©. CASE tools are subdivided into several categories. Two of the categories are: "classic" and "real". Computer compilers are examples of "classic" CASE tools. CASE tools that can be used in several of the phases are called "real". Both Visio and Visual Studio .NET can be considered "real" CASE tools using this definition. Some of the new testing tools on the market can be considered "real" as well because they can be involved in several of the 5phases. Another categorization of CASE tools are "upper" and "lower". By the term: "upper" CASE tools is meant those tools that support the first two phases while the "lower" CASE tools support the last three phases. In terms of these categories, Visio is considered an "upper" CASE tool while Visual Studio .NET is considered to be a "lower" CASE tool. Both Visio and Visual Studio .NET have a greater capacity as CASE tools than will be studied in this course. It is recommended that you try to go beyond their minimal introduction and study both of these CASE tools more in depth. Many students do not like to use the power of these tools until they are forced to. However you will find that in general, once you learn how to use them, they will save considerable amounts of time. For example in the Galin book listed below, he provided data on a programming job that required 110 days for the 5-phases to develop the software using traditional non-CASE tool methods. When the same program was created using CASE tools, only 61 days were required. He claimed that if advanced CASE tools had been used then there would have been an even greater reduction in time spent on development of the program. The following graphic attempts to illustrate how traditional programming compares to using CASE tools. This graphic is from the Galin book p 301.
file:///D|/1/final/BBL0007.html (1 von 2) [01.12.2007 04:47:36]
CASE Tools
Note: In the graphic above, Repository means the collection of the documentation from all phases of the software development. Note: In the graphic above, notice the different categories of the development team. Your goal as a future member of a software development team is to determine which of these jobs you are the best at and which you want to work on. The above discussion is a modification of the topic from the following book which I highly recommend that you read: Galin, Daniel; Software Quality Assurance: From theory to implementation; Addison Wesley, 2004. p 298 – 304.
file:///D|/1/final/BBL0007.html (2 von 2) [01.12.2007 04:47:36]
The Team
The Team The project team consists of many different groups of individuals to include: ●
Upper Management
●
Middle Management
●
Team Manager
●
Users ("Real People" or "Stakeholder")
●
Program Analysts
●
Program Designers
●
Program Coders
●
Test Center Staff (Quality Assurance)
●
Program Maintenance Staff
●
System's Deployment Staff
●
System's Security Staff
●
Help Center Staff
Which of the above positions you will be assigned will depend on the project, your talents, your client and your company. Note: In today's world the groups listed above may not be in the same part of the world or even within the same company. Some companies do the analysis and the design internally and sub job out the coding. The testing may be done internally but it could also be sub jobbed out as well. Since the maintenance can link back to the top of this list, these staff members may be a part of the company. The deployment and the security may also be internal as well as sub jobbed. Ask yourself after this course: ●
Where do I want to work?
●
In which of these areas do I have the skills necessary to be successful?
file:///D|/1/final/BBL0008.html [01.12.2007 04:47:36]
An Example of the 5 Phases
An Example of the 5 Phases The following is a look at a "real world" example (only parts of the phases are included): ●
Phase 1 Problem Analysis and Specification
●
Phase 2 Design
●
Phase 3 Implementation of the Design (Coding)
●
Phase 4 Testing, Execution and Debugging
●
Phase 5 Maintenance
Phase 1: Problem Analysis and Specification Make a small business accounting system for an accounting service that meets the following specifications: 1. Statement of the problem. 2. Sample Data and Print Outs ❍
Profit and Loss Statement
❍
Expense Ledger
❍
Sales Ledger
3. Program Conditions 4. Sample screens ❍
Main Menu
❍
Sales Menu
Case Study #1: A Single Entry General Ledger for Multiple Clients of an Accountant This program was encountered in the early 1980's. An accountant needed some accounting programs written. He had purchased a PC with 64 KB of RAM and a dual floppy 5 1/4" drives. In addition he had a dot-matrix printer. Prior to this project, the company's staff members were using this system to only do word processing. A franchised computerized accounting service had come to town. They were offering a service similar to what he provided for his clients. They were offering their services at a lower price than he was charging. Their service used the paid out records and the sales records to develop a monthly profit and loss statement. Their service did not include check writing or consultation on the status of the business or what future actions might improve the business performance. The accountant wanted to computerize his business so that he could compete with the computerized accounting service. He hoped that if he computerized, he could serve more clients in the same amount of time and thereby be able to lower his prices to that of the computerized accounting service. The accountant had surveyed the computer accounting field and could not find an accounting package which met his needs. His clients were small cash businesses. They had no accounts receivable, no accounts payable and no inventory control needs. He only used a simple single entry general ledger rather than a double entry general ledger for his clients. Most of the software packages he found were double entry ledgers and had far more features than were needed by his clients. Therefore, he wanted a single entry general ledger program created that was easy to use, would run on his computer, and would duplicate the forms he was currently using (sample forms are included on the next few pages.) He wanted to be able to have several different clients on each floppy. Because he did not want an extensive library and he wanted to be able to call up their past records using their client number. He had two different forms for different types of clients and he wanted two different programs to serve the two types of clients or one program that could be used for all of his customers. Profit or Loss Statement Name:_____________________________ DBA:______________________________ Street: ______________________________ file:///D|/1/final/BBL0009.html (1 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
City/State: ___________________________ Month of ________ Year: _______________ ============================================================== SALES
CURRENT MONTH
YEAR TO DATE
3.__________________ $______________ 4.__________________ $______________ 5.__________________ $______________ 6.__________________ $______________ 7.__________________ $______________ 1. TOTAL SALES
$________________
$________________
2. OTHER INCOME
$________________
$________________
1&2 GRAND TOTAL
$________________
$________________
$________________
$________________
$________________
$________________
=============================== PURCHASES\ Cost of Sales 8. __________________ $______________ 9. __________________ $______________ 10._________________ $______________ 11._________________ $______________ 12. TOTAL PURCHASES\ Cost of Sales =============================== GROSS PROFIT =============================== DEDUCT EXPENSES 13._________________________________
$________________
$________________
14._________________________________
$________________
$________________
15._________________________________
$________________
$________________
16._________________________________
$________________
$________________
17._________________________________
$________________
$________________
18._________________________________
$________________
$________________
19._________________________________
$________________
$________________
20._________________________________
$________________
$________________
21._________________________________
$________________
$________________
22._________________________________
$________________
$________________
23._________________________________
$________________
$________________
24._________________________________
$________________
$________________
25._________________________________
$________________
$________________
___________________________________
$________________
$________________
___________________________________
$________________
$________________
___________________________________
$________________
$________________
TOTAL EXPENSES ==================================
$________________
$________________
NET PROFIT
$________________
$________________
==================================
Expense Ledger Open table as spreadsheet Sam's Computer Store
Jill & John Pilgry
544 W. 5th St. Mayville, WI file:///D|/1/final/BBL0009.html (2 von 23) [01.12.2007 04:47:42]
Expenses
An Example of the 5 Phases
May-00 12
14
Check Amt
$
11,348.00
7-MayBill Wagner
15492 $
280.00
$
280.00
7-MayTom Jason
15493 $
350.00
$
350.00
10-MayRace Office Supply
15494 $
146.31
10-MayIRS
15495 $
1,146.81
10MayHowie's Service
15496 $
19.00
11MayThomas Electronics
15497 $
7,948.00
11-MayWPS
15498 $
450.00
11MayWisconsin Tele
15499 $
179.40
12-MayWNAM
15500 $
491.00
12-MaySun Inc.
15501 $
1,346.57
14-MayTom Jason
15502 $
350.00
$
350.00
14-MayBill Wagner
15503 $
280.00
$
280.00
14-MayPost Crescent
15504 $
752.76
14-MayBenic Computers
15505 $
6,349.00
17MayService Master
15506 $
192.00
17-MayPolice Ball
15507 $
45.00
18MayThomas Electronics
15508 $
4,689.00
19-MayWYTL/ WOSH
15509 $
540.00
19MayHomarc Inc
15510 $
795.00
21-MayTom Jason
15511 $
350.00
$
350.00
21-MayBill Wagner
15512 $
280.00
$
280.00
22MayHowie's Service
15513 $
45.00
23MayOshkosh Northwestern
15514 $
350.00
24-MayBenic Computers
15515 $
3,568.00
Date
Name
YTD Totals
Cost of Sales
13
Check #
$
file:///D|/1/final/BBL0009.html (3 von 23) [01.12.2007 04:47:42]
92,499.32
Office Sup. $
$
495.75
15
Wages
16 Rent
$
3,180.00
17
Telephone $
720.00
18
Utilities $
1,549.96
19
Advertizing $
7,990.60
$
$
$
7,157.80
$
1,146.81
$
258.75
$
450.00
22
23
Maintenance $
1,728.97
$
192.00
Misc Expenses $
1,556.38
$
45.00
19.00
179.40
$
491.00
$
752.76
1,346.57
6,349.00
4,689.00
$ $
540.00
795.00
$
$
$
$
Insurance
7,948.00
$
$
576.50
21
Taxes
146.31
$
$
20
Vehicle
3,568.00
350.00
45.00
An Example of the 5 Phases
24-MayINA
15516 $
175.00
25-MayWis. Public Service Corp
15517 $
374.32
26-MayUnited Fund
15518 $
150.00
26-MaySun Inc.
15519 $
592.56
27MayChamber Com. (Dues)
15520 $
230.00
28-MayTom Jason
15521 $
350.00
$
350.00
28-MayBill Wagner
15522 $
280.00
$
280.00
28MayHowie's Service
15523 $
37.50
28MayService Master
15524 $
211.00
31-MayWis. Dept. Revenue
15525 $
697.41
31-MayRace Office Supply
15526 $
28.56
●
MTD Totals
●
YTD Totals
$34,069.20
$ $
$
374.32
$
$
28.56
230.00
37.50
$
697.41
$
211.00
$
174.87
$
2,520.00
$
795.00
$
179.40
$
374.32
$
2,133.76
$
101.50
$
1,844.22
$
625.00
$
403.00
$
425.00
$
116,992.45
$
670.62
$
13,868.00
$
3,975.00
$
899.40
$
1,924.28
$
10,124.36
$
678.00
$
9,002.02
$
883.75
$
2,131.97
$
1,981.38
Jill & John Pilgry
Mayville, WI May-00
SALES 3
4
Computer
5
Software $
26,096.44
6
Books $
2,741.72
7
Peripherals $
23,937.48
8
Training $
750.56
Misc $
Daily Totals
Weekly Totals
28.00
Date 2-May
$
567.52
$
156.99
$
36.42
$
399.95
$
80.00
$
-
$
1,240.88
3-May
$
764.98
$
210.87
$
15.75
$
196.50
$
-
$
5.00
$
1,193.10
4-May
$
871.32
$
184.63
$
75.30
$
245.30
$
10.00
$
-
$
1,386.55
5-May
$
671.36
$
220.42
$
53.20
$
288.40
$
30.00
$
-
$
1,263.38
6-May
$
794.53
$
350.72
$
21.10
$
149.36
$
-
$
-
$
1,315.71
7-May
$
943.31
$
424.65
$
-
$
836.75
$
-
$
-
$
2,204.71
9-May
$
475.41
$
198.64
$
26.00
$
330.40
$
40.00
$
-
$
1,070.45
10-May
$
631.25
$
75.00
$
-
$
-
$
-
$
10.00
$
716.25
11-May
$
241.63
$
156.38
$
33.40
$
440.00
$
-
$
-
$
871.41
12-May
$
714.62
$
348.62
$
25.00
$
75.36
$
20.00
$
-
$
1,183.60
13-May
$
691.75
$
75.84
$
19.50
$
590.00
$
-
$
-
$
1,377.09
14-May
$
541.28
$
140.50
$
-
$
-
$
-
$
4.00
$
685.78
16-May
$
364.18
$
230.75
$
41.90
$
-
$
-
$
-
$
636.83
17-May
$
894.36
$
246.40
$
36.52
$
-
$
-
$
-
$
1,177.28
18-May
$
1,643.80
$
643.74
$
147.80
$
876.51
$
-
$
6.00
$
3,317.85
19-May
$
284.67
$
-
$
-
$
321.54
$
-
$
-
$
606.21
file:///D|/1/final/BBL0009.html (4 von 23) [01.12.2007 04:47:42]
$
24,493.13
Sam's Computer Store
78,329.68
150.00
$
544 W. 5th St.
$
$ 592.56
Sales Ledger Open table as spreadsheet
YTD Totals
175.00
$
8,604.33
$
5,904.58
An Example of the 5 Phases
20-May
$
591.84
$
280.30
$
17.50
$
543.41
$
30.00
$
-
$
1,463.05
21-May
$
756.31
$
150.30
$
42.30
$
678.95
$
20.00
$
4.00
$
1,651.86
23-May
$
594.51
$
250.90
$
56.75
$
136.50
$
-
$
-
$
1,038.66
24-May
$
964.35
$
442.53
$
31.42
$
-
$
-
$
2.00
$
1,440.30
25-May
$
736.49
$
211.34
$
25.97
$
71.00
$
-
$
3.00
$
1,047.80 5,009.25
26-May
$
3,497.86
$
1,468.39
$
43.00
$
-
$
-
$
-
$
27-May
$
284.69
$
-
$
15.00
$
245.00
$
-
$
-
$
544.69
28-May
$
1,384.76
$
546.97
$
13.00
$
-
$
-
$
-
$
1,944.73
30-May
$
796.58
$
231.42
$
-
$
438.41
$
40.00
$
-
$
1,506.41
31-May
$
384.60
$
119.75
$
30.00
$
120.70
$
10.00
$
-
$
========= ●
MTD Totals
$
21,087.96
========= $
========= ●
YTD Totals
$
99,417.64
7,366.05
========= $
========= $
33,462.49
806.83
========= $
========= $
3,548.55
6,984.04
========= $
========= $
30,921.52
280.00 =========
$
1,030.56
========= $
34.00
$
========= $
62.00
665.05 ========= 36,558.88 =========
$
Program Conditions The accountant requested that the program include the following features: 1. That all of the calculations should be carried out by his computer. 2. That the sums for each client should be stored to be used from month to month but that the program would have a way to modify these sums if it became necessary later. 3. That a column for percentages be added to the general ledger so that he could compare sales, purchases (cost of sales), and that the program would calculate each expense category as a percentage of gross sales for MTD and YTD. 4. That he would be able to enter in the expenses and sales into the program as he read from the client's checkbook and the cash register slips, he would be able to edit errors or delete records which were incorrect, he would be able to get a print out of the expenses and sales for MTD, and that these could be cleared after each month. (The monthly values would be cleared only on demand by him and not automatically done by the computer.) 5. That the computer would sort the expenses and sales into their respective categories and print their sums in the P&L statement. 6. That he could override the Total Sales and the Total Purchases if he wished. He claimed that this was necessary to adjust the monthly profit/ loss statements to reflect the "true business" when sales or purchases would require carrying over several months. 7. That all of his thirteen expense categories could be used and in addition four others could be entered for special clients. Further he wanted room for three expense categories to be listed in the remarks area which were not figured into the Total Expenses.
Program Main Menu The Main Menu of the program was to look like the following:
Sales Ledger The Sales Ledger menu was to look like the following: file:///D|/1/final/BBL0009.html (5 von 23) [01.12.2007 04:47:42]
168,442.76
$
8,853.08
$
11,025.43
$
2,171.46
An Example of the 5 Phases
Phase 2: Design The following steps were part of the Design Phase: 1. Abstract Data Types for Accounting 2. Human Interface for Accounting 3. Structure Chart for Accounting 4. Flow Chart for Accounting 5. Pseudo Code for Accounting The above examples of the design phase's documents are incomplete and are listed here to only give you a brief illustration of where you will be by the end of this course.
Abstract Data Types (ADT) for Accounting System 1. Company: What types of data are needed for Company? ❍
name - string
❍
owner - string
❍
address - string
❍
city - string
❍
state - string
❍
zip - string
What types of functions/methods are needed for Company? ❍
input name, owner, address, city, state and zip
❍
output company information
UML data type description:
Company -companyName:string -companyOwner:string -companyAddress :string -companyCity:string -companyState:string -companyZip:string
file:///D|/1/final/BBL0009.html (6 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
+inputName(name: string ) +inputOwner(owner: string ) +inputAddress(address: string ) +inputCity(city: string ) +inputState(state: string ) +inputZip(zip: string ) +outputCompanyInfo( )
2. Date: What types of data for Date? ❍
month - int
❍
day - int
❍
year - int
What types of functions/methods for Date? ❍
input month,
❍
input day
❍
input year
❍
output month
❍
output day
❍
output year
❍
output date
UML data type description:
Date -month:integer -day:integer -year:integer +inputMonth(theMonth: int ) +inputDay(theDay: int ) +inputYear(theYear: int) +outputMonth( ):integer +outputDay( ):integer +outputYear( ):integer +outputDate( )
3. Sales: What types of data for Sales? ❍
day - date
❍
daily_sales[5] - array of floats
file:///D|/1/final/BBL0009.html (7 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
What types of functions for Sales? ❍
input date (month, day and year)
❍
input sales
❍
modify sales
❍
output sales date
❍
output sales amount for a particular account
❍
output sales for the date
UML data type description:
Sales:Date -dailySales[5]:float +inputSalesAmounts(dayNumber: int, amount: float ) +modifySalesAmount(dayNumber: int, amount: float ) +showSalesAmount(number:integer):float +showSalesAmounts( )
The above listing is not a complete analysis, so ask yourself: What other ADTs would be needed?
Human Interface for Accounting The Design Phase as well as the Specification Phase should contain samples of the Human Interface. For example there should be samples of the menus. The menus of the system should look something like the following:
Main Menu 1. Start New Client 2. Expense Ledger Menu 3. Sales Ledger Menu 4. Profit and Loss Menu 5. End of Year Processing 6. Quit Which?
Sales Ledger Menu 1. Enter Daily Sales 2. Edit Daily Sales 3. Print Daily Sales 4. Process End of Month Sales 5. Return to Main Menu
file:///D|/1/final/BBL0009.html (8 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
Which?
Expense Ledger Menu 1. Enter Expense 2. Edit Expense 3. Print Expense Report 4. Process End of Month Expenses 5. Return to Main Menu Which?
In addition to the menus as shown above, there should also be samples of any additional input screens to provide the programmer with information about how they are to appear. For example input screens need to provide information as to how the sales and expenses would be entered and what the screens will look like when the user wants to edit the sales or the expenses. But not only should there be examples of the input screens, there needs to be examples of output screens as well. For example there needs to be examples of what each report will look like. The samples for both the input and the output will be similar to yet different from the samples created for the Specification Phase. The documents of the Specification Phase should be samples of what the user is currently viewing and how it will be different. The Design Phase samples should show the programmer how to represent the screens that the user will view in the finished program.
Structure Chart for Accounting As discussed previously, a program needs to be subdivided into pieces that are called modules. Subdividing the program in this way provides a better design, one which is easier to manage and in general one that is less expensive to create and to maintain. The structure chart of the accounting program should look similar to the following:
Notice at the top of this structure chart is the main module called accounting. This module is then subdivided into the several additional modules that appeared in the main menu seen previously to include the options: Start Client, Sales Ledger, Expense Ledger, Profit and Loss and End of Year Processing. The Sales Ledger and the Expense Ledger menus each had several options. For example in the Sales Ledger menu, there were Enter Sales, Edit Sales, Print Sales and Process End of Month options. Notice in this structure chart that each of these options has a module that is to carry out these objectives. What this sample of a structure chart does not show is the movement of data between the different modules. The reason for this is that this program was created in the early 80's and the movement of data was not directly between the different modules but instead the data was handled globally. Later in the notes will be samples of structure charts that show how to handle the movement of data directly between modules rather than moving data globally.
Flow Chart for Accounting The Design Phase should provide documentation that shows the programmer the logic of the program and the names of the modules as well as file:///D|/1/final/BBL0009.html (9 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
the names of the data that are to be used in the program. There are several different tools that can be used to do this. One tool is a flowchart and another is pseudo code. A flowchart is a graphic representation of this logic. It shows the program flow. The following is a flowchart for the Accounting module and it shows the logic of the main menu. Notice as the program begins, the user decides which process to select and depending on the choice will go to one of the modules for that menu option. After each module is completed, the program flow returns to the main menu.
This flowchart is not a complete flowchart of the total system and its individual parts/modules. The final documentation should contain a separate flowchart for each module.
Pseudo Code for Accounting The Design Phase should contain documents that represent the logic of the program. This can be done with a flowchart or with pseudo code. The pseudo code is "false" code. That is, it does not show exactly the instructions in a particular language. In fact pseudo code should be written so that it could be used in one of several different languages depending on what language is available for the program. What the pseudo code should do is to show the logic of the program but do it in words rather than graphically as is done with a flowchart. This example could represent the pseudo code of the accounting program: Accounting do Display the Main Menu Choices 1. Start New Client 2. Expense Ledger Menu 3. Sales Ledger Menu 4. Profit and Loss Menu 5. End of Year Processing 6. Quit Request and Receive Choice Case: 1: Process strt_clnt 2: Process expens_ldgr 3: Process sales_ldgr 4: Process pandl 5: Process eoy 6: End Program EndCase file:///D|/1/final/BBL0009.html (10 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
dowhile(continue) End strt_clnt ..... Return expens_ldge ..... Return sales_ldgr .... Return pandl ...... Return
Notice that the main module processes or calls each of the sub modules depending on the user's choice. When creating pseudo code, each module has its own separate part of the total. When each module completes its instructions, the program will return to the calling module. That is the reason for the word Return in each of the sub modules of the pseudo code. In this example, the dots above represent statements that are being left out. The real pseudo code would provide these statements.
Phase 3: Implementation of the Design (Coding Phase) The Coding Phase converts the documents of the previous phases into the instructions of a particular version of a particular language. In this course we will look at using the version of C# in Visual Studio .NET 2005. Note: The original accounting program was written in the early 80's in BASIC before C# was invented. The coding listed here is actually a maintenance of the original program that has been rewritten in C++. Link to each of the following to get a general feel of how the design would be converted to C++. ●
Header file: accounting.h
●
Program file: accounting.cpp
This implementation of the program is in two pieces one of which is called a header file and the other is called a program file. A later lecture will discuss how to combine these two files into a program using the Visual Studio .NET C# CASE tools. // // // // // // // // // // //
This is the header: accounting.h This header is required for the program accounting.cpp It does not include all of the class information required by the program.
Some of the classes that are needed in this program.
class company { private: string companyName, companyOwner, companyAddress, companyCity, companyState, companyZip; public: void inputName() { cout << "What is the company name? "; cin >> companyName; file:///D|/1/final/BBL0009.html (11 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
cout << endl; } string outputName() { return companyName; } void inputOwner() { cout << "Who is the company's cin >> companyOwner; cout << endl; } void inputAddress() { cout << "What is the company's cin >> companyAddress; cout << endl; } void inputCity() { cout << "What is the company's cin >> companyCity; cout << endl; } void inputState() { cout << "What is the company's cin >> companyState;
owner? ";
address? ";
City? ";
State? ";
cout << endl; } void inputZip() { cout << "What is the company's Zip? "; cin >> companyZip; cout << endl; } void outputCompanyInfo() { cout << "Company: " << companyName << endl << "Owner: " << companyOwner << endl << "Address: " << companyAddress << endl << "City: " << companyCity << endl << "State: " << companyState << endl << "Zip: " << companyZip << endl; } }; class date { private: int month, day, year; public: void inputMonth() { cout << "What is the month? "; cin >> month; cout << endl; { void inputDay() { cout << "What is the day? "; cin >> day; cout << endl; } void inputYear() { cout << "What is the year? "; file:///D|/1/final/BBL0009.html (12 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
cin >> year; cout << endl; } int outputMonth() { return month; } int outputDay() { return day; } int outputYear() { return year; } void outputDate() { cout << month <<'/' << day << '/' << year; } }; class sales: public date { private: float dailySales[5]; public: void inputSalesAmounts() { for(int gl = 3; gl<=7;++gl) { char resp, ch; do { cout << endl <<"What is the sales for GL # " << gl << "? "; cin >> dailySales[gl-3]; cout << endl << "Correct? (Y/N) "; resp=' '; cin.get(ch).get(resp).get(); }while((resp!='Y') && (resp!='y')); } } void modifySalesAmount(int number) { cout << "The current value for that gl account is: " << dailySales[number] << endl; cout << "What should the amount be? "; cin >> dailySales[number]; cout << endl; } void showSalesAmounts() { float ttl_sales=0.00; for(int gl = 3; gl<=7;++gl) { cout << endl << "Sales GL #" << gl << ": " << setprecision(2) << setw(10) << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << dailySales[gl-3]; ttl_sales += daily_sales[gl-3]; } cout << endl << setw(23) << "----------"; cout << endl << "Totals Sales " << setprecision(2) << setw(10) << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << ttl_sales; file:///D|/1/final/BBL0009.html (13 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
} float showSalesAmount(int number) } return dailySales[number]; } };
// // // // // // // // // // // // // // // // // // // //
program-id author date written modified by date(s) modified hardware requirements
software requirements
program description
ACCOUNTING.CPP DON VOILS SEPTEMBER 21, 1988 dlv 12/1/93; 8/23/00; 8/23/01 PC 512 K RAM 10 MB HARDDISK PC DOS 2.1 or higher MICROSOFT C++ Version 6.0 or higher THIS PROGRAM CONTAINS THE MENUS FOR ALL MODULES OF THE ACCOUNTING SYSTEM. FROM THESE MENUS THE USER CAN SELECT WHICH OF THE ACCOUNTING MODULES HE/SHE WANTS TO USE.
Program was modified to be compliant with Standard C++.
/* The following are the headers required for this program. The names have been modified to be compliant with Standard C++. */ #include
#include #include #include #include<string> /* The following was added to become compliant with Standard C++. */ using namespace std; /* The following header contains the data structures definition. */ #include"accounting.h" // // //
FUNCTION PROTOTYPES
void clr_scrn(); void salesLedger(); void void void void void
inputSales(); printSales(); editSales(); eomSales(); startClient();
file:///D|/1/final/BBL0009.html (14 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
// // //
Start of the program.
void main() { char menu_1='0', ch; /* Main menu to select major processes to perform. */ do { menu_1='0'; clr_scrn(); cout << << << << << << << <<
" " " " " " " "
1. 2. 3. 4. 5. 6.
Main Menu" << endl << endl << endl Start New Client" << endl << endl Expense Ledger Menu" << endl << endl Sales Ledger Menu" << endl << endl Print P&L" << endl << endl End of Year Processing" << endl << endl Exit" << endl << endl Which? ";
cin.get(menu_1).get(ch); clr_scrn(); switch (menu_1) { case '1': // // // //
THIS MODULE PROCESSES THE INSTALLATION OF NEW CLIENTS.
startClient(); // menu_1 = '0'; break; case '2': // THIS MODULE HELPS THE USER TO SELECT WHICH // OF THE EXPENSE MODULES TO USE. // // // expenseLedger(); // menu_1 = '0'; break; case '3': // THIS MODULE HELPS THE USER TO SELECT WHICH // OF THE SALES MODULES TO USE. // salesLedger(); // menu_1 = '0'; break; case '4': // // // // // //
THIS MODULE PERMITS THE USER TO PROCESS THE P & L STATEMENT BY MERGING THE MTD FIGURES WITH THE YTD FIGURES. IF THE USER CHOOSES, THE MTD MAY BE ADDED TO THE YTD FIGURES FOR STORAGE FOR THE NEXT MONTH.
file:///D|/1/final/BBL0009.html (15 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
// // PandL(); // menu_1 = '0'; break; case '5': // THIS MODULE PERMITS THE ZEROING OF YTD // FIGURES SO THAT A NEW YEAR CAN BE PROCESSED. // // endofYear(); // menu_1 = '0'; break; case '6': // // menu_1 = '6'; break; default: // // // // menu_1 = '0'; break;
THIS SECTION PERMITS THE USER TO EXIT
IN CASE THE USER SELECTED A NUMBER OTHER THAN 1-5 THIS MODULE WILL FORCE THE USER TO CHOOSE AN ACCEPTABLE NUMBER.
} } while (menu_1=='0'); } /*
program-id author date written modified by
salesLedger() DON VOILS SEPTEMBER 21, 1988 dlv
date(s) modified 8/23/01 program description THIS FUNCTION CONTAINS THE MENU FOR THE SALES. */ void salesLedger() { char menu_3='0'; /* THIS MODULE HELPS THE USER TO SELECT WHICH OF THE SALES MODULES TO USE. */ do { menu_3='0'; clr_scrn(); cout << flush; cout
<< << << << << << << <<
" Sales Ledger Menu" << endl << endl " 1. Enter Sales" << endl << endl " 2. Change Sales" << endl << endl " 3. Print Sales" << endl << endl " 4. End of Month Processing for Sales" endl << endl " 5. Return to Main Menu" << endl << endl " Which? ";
cin.get(menu_3).get(); switch (menu_3) file:///D|/1/final/BBL0009.html (16 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
{ case '1': /*
THIS MODULE PERMITS THE USER TO ENTER MTD SALES TRANSACTIONS.
*/ inputSales(); menu_3 = '0'; break; case '2': /*
THIS MODULE PERMITS THE USER TO EDIT MTD SALES TRANSACTIONS.
*/ editSales(); menu_3 = '0'; break; case '3': /*
THIS MODULE PERMITS THE USER TO PRINT MTD SALES. */ printSales(); menu_3 = '0'; break;
case '4': /* THIS MODULE PERMITS THE USER TO ZERO MTD TRANSACTIONS SO THAT A NEW MONTH CAN BE PROCESSED. */ eomSales(); menu_3 = '0'; break; case '5': /*
THIS MODULE PERMITS THE USER TO GO BACK TO THE MAIN MENU.
*/ menu_3 = '5'; break; default: /*
IN CASE THE USER ENTERED A SELECTION OTHER THAN 1-5 THIS MODULE WILL FORCE THE USER TO MAKE THE CHOICE AGAIN.
*/ menu_3 = '0'; break; } } while (menu_3 == '0'); } // // // // // // //
program_id author date written modified by date(s) modified program description
inputSales() don voils 11/25/93 dlv 8/23/00 This function inputs the daily sales.
void inputSales() file:///D|/1/final/BBL0009.html (17 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
{ char
resp=' ';
clr_scrn(); sales today; ofstream outfile; outfile.open("SALES.DAT",ios::app | ios::binary); do { clr_scrn(); today.inputDay(); today.inputMonth(); today.inputYear(); today.inputSalesAmounts(); outfile.write((char *) &today, sizeof(today)); clr_scrn(); cout << "Enter another day? (Y/N) "; resp=' '; cin.get(resp).get(); }while(resp=='Y' || resp=='y'); outfile.close(); } // // // // // // // // //
program_id author date written modified by date(s) modified program description
printSales() don voils 11/25/93 dlv 8/23/01 This function inputs from file the daily sales and sends them to a printer.
void printSales() { char resp=' ', ch; int count; clr_scrn(); ifstream companyFile; companyFile.open("COMPANY.DAT"); company theCompany; companyFile.read((char&)theCompany,sizeof(theCompany)); companyFile.close(); string name = theCompany.outputName(); sales today; clr_scrn(); ifstream infile; infile.open("SALES.DAT",ios::in | ios::binary); if (!infile) { cout << "The SALES.DAT is having problems."; return; file:///D|/1/final/BBL0009.html (18 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
} ofstream prtfile; /* The following will need to be modified for system installed on. */ prtfile.open("LPT1"); if (!prtfile) { cout << "The printer is having problems."; return; } float gl_ttls[5]={0.00}; for(count=1;count<=(60 -strlen(name))/2;++count) prtfile.put(' '); prtfile << name << endl; prtfile << setw(40) << "Monthly Sales Ledger" << endl; prtfile.width(60); prtfile.fill('-'); prtfile << endl; prtfile.fill(' '); prtfile << setw(6) << "Date"; for(count=3;count <=7;++count) prtfile << setw(9) << "GL#" << count; prtfile << endl; infile.read((char *) &today, sizeof(today)); while(infile) { prtfile.width(2); prtfile.fill('0'); prtfile<< today.showMonth(); prtfile.width(1); prtfile << "/"; prtfile.width(2); prtfile.fill('0'); prtfile << today.showDay(); prtfile.width(1); prtfile << "/"; prtfile.width(2); prtfile.fill('0'); prtfile << today.showYear(); prtfile.fill(' '); for(count=3;count <=7;++count) { prtfile << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2) << setw(10) << today.showSalesAmount(count-3); gl_ttls[count-3] += today.showSalesAmount(count-3); } prtfile << endl; infile.read((char *) &today, sizeof(today)); }
file:///D|/1/final/BBL0009.html (19 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
prtfile << setw(8) << " "; for(count=3;count <=7;++count) prtfile << setw(10) << "---------"; prtfile << endl << setw(8) << " "; for(count=3;count <=7;++count) prtfile << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2) << setw(10) << gl_ttls[count-3]; prtfile << flush; cout << endl << endl << "Are you ready to end this? (Y/N)"; cin.get(resp).get(ch); } // // // // // // // //
program_id author date written modified by date(s) modified program description
void editSales() { char ch;
editSales() don voils 11/25/93 dlv 8/23/01 This function permits editing of the daily sales.
resp=' ',
clr_scrn(); sales today; fstream file; int record_number; int position; file.open("SALES.DAT",ios::in | ios::out | ios::binary); file.seekg(0,ios::end); int end_position = file.tellg(); int last_record = end_position/sizeof(sales); cout << << << << <<
"The length of the files is " end_position << " bytes" endl << "The size of each record is " << sizeof(sales) " bytes" << endl "The number of records is " << last_record << endl;
if (last_record==0) { cout << "There are no records. The program is now exiting." << endl << endl << "Continue? (Y/N) "; cin.get(resp).get(); return; } do { do file:///D|/1/final/BBL0009.html (20 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
{ cout << endl << "Which record do you want to see? "; cin >> record_number; if ((record_number>last_record) || (record_number<1)) cout << endl << endl << "Beyond end of data." << " Pick another record." << endl; }while((record_number>last_record) || (record_number<1)); clr_scrn(); position = (record_number-1)*sizeof(sales); file.seekg(position); file.read((char*) &today,sizeof(sales)); cout << "Sales at record number " << record_number << " is " << endl; cout << "Date: " << today.outputMonth() << "/" << today.outputDay() << "/" << today.outputYear() << endl << endl; today.showSalesAmounts(); cout << endl << endl << "Edit this record? (Y/N) "; cin.get(ch).get(resp).get(); cout << endl; if ((resp=='y') || (resp=='Y')) { today.inputMonth(); today.inputDay(); today.inputYear(); today.inputSalesAmounts(); file.seekp(position); file.write((char *) &today, sizeof(today)); } cout << endl << endl << "Do you want to edit another record? (Y/N) "; cin.get(resp).get(); clr_scrn(); } while(resp=='Y' || resp=='y'); } // // // // // // // // //
program_id eomSales() author don voils date written 11/27/93 modified by dlv date(s) modified 8/23/01 program description This function removes the sales file from the disk at the end of the month.
void eomSales() { char resp=' '; clr_scrn(); cout << "Clear the sales data for end of month processing? (Y/N) "; cin.get(resp).get(); file:///D|/1/final/BBL0009.html (21 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
if(resp=='Y' || resp=='y') { resp = ' '; cout << endl << endl << "Are you sure? (Y/N)"; cin.get(resp).get(); if(resp=='Y' || resp=='y') { cout << "I am erasing the file." << endl; fstream file; file.open("SALES.DAT",ios::out | ios::trunc | ios::binary); } } } // // // // // //
program_id author date written
startClient() don voils 11/27/93
program description
This function starts a new client
void startClient() { int count; clr_scrn(); ofstream the_company; the_company.open("COMPANY.DAT",ios::out|ios::binary); company theCompany;
clr_scrn(); char word[80]; for(count = 0; count <=5;++count) switch(count) { case 0: theCompany.inputName(); break; case 1: cout << "What is the company name? "; cin.getline(word,80); cout << endl << endl; theCompany.inputOwner(); break; case 2: theCompany.inputAddress(); break; case 3: theCompany.inputCity(); break; case 4: theCompany.inputState(); break; case 5: theCompany.inputZip(); break; } /* A module to enter YTD totals needs to be inserted at this point.
file:///D|/1/final/BBL0009.html (22 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
*/ write((char *) &theCompany, sizeof(theCompany)); } // // // // // // // //
program_id author date written
clr_scrn() don voils 11/27/93
program description
This function clears the screen for those compilers which do no have such a function built in.
void clr_scrn() { for(int loop_counter=0;loop_counter<=25;++loop_counter) cout << endl; }
Phase 4: Testing, Execution and Debugging Phase After the coding phase, a system of testing needs to be set up in the testing phase. This is usually done by the testing staff which might be called: Quality Assurance. For this group, the following questions need to be addressed: ●
What are the general techniques of the company used for testing?
●
Using these techniques, what would be a good plan for testing of this program?
●
How should the program be tested for Validation, Verification, Unit Testing, Integration Testing, Systems Testing, Blackbox Testing and Whitebox Testing?
●
Where are the specification documents, the design documents and the coding documents?
●
Do the documents of the various phases agree?
●
Where should the sample data come from and what should it look like?
●
Is there going to be Beta Testing in addition to Alpha Testing and if so who and when will these individuals be involved?
Note: What is being recommended today is that the testing of the program should begin with the first phase and then continue to a more intense testing in the Testing Phase.
Phase 5: Maintenance Phase Most programs require some modification after they have been put into service. That is why each programming project has a maintenance phase. To implement this phase, a system of maintenance needs to be set up and the following questions need to be addressed: ●
What would be a good plan for this phase?
●
What type of modifications can be anticipated?
●
Did management hurry this product to market so that not all of the features were implemented or tested that will require maintenance?
One thing to keep in mind is that this phase can be a very costly phase. For a private consultant, this can also be an area of additional revenue. After the accounting program described in this example was set up for the accountant and was in place for some time, he began to see places where modifications should be made to improve the quality of his services. Therefore a maintenance phase started the 5-phases of software development all over again.
file:///D|/1/final/BBL0009.html (23 von 23) [01.12.2007 04:47:42]
Comments on Software Development
Comments on Software Development ●
There are several methods used for program design. One is called Structured Design. This method of design began in the 1960's. It was used in COBOL, C and other early languages. This will be one of the major design methods used in this lecture.
●
Another method of design is called Object Oriented Design. This method began in the 80's. It is used in C++, Java and C#. This method of design will also be studied.
●
With the introduction of Windows another method of design was created: Graphic User Interface. Two other methods of design that were created with the introduction of Windows are Component Oriented Design and Event Oriented Design. These three methods began in the late 90's. They are the foundation of language: C# from Microsoft and Java from Sun MicroSystems. These three methods will be the major points considered in this course.
●
In most texts today, the authors state that a well structured program has no GOTO. While I support this position, you should be aware that older languages: e.g. COBOL, BASIC, C, and even C++ all have a GOTO and some people use this command when structured programming techniques do not seem to solve the problem at hand. Even C# has a GOTO command as well. However be very careful if you use it in your work.
●
While it is true that some of the languages you may encounter will have nonstructural constructs, you should learn these techniques because you will find that when used properly, they improve your software development and when it becomes necessary to violate the structured programming rules, you will understand why you would take this direction and you will understand the consequences of this deviation.
●
In some companies one or more of the 5-phases or parts of them are sub jobbed out. For example some recommend that the testing phase be done by an outside company. Their recommendation is based on the fact that members of the company's staff may not be as unbiased when reviewing the system development or parts there of.
●
The greater the risk of the system failing the greater the need for in depth analysis, design and formal documentation.
●
Another modification of the 5-phases being used is called "off shoring". In this approach, the coding phase is jobbed out to a programming company frequently in another country. This approach sometimes reduces the cost of programming. When the project is off shored, then the specifications and the design documents need to be more detailed to ensure that the off shore members of the team understand the project. This requirement can add to the cost of the project because those who are involved at this level of the project cost more than at the lower levels of the project. Because of the need for this additional managerial monitoring, the actual cost of sub jobbing or "off shoring" may not be less but in fact it may be greater than doing the 5-phases all in-house.
●
Instead of either programming in house or off shoring, some companies consider buying off the shelf software. Reasons for considering this approach are that the analysis and design needs are expected to be less. However in some cases this is not true.
●
Each of the five phases should be documented. The types of documentation used for each phase is specific to that particular phase. Some authors call the last phase of software development the documentation phase where all of the documentation is brought together. In some companies there is even a company program documentation librarian to keep track of all of the program documents.
●
While these notes shall discuss only the 5 phases for software development, the actual number of phases of program development is more than five. ❍
There is a phase called: System Analysis Phase that considers the analysis of the whole system including the human and the hardware parts of the system. This phase is in addition to the pure software approach that will be considered in this lecture. In this lecture the design view will be only that of the
file:///D|/1/final/BBL0010.html (1 von 2) [01.12.2007 04:47:42]
Comments on Software Development
software. ❍
❍
Further, there is another software phase that will not be considered in this lecture and it is called the Deployment Phase. This phase considers the implications and the process of the deployment of the software including the training of the users, development of a user's manual and even the development of a help center. The data stored in the computer systems that you will work on should be considered as company assets. As such, they should be guarded or protected as all company assets are. This consideration creates a phase that could be called the Security Phase. The Security Phase should begin with the first discussion of the system requirements and continue throughout the system's life cycle.
As stated above, there may be additional phases or steps that your project will pass through depending on the company you work for. You should consider taking additional courses that concentrate on the other phases of program development.
file:///D|/1/final/BBL0010.html (2 von 2) [01.12.2007 04:47:42]
Implications of Visual Studio .NET and C#
Implications of Visual Studio .NET and C# The .NET modification to Visual Studio was introduced in June 2000 as a new way to create programs for the Internet and other software uses. The latest version was introduced in November of 2005. In this course we will discuss Visual Studio .NET 2005. This IDE assists in creating programs that are component oriented using the many components included in .NET as well as those supplied by others. This environment permits the creation of systems that may be used in desktop computers, notebooks, PDA, cell phones and many other hardware devices. Visual Studio .NET 2005 has added many additional features for cell phones and other small hardware devices. The .NET environment permits the intermixing of programs written in several different languages to include: Managed C++, C#, J# (similar to Java), Visual Basic, COBOL .NET and many other languages. (Additional languages are continually being added to the .NET family of languages by other companies than Microsoft.) At first . NET programs were only designed for the Windows operating system. However it is now possible to develop .NET program to be used on Mac OS, Unix and other operating systems‥ The .NET environment is based upon components to include: XML Web Services, User Interfaces (either console or GUI). ASP .NET (for web access), ADO .NET (for data base and XML access), .NET Framework Class Library and the Common Language Runtime as indicated in the following graphic.
Visual Studio .NET has the ability to compile Managed C++ code, C# code, J# code and Visual Basic Code. Other vendors have created compilers for other language like COBOL .NET In the .NET environment these languages can share components with each other. This is done utilizing the components listed above and then by converting the original code into another code called: Common Intermediate Language (CIL) code. (This may require you to add additional code to your program to be able to share between these different language components.) Then the Windows' environment has built into it a program called a Just In Time Translator (JIT). The JIT then translates the CIL code into machine language on demand i.e. as the program runs. This translation is done only the first time the program is run in that environment. The following graphic illustrates this relationship.
file:///D|/1/final/BBL0011.html (1 von 2) [01.12.2007 04:47:43]
Implications of Visual Studio .NET and C#
The .NET Framework includes: ●
Common Language Runtime which is a run-time environment that manages the execution of code and provides services that simplify the development process.
●
Assemblies which are fundamental units of deployment, version control, reuse, activation scoping and security permissions.
●
Common Type System which identifies the types supported for the common language runtime.
●
Cross-Language Inter operability which manages objects created in different programming languages so that they may interact with one another.
●
.NET Framework Security which is a mechanism for protecting resources and code from unauthorized code and unauthorized users.
●
Framework Class Library which provides access to system functionality and is designed to be the foundation which .NET Framework applications, components and controls are built.
The purpose of this class is to only introduce you to these concepts. It is recommended that after this class, you spend additional time exploring the features of the .NET environment.
file:///D|/1/final/BBL0011.html (2 von 2) [01.12.2007 04:47:43]
Using Windows XP to Zip Files
Using Windows XP to Zip Files All homework for these lectures is to be submitted electronically. Each homework will have more than one file. All of the files for a homework are to be submitted in one zip file. You may use any program that creates a zip file. For example, you may use WinZip or your may use Windows XP. These zip files may be created at home, in one of the University's labs or any where in the world you want to create the zip files. The first step is to open a view of the directory where your files are saved. For example suppose that you were using a "thumb" drive (also called a USB drive). Clicking on myComputer you would select the location of your USB drive.
For example you might see the following:
Next suppose that you had created the files: temp1.txt, temp2.txt, temp3.txt and temp4.txt all of which you saved to your USB drive as the following graphic illustrates:
Next click on File, New and then Folder and then you will see the following:
file:///D|/1/final/BBL0012.html (1 von 7) [01.12.2007 04:47:44]
Using Windows XP to Zip Files
Notice the Compressed (zipped) Folder at the bottom of the dialogue box. Click on it and you will see:
The folder: New Compressed (zipped) Folder appears on the screen as in the above graphic. Change this name to the homework example like: HW1 (or whatever is the name of the homework) as in the following:
Holding the Ctrl button, click with your mouse on each of the files: temp1, temp2, temp3 and temp4 (of course the names of your files would be different). (Remember that all of the files are to be copied into the zip file. You are not to place each individual file in it own zip file.) What you will see is the following:
file:///D|/1/final/BBL0012.html (2 von 7) [01.12.2007 04:47:44]
Using Windows XP to Zip Files
Pointing at one of the files colored blue, click your right mouse button and you will see the following:
Next click the word Copy. This will store these instructions in the computer's memory. Follow this by clicking on the HW1 folder and click your right mouse button again and you will see:
file:///D|/1/final/BBL0012.html (3 von 7) [01.12.2007 04:47:44]
Using Windows XP to Zip Files
Then click Paste which copies the files into the zip folder. If you double click on the zip folder, you should see your files in the folder as in the following:
The next step is to log on to course into Blackboard and click on Tools on the menu and then click on the Digital Dropbox:
file:///D|/1/final/BBL0012.html (4 von 7) [01.12.2007 04:47:44]
Using Windows XP to Zip Files
When you do, you will see the following:
Next click on the Send File button and you will see:
Click on the Browse button and you will see:
file:///D|/1/final/BBL0012.html (5 von 7) [01.12.2007 04:47:44]
Using Windows XP to Zip Files
Click on the folder (in this case HW1) and the click on the Open button. The screen will now appear as the following:
Follow this by clicking the Submit button on the right. This should then show you a screen like the following:
Now click the OK button and you will see:
Each time you submit your homework the same steps should be followed. (Of course you see would be your name
file:///D|/1/final/BBL0012.html (6 von 7) [01.12.2007 04:47:44]
Using Windows XP to Zip Files
rather than mine as in the above graphic.) This file will be there until it is received and removed it from the Digital Dropbox. This is the process you are to use for each of the homework assignments. Notice that the date and time the file was sent appears. As a result, I will know whether you have submitted the homework on time. Remember that no late homework will be accepted for any reason.
file:///D|/1/final/BBL0012.html (7 von 7) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
Using Visio to Create UML Charts This lecture will discuss how to use Microsoft Visio Professional 2003 to create UML charts. Additional discussions on these charts will appear in other lecture notes. There are several books on the market that go into detail on how to use Visio, if you find that necessary. Generally, I have found that these books contain far more information than is needed for these lectures. I have noticed that Visio 2003 installed on different computers have some of the tool bars in other locations than you will see in these graphics. You may have to experiment to find some of the tools. Look under Tools or Format on the menu bar for additional tools that may not appear like these graphs on your copy of Visio 2003. During these lectures, you will be provided with a brief introduction to the Unified Modeling Language (UML). Among other things, by using UML it is possible to depict structures, classes, instances of structures and objects of classes. Visio can be used to create UML diagrams. For example in this lecture, the design of a class called Company was depicted as the following The data type Company will have the following fields: ●
name - string
●
owner - string
●
address - string
●
city - string
●
state - string
●
zip - string
The methods for Company: ●
input: name, owner, address, city, state and zip code
●
output: company information.
UML data type description: Company companyName:string companyOwner:string companyAddress :string companyCity:string companyState:string companyZip:string inputName(name:string) inputOwner(owner:string) inputAddress(address:string) inputCity(city:string) inputState(state:string) inputZip(zip:string) outputCompanyInfo()
file:///D|/1/final/BBL0013.html (1 von 9) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
The diagram above was done using a table. However the class Company can be depicted using Visio. To do this, open in Visio to a blank screen. In the Category menu bar select Software. When you do, a collection of options appear in the Templates on the right. One of these options is UML Model diagram (US units). Select this template. On the left will now appear a selection of UML graphics including Class. What you should see is something like the following graphic:
If the left hand side does not look like the above graphic, you may need to click the UML Static Structure (US units) option. Instead of being above the drawings as in the above graphic, this option may be below the graphic images. Once you have this available and you see these graphic images drag a copy of the Class onto the graphic. When you do it will appear like the following:
file:///D|/1/final/BBL0013.html (2 von 9) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
Double click on the Class 1 option and when you do the following should appear:
In the textbox: Name type in Company. In the Categories menu on the left, double click on the Attributes. When you do you, the attributes' option should appear. (In C# the attributes are called: fields.) Type in the field names: companyName, companyOwner, companyAddress, companyCity, companyState and companyZip. Once you do, you should have the UML Class Properties appear as in the graphic below (unfortunately the names are not completely visible but this can be overcome for any of the columns by moving your mouse to the vertical line between the columns and moving the line to make any column larger.):
file:///D|/1/final/BBL0013.html (3 von 9) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
For the Type select C#::string. When you have completed these steps, the UML Class Properties dialog box should appear as the following. To complete this step, click the OK button.
On the left the Model Explorer should list the class name with the names of the fields listed below as the following:
file:///D|/1/final/BBL0013.html (4 von 9) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
The Class diagram for Company on the grid should appear as:
Double click on Company in the Model Explorer on the left. This time double click on the Operations menu option. In the Operations column type enter the name of each of the following methods: inputName, inputOwner, inputAddress, inputCity, inputState, inputZip, outputCompanyInfo. When you do, the following should appear:
file:///D|/1/final/BBL0013.html (5 von 9) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
Select C#::void as the output for the first six of these operations and C#::string for outputCompanyInfo. You should now see something like the following graphic:
Once the names are in, click the OK button. In the Model Explorer you should see:
file:///D|/1/final/BBL0013.html (6 von 9) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
However the arguments for the operations are missing. For an example on how to place those items on the UML graph, click on the operation inputName. Next click on the button labeled: Properties. When you do, you should get a dialog box like the following:
When you do this the following dialog box appears:
file:///D|/1/final/BBL0013.html (7 von 9) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
Next click in the blank in the column below the word: inputName in the column headed: Parameter. Type in the word: name and select as the Type: C#::string. When you do this step, you should see the following:
For inputOwner enter owner, inputAddress enter address, inputCity enter city, inputState enter state and for inputZip enter zip. For each of these operations, you should select for the Type: C#::string. After you have done this process for each method, notice that there is a column labeled: Kind and that each argument has by default the word: in. This term means that the argument is moving data into the method's body using this parameter. Other options for Kind are: out and in/out. To complete this process, click the OK button. In the graph is now the UML diagram for the class Company and it should appear like the following. Once the graphic is completed save it as Company.VSD and then as Company.jpg:
file:///D|/1/final/BBL0013.html (8 von 9) [01.12.2007 04:47:44]
Using Visio to Create UML Charts
Now do the same thing for the class Date and the class Sales from the Lecture 1 design example. Do these two classes on the same graph. The difference between this graph and the previous one is that the class Sales is derived from the class Date. Therefore you would need to connect the two class UML diagrams together with an arrow pointing from Sales to Date and the name of the bottom class should be: Sales:Date as in the following graph:
Save this UML diagram as: Date_Sales.VSD and then as: Date_Sales.jpg. Remember to always save in both file types. The .VSD type may be used if it is necessary to redo a Visio graphic.
file:///D|/1/final/BBL0013.html (9 von 9) [01.12.2007 04:47:44]
Lecture 2: C# Language Fundamentals
Lecture 2: C# Language Fundamentals A C++ Program Compared to a C# Program NOTE: As you read these notes, have Visual Studio .NET 2005 open so that you can compile and run the programs listed to help you to understand what the lecture is trying to say. In addition store the projects onto your USB drive. That way you will be able to take the examples with you. Note: This course is only an introduction to Visual Studio .NET 2005 and only an introduction to C#. Both contain a lot of features that are not possible to cover in the time allotted to this course.
Structure of a C++ Program It is assumed that you know how to program in unmanaged C++ with Visual Studio .NET 2005. Therefore let's first consider a simple C++ program and then compare it to a simple C# program. The following program: hello1.cpp is a simple unmanaged C++ console program: // program_id: hello1.cpp // written_by: don voils // date_written: 12/11/2006 // description: This is a simple C++ console program that // demonstrates program output to the screen // #include void main() { std::cout << "Hello students!!" << std::endl; }
In the C++ program above the #include is required because the header file iostream contains many definitions including namespaces and classes that are needed for this and other C++ programs. Each C++ program requires at least one main() in one of its source files. This function is the entry point into the program. Recall that there are several different forms of this function. Next note std::cout and std::endl. The std is a namespace defined in the header file iostream. The constructs cout and endl are objects and << is an operator of the class ostream that is defined in the header iostream (If the program was using input, the object cin and >> an operator of the class istream would have been used. These constructs are also defined in the header iostream.) Recall that namespaces are blocks of code that are defined in the program usually in header files like iostream. These blocks of code contain multiple definitions. When using namespaces, it is possible to have multiply defined variables, objects, functions and other constructs in a program with the same name. By specifying the namespace's name when utilizing the constructs, the program is able to distinguish which is being utilized. The scope specification operator: (::) is used to connect the namespace with the construct that is defined in the namespace.
Structure of a C# Program Create a Visual Studio .NET C++ console project that contains the program code in hello1.cpp. Compile and run it to refresh your memory about these C++ features. Since C++ is a prerequisite of this course, it is being assumed that no discussion of how to create this C++ console program is required. Next let's consider a similar simple C# console program: hello2.cs (Notice the different file extension from the C++ program above.)
file:///D|/1/final/BBL0014.html (1 von 8) [01.12.2007 04:47:46]
Lecture 2: C# Language Fundamentals
// program_id: hello2.cs // written_by: don voils // date_written: 12/11/2006 // description: This is a simple C# console program that // demonstrates program output to the screen // class Hello { static void Main() { System.Console.WriteLine("Hello students!!"); } }
Notice the similarities and differences with the C++ console program above. First note that the program consists of the definition of the class Hello. In fact every C# program is based upon a class similar to Hello. Next notice that the } at the end of this class' definition is not followed by a semi-colon. Next instead of the function: main() there is the function: Main(). This function tells the CLR where to begin with executing the code. As with main(), the function Main() has several different formats including either void or int output. It also has additional arguments than just the void as indicated in the example above. At least one file of the project must have a Main() in a class within the file. Next observe that to the left of the header of Main() is the keyword static. Since this function is being defined inside of the class Hello, Main() is therefore a static class method. Recall from C++ that the modifier static before the definition of a method enables the method Main() to be called by the class Hello without the need to define an object of the class. The same is also true in C#. Notice inside of the method Main() is the statement: System.Console.WriteLine("Hello students!!");
(Note that the statement above ends in a semi-colon.) The construct System in this statement is the name of a namespace similar to std in the C++ program above. Console is the name of one of the many classes defined in the namespace System that are a part of the .NET Framework Class Library (FCL). The FCL contains many different files called assemblies. Some assemblies require that they be added to the program. However the assembly which contains the namespace: System and therefore the class Console is an integral part of the IDE. Under certain circumstances this class will be denoted as: System.Console to notify the compiler in which assembly it is contained. The name System.Console is what is called the fully qualified class name of the class Console. In C++ when the keyword using precedes the namespace std, then the fully qualified names for cin and cout are not required. The same is true in C#. When the keyword using precedes System, then only the class name: Console is needed. (While this is what appears in the code, the compiler actually sees the fully qualified name.) Note: While it may appear that fully qualified names are not needed, that may not be the case. For example if one or more namespaces in a project have a class with the same name, then the fully qualified name may be necessary so that the compiler knows which class is being referred to. To overcome this problem, it is possible to use a technique similar to typedef in C++ to produce an alias. For example suppose that the namespaces BankClasses and OfficeClasses both have a class Account. What could be done would be to define an alias for each of these classes in the program like the following: using BankAccount = BankClasses.Account; using OfficeAccount = OfficeClasses.Account;
file:///D|/1/final/BBL0014.html (2 von 8) [01.12.2007 04:47:46]
Lecture 2: C# Language Fundamentals
Placing these statements at the top of the program would enable the program to make calls to the pseudo classes: BankAccount and OfficeAccount. In addition to the class Console defined in the namespace System, this namespace also contains many subnamespaces. For example System contains the subnamespaces: Collections, Configuration, Data and so forth. In addition the subnamespace: Collections has its own subnamespaces. When these namespaces are required, they will be called like System is being called in these examples. This topic will be discussed in more detail in later lectures. The function: WriteLine() is a static method of the class Console. Since WriteLine() is a static method, it is being called by the name of the class: System.Console rather than by an object of the class. Note further that instead of using the scope specifier operator (::) as in C++, these constructs are joined by the dot operator (.). The method WriteLine() sends its argument(s) to the screen followed by a line feed moving the cursor to the next line. If you do not want a line feed at the end, you can use the static Console method: Write() which sends data to the console but once the data appears, the cursor remains on the same line as the last character displayed. Note: The operator (::) may still be used in C# instead of the operator (.) as was done above. The main use of this operator is when the program may have multiple classes with the same name. While this operator is also available in C#, it will not be used in this course. The static Console method: WriteLine() provides a convenient way to output various types of data. WriteLine() will automatically convert numeric values from their internal, binary format into strings representing the numeric values. C# also provides a reverse IO method that reads and converts strings into the internal, binary format for numeric data. To do this, the static method Parse() is defined for all-builtin numeric types. What is necessary is to then use the static Console method ReadLine() to receive the keyboard input and then the output of this method can be used as a parameter for the Parse() method of the data type. The static method: ReadLine() outputs a line feed. Note: As with C++, the symbols: // and /* with */ can be used to comment out text from the program. C# has an additional comment symbol: ///. This is the XML comment symbol.
Creating a C# Console Project Open up Visual Studio .NET 2005 and create a C# console project. When you open Visual Studio .NET 2005 for a new project, you should see the following screen:
Click on Visual C# project under Project Types and then click on Console Application under Visual Studio
file:///D|/1/final/BBL0014.html (3 von 8) [01.12.2007 04:47:46]
Lecture 2: C# Language Fundamentals
installed templates. Enter hello2 in the Name: blank. Next click the OK button. (Note: In a classroom or in a University lab, select the Browse button and choose to store the project on your USB drive.) When the project opens, you should see something like the following (If the Solution Explorer does not appear on the left, click on View on the menu bar and select Solution Explorer. Then click the pin on the right hand side so that Solution Explorer is continuously visible:
Looking at the Solution Explorer on the left side (Note: The setup that you are using may have the Solution Explorer on the right side instead), notice that the name of the C# program is Program.cs. Click on the name and change it to hello2.cs. Next notice that Visual Studio .NET has placed some code into the file: hello2.cs. Notice at the top of the program are the following statements: using System; using System.Collections.Generic; using System.Text;
The first of these permits the program to access the contents of the namespace: System which contains most of the basic types used in .NET applications. The second statement also permits the program to access a namespace that contains code which permits Generic collections. Generics are similar to templates in C++. The third statement adds a namespace that contains types including the ability to process strings. (Note: The bottom two using statements were not required before, only the using System; is required in the 2005 version.) Click the link to open the file: hello2.cs. When the file opens, do a CTRL-A (to block the text) followed by a CTRLC (to copy the blocked text to memory). Next click into the frame: hello2.cs. Do a CTRL-A followed by a CTRL-V (to paste the copied text). The code of the program hello2.cs should now appear as in the following:
file:///D|/1/final/BBL0014.html (4 von 8) [01.12.2007 04:47:46]
Lecture 2: C# Language Fundamentals
Click Build/Build Solution (or F7 or F6 depending on your installation) followed by Debug/Start without Debugging (or Ctrl+F5). When you do this, you should see: Hello students!!
appear on the screen. Next look at the folders and files for each of the programs: hello1.cpp and hello2.cs on your disk and observe the similarities and the differences. Recall that in C++, the code in hello1.cpp could be written without the use of std::. This can be done by placing the statement: using namespace std;
at the top of the program. When you do this, the program: hello1.cpp becomes the program: hello3.cpp as in the following: // program_id: hello1.cpp // written_by: don voils // date_written: 12/11/2005 // description: This is a simple C++ console program that // demonstrates program output to the screen // #include using namespace std; void main() { cout << "Hello students!!" << endl; }
Create a new project: hello3.cpp for this program, paste the code for this program into the new project, compile and run it. Notice that the output of the program does not appear any different than the program: hello1.cpp. As with C++ programs, it is also possible to simplify a C# program by placing a using statement at the top of the program. For example: hello2.cs can be changed to hello4.cs as in the following: // program_id: hello4.cs file:///D|/1/final/BBL0014.html (5 von 8) [01.12.2007 04:47:46]
Lecture 2: C# Language Fundamentals
// written_by: don voils // date_written: 12/11/2006 // description: This is a simple C# console program that // demonstrates program output to the screen // using System; class Hello { static void Main() { Console.WriteLine("Hello students!!"); } }
Notice that the keyword: namespace is not required between the using and System in C#. The same will be true when other namespaces are required. You might ask why you could not also get rid of the Console above as you got rid of the System. This is not possible because Console is the name of a class and not the name of a namespace. Further WriteLine() is a static method of the class Console and therefore must be called by the class name and the dot operator as was done in C++ (except of course the scope resolution operator was used in C++ instead of the dot operator.). The namespace: System is contained in the file: mscorlib.dll. (The .dll stands for "dynamic linked library"). Files like this are referred to in .NET as assemblies. An assembly is a collection of files that appear to the programmer to be a single DLL or EXE file. In .NET an assembly is a basic unit of reuse. In fact any .NET program you create could be called an assembly. There are several assemblies that are a part of the CLR. When programming in .NET, it may be necessary to add these assemblies to the project in order to use them. The mscorlib.dll assembly comes installed in .NET and does not require installation as may be required for other assemblies. Later in the lectures, files will be placed in a dynamic linked library that will then be added to other programs. Note: To assist the programmer in the alignment of code, the Visual Studio .NET IDE provides a command for automatic alignment. To activate this feature on your program, block the code to be realigned and the press: ctrl-k followed by ctrl-f. When this is used, the code will automatically align. Go into the project you just created for hello4.cs and move the lines around in a random manner. Then block the code followed by ctrl-k then ctrl-f. Notice how the IDE has adjusted the lines of code to a more acceptable format.
Visual Studio .NET C# Console Project Default When you request a C# project from Visual Studio .NET, several lines of code will be supplied automatically. They include: using System; using System.Collections.Generic; using System.Text;
which will make available these features of the namespace System to the program. Next there will also be a namespace supplied with the same name as the project both of which may be changed or eliminated entirely. There will also be the definition of a class usual with the name Program which may also be changed. This class' definition by default will include no data members and only one member function: Main(). Finally the Visual Studio .NET default will provide a copy of the function: Main() as the entry point into the program. This function may be included in any class within the program. The function Main() in C# has several forms as the C file:///D|/1/final/BBL0014.html (6 von 8) [01.12.2007 04:47:46]
Lecture 2: C# Language Fundamentals
++ main() does. The examples in these notes will always have the output be void however as with C++, it is possible to have an int output. Further, the examples in these notes will have a void signature even though it is possible to have a signature with an array of strings as the argument as in the following: static void Main(string[] args) { }
When you request that Visual Studio .NET create a C# project for you, the above Main() will be the default. In your homework or on a quiz you may use any of these forms of Main(). An additional modifier must be supplied for Main () and that is static. The reason for this modifier is that Main() is a method of the class Program and by providing Main() with a static modifier, it does not need to be called by an object of the class.
The Different Forms of Main() As with C++, C# has several different forms to Main(). They are the following: static int Main() { .... }
This form is used in the program when the program is to be designed to return values like error messages back to the operating system. static void Main(string[] args) { ..... }
This form is used if values are to be entered from the console prompt. static void Main() { .... }
This last form is used if the program is not to be designed to return values to the operating system. In most of the examples in this course, this form will be the one used. By definition Main() should always be static. By default Main() has an access modifier of private. If this function is to be shared outside of its class, then the access modifier needs to be public.
Running C# Programs If a client's computer does not have Visual Studio .NET 2005 installed on it, then the C# Console and Windows programs you develop may not run on their computer. The reason is that their computer may not contain Framework 2.0 (or a newer version). While this is true, it is possible to install it by going to the Microsoft web site and downloading the free program dotnetfx.exe. This problem does not occur for the web programs because they are translated into HTML and JavaScript which may be read by any Internet browser.
file:///D|/1/final/BBL0014.html (7 von 8) [01.12.2007 04:47:46]
Lecture 2: C# Language Fundamentals
file:///D|/1/final/BBL0014.html (8 von 8) [01.12.2007 04:47:46]
The C# Keywords, Escape Sequences and Built-in Data Types
The C# Keywords, Escape Sequences and Built-in Data Types C# Keywords The following is a list of most of the current C# keywords:
abstract
as
base
bool
break
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate
do
double
else
enum
event
explicit
extern
false
finally
fixed
float
for
foreach
goto
if
implicit
in
int
interface
internal
is
lock
long
namespace
new
null
object
operator
out
override
params
private
protected
public
readonly
ref
return
sbyte
sealed
short
sizeof
stackalloc
static
string
struct
switch
this
throw
true
try
typeof
uint
ulong
unchecked
unsafe
ushort
using
virtual
void
volatile
while
Open table as spreadsheet
Note: Since C# is a dynamic language, this list may be out of date. Notice that some of the above keywords are common to C++ but there are additions and deletions of the C++ keywords. (It is not necessary for you to memorize this table.) When a keyword is typed into the IDE, it turns blue to assist the programmer in determining whether the keyword was spelled correctly.
Escape Sequence Characters C# has the same escape sequence characters that you learned in your C++ class and they are:
Open table as spreadsheet Escape Sequence Character
Name Given to Character
\a
Bell
\b
Backspace
\f
Form feed
\n
Newline (linefeed/return depending on the system)
\r
Return
file:///D|/1/final/BBL0015.html (1 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
\t
Tab
\\
Backslash
\'
Single quotation mark
\"
Double quotation mark
These escape sequences may be used where ever a character is used. They are the same as those from C ++. (It is not necessary for you to memorize this table either.)
The escape sequence \b will cause the cursor to move to the left one position. The escape sequence \t will force a tab. The escape sequence \n will force a newline to appear below the current one. Sometimes it will be necessary to use a \r together with \n. The \r is a carriage return and the \n is a new line character. Together they would send the cursor to the next line and to the left margin. Recall that escape sequence characters may be used to format strings. For example to have a string to output a double quote like: ", the string to be output needs to have the escape character \". See format1.cs. The character @ can be used to eliminate the need for some escape sequences to have the extra \ before them. For example when storing the name of a file in the string variable theFile instead of the following: string theFile = "D:\\theFolder\\theSubFolder\\theFile.txt";
the following statement may be used (notice that some of the \ characters are removed from the above): string theFile = @"D:\theFolder\theSubFolder\theFile.txt";
Another use of the character @ can be to eliminate the need for additional escape characters like \n as in the following example: string theSentence = "To be or not to be \nthat is the question.";
could be written as the following (notice that the newline character is gone and that an Enter key was used instead): string theSentence = @"To be or not to be that is the question.";
See format2.cs.
C# Reference and Value Data Types C# as with C++ is a strongly typed language. By this is meant that the compiler will force the programmer to use a variable as defined. Variables in C# may be of a data type defined by programmer or they may be one of the builtin data types. However all data types whether they are built-in or programmer defined are derived from a built-in class called Object. All variables that are from the built-in data types, those created from enumerated data types or those created from structures are what are called value type variables. (As will be discussed later, the built-in data types are actually structures). Those variables that control the objects of classes are called reference type variables. All value type variables are stored in the stack. As will be discussed later in the lecture on classes, each class object will be referred to by using a variable called a reference and this reference will be stored on the stack. It will contain the address of the object to which it refers. The objects referred to by the reference type variables are stored on the heap.
file:///D|/1/final/BBL0015.html (2 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
Define a C# Value Type Instance To define a value type variable (also called an instance) of one of the built-in data types (as well as enumerated and structure data types) the following statement is used (to define reference types will be discussed in the lecture on classes): [access-modifier] theDataType theVariable;
The access-modifier may be: static, private, public or protected. Once a variable has been defined, it is possible as you move your cursor through the code to observe the data type of the variable. When placing the cursor over the variable, a Tool Tip will appear showing the data type of the variable. That is if theVariable appeared somewhere in the code after this definition, the Tool Tip would show that theVariable was of the data type: theDataType as shown in the following:
When naming a variable use names that are suggestive of what the variable is being used for. The name should always be in lower case for the first word and the first letter of each additional word should be in upper case with the remaining letters in lower case. Be very careful how you select names because VB does not make a distinction between upper and lower case. Since your programs may be shared in a .NET program with VB programs, this could cause a problem. Notice in these notes, the above statement is called a definition rather than a declaration as in some books. The distinction is that a variable is declared if the code only announces to the program that a particular variable name is being used in a particular way. A variable is defined if not only does the program provide a name for a place in memory but it also sets aside a unit of memory of the required size and then requires that this memory be used with the operators and functions defined on the specified memory. Unlike C++, C# does not allow global variables. All variable must be defined either in a class as a data member or in a class' method as a local variable. Those variables that are static and are defined in the main program class can act like global variables in C++ in that they can be accessible anywhere in the program class.
C# Built-in Data Types As with C++, C# has several built-in data types all of which are derived from the class System.Object to include the following:
file:///D|/1/final/BBL0015.html (3 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
The class Object has a number of useful methods including the following that are inherited by the system and the programmer data types:
Open table as spreadsheet Method
Description
Equals()
Evaluates whether two objects are equivalent
GetHashCode()
Allows objects to provide their own hash function for use with int collections.
GetType()
Provides access to the type of the instance.
ToString()
Provides a string representation of the instance.
Finalize()
Cleans up non memory resources
MemberwiseClone ()
Creates copies of the object but should never be implemented.
The keyword object is an alias for System.Object. Therefore when referring to System.Object, the word object may be used. If the program was preceded with the following:
file:///D|/1/final/BBL0015.html (4 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
using System;
then the word Object could be used instead. A reference to object may be used to access any object of any class or variable of a value type. Notice in the graphic above that both string and array are reference types. In fact both of these are classes and will be discussed further later in the notes. The following is the C# system value data type descriptions:
Open table as spreadsheet Data Type (short hand name)
Data Type
Size (in bytes)
.NET Data Type
Literal Designator
Description
[***]
byte
System. Byte
1
Byte
Unsigned (values 0–255)
char
System. Char
2
Char
Unicode characters
bool
System. Boolean
1
Boolean
* true or false [ ]
sbyte
System‥ Sbyte
1
Sbyte
Signed (values -128 to 127)
short
System. Int16
2
Int16
Signed (short) (values 32,768 to 32,767)
ushort
System. UInt16
2
Uint16
Unsigned(short)(values 0 to 65,535)
int
System. Int32
4
Int32
Signed integer values between -2,147,483,647 and 2,147,483,647
uint
System. UInt32
4
Uint32
U or u
Unsigned integer values between 0 and 4,294,967,295
float
System. Single
4
Single
F or f
Floating point number. Holds the values from * approximately +/-1.5[ ]10-45 *
to approximate +/- 3.4 [ ] 10 +38 with 7 significant figures. [**]
double
System. Double
8
Double
D or d
double-precision floating point, holds the values from * approximately +/-5.0[ ]10-324 *
to approximately +/- 1.7[ ]10 +308 with 15–16 significant ** figures.[ ]
file:///D|/1/final/BBL0015.html (5 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
decimal
System. Decimal
12
Decimal
M or m
Fixed-precision up to 28 digits and the position of the decimal point. This is typically used in financial ** calculations. [ ]
long
System. Int64
8
Int64
L or l
Signed integers ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
ulong
System. UInt53
8
Uint64
UL or ul
Unsigned integers ranging from 0 to 0xffffffffffffffff
string
System. Sting
16 bits per character
String
Literals are enclosed in quotation marks
Note: The character data to be more international uses the Unicode specifications. The real number data uses the IEEE 754 standard. [***]When
manipulating variables of the built-in data types, methods will be used and the .NET Data Type will be used to call the data type methods. One of these methods is Parse(). It converts a string into the data .NET Data Type which called the method Parse(). e.g. Double.Parse("123.43") would convert the enclosed string to the double: 123.43.
[*]Notice
that C# only has two values for a bool variable: true and false. Unlike C and C++, numbers are not allowed as values for bool in C#. [**]Be
aware that real number calculations are only approximate. This is especially important when using selection or repetition
What should be noted from the above table, is that C# has a greater variety of data types that cover a greater size for the data values than C++ does. As a result, C# may handle larger and smaller numbers more accurately than C+ + does. Note: The data type decimal which has a smaller range that a double, is more accurate than a double. Therefore when selecting a data type of monetary representation, it is recommended that decimal should be used rather than float or double
Definite Assignment Rule In C++ it was possible to define a variable and use it without first initializing it. This caused problems because the memory location could contain bytes that did not translate correctly. C# avoids this problem by not permitting a program to be compiled unless each defined variable is initialized prior to its use. This is called the Definite Assignment Rule. For example the following two lines of code would not compile: int theNumber; Console.Write(theNumber);
Compile and run the program: DefiniteAssignmentRule.cs Observe that the program will not compile. This program contains the statements listed above. If the lines above are commented out and those lines (similar to these) are uncommented, then the program will compile. (While this is true, there are some automatic initializations of variables that will be discussed later.)
file:///D|/1/final/BBL0015.html (6 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
Explicit and Implicit Type Conversion As with C++, it is possible to have either implicit or explicit type casting. Implicit type casting means that a variable's contents may be passed to another variable with a larger memory unit without the need for any special code. However, explicit type casting is achieved by the function: (datatype) where datatype is the type being cast to. This is the same symbolism as is used in C and one of the methods that is used in C++. These features of C# are contained in the class: System.Convert. When placing the contents of a variable like a short into a larger variable like an int, the conversion is implicit since there is no data loss. It is implicit since there is no required action by the programmer. For example: short theSmaller = 7; int theLarger = theSmaller;
However, if the reverse was attempted i.e.: int theLarger = 700; short theSmaller = theLarger;
then the code above will not compile although the value would fit into the variable theSmaller. To overcome this problem, an explicit type casting must be used like the following: int theLarger = 700; short theSmaller = (short) theLarger;
Data Type Conversion Using the Class Convert In addition to the type conversion mentioned above, it is also possible to use the methods of the class System. Convert. No additional using statement is required for this class. Some of the methods for this class are:
Open table as spreadsheet Method
Description
ToBoolean()
Provides 18 different methods for converting to a bool.
ToByte()
Provides 18 different methods for converting to a byte.
ToChar()
Provides 18 different methods for converting to a char.
ToDateTime ()
Provides 18 different methods for converting to a DateTime object.
ToDecimal()
Provides 18 different methods for converting to a decimal.
ToDouble()
Provides 18 different methods for converting to a double.
ToInt16()
Provides 19 different methods for converting to a int.
ToInt32()
Provides 19 different methods for converting to a int.
ToInt64()
Provides 19 different methods for converting to a int.
ToString()
Provides 36 different methods for converting to a string.
For some examples of these System.Convert methods see Conversion.cs.
file:///D|/1/final/BBL0015.html (7 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
The Data Type Operators C# has some of the same unary, binary and binary assignment operators as C++ does. That is: ●
the operators: +, -, /, * and % are defined on the integral data types.
●
the operators: +, -, / and * are defined on the real data types.
●
the operators: +=, -=, /= and */ are defined on both the integral data types and the real data types.
●
the operators: ++ and -- both pre and post are defined on both the integral data types and the real data types.
●
the operators: &&, || and ! are defined on the Boolean data type.
●
the operators: <, <=. >, >=, == and != are the relational operators that are defined on expressions but return a Boolean.
●
the operators: + is a binary operation on variables of the string data type
●
the operators: + is a binary operation where numbers may be added to strings.
Note: C# has in addition to the Boolean operators: &&, || and !, the Boolean operators: &, | and ^. The difference between & and &&, is that with & both operands are checked regardless of the Boolean value of the left operand and if there is any code in the right operand like the increment operator, the code is executed. There is the same difference between the operator || and the operator |. That is both operands in a statement with | are checked regardless of the Boolean value for the left most operand. The Boolean operator ^ is the exclusive or. By this is meant that the Boolean A ^ B is true only if one of the booleans A and B is true. If they are both true, then the compound Boolean statement: A ^ B is false. See booleanOperators.cs As with C++, in C# one must be careful about the order of precedence of these operators. The best solution is to enclose multiple operators in parenthesis to ensure the order desired is followed.
The String Data Type In addition to the numeric system data types listed above, C# also has a string data type. To define a variable to be of a string data type a statement like the following must be used: string theName;
As with C++, a string literal is created by placing a collection of characters inside of a pair of double quotes as in the following: string theName = "George Washington";
As with C++, C# strings may be added. As a result of the following code: string firstName = "George"; string lastName = "Washington"; string theName = firstName + " " + lastName;
the sting variable: theName will contain the string: "George Washington". The following code would add 5 to "Item":
file:///D|/1/final/BBL0015.html (8 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
string theItem = "Item" + 5;
to store the string: "Item5" in theItem. The following code would add 56.75 to "Item": string theItem = "Item" + 5 + 6.78;
and store the string: "Item56.78" in the string: theItem. See string1.cs. The following table lists some of the methods of the String Class
Open table as spreadsheet Member
Description
Length
This attribute returns the length of the string.
Contains()
This method is used to determine if the current string object contains a specified string.
Compare()
This method is used to compare two strings to determine whether the first is before (will return a 1 in this case), after (will return a -1 in this case) or the same (will return a 0 in this case) as the other string.
Format()
This static method is used to format a string literal using other primitives.
Insert()
This method is used to receive a copy of the current string that contains newly inserted string data.
PadLeft()
These methods return copies of the current string that has been padded with specific data.
PadRight() Remove() Replace()
These methods receive a copy of a string with modifications i.e. characters removed or replaced.
Substring()
This method returns a string that represents a substring of the current string.
ToCharArray ()
This method returns a character array representing the current string.
ToUpper()
These methods create a copy of a given string in upper or lowercase.
ToLower() Additional properties of the String class will be discussed later in the lectures.
Constants C# has three types of constants: literals, symbolic constants and enumerations (enumerations will be discussed later in the notes). For example in the following statement: double theAmount = 45.67;
The value: 45.67 is a literal constant.
file:///D|/1/final/BBL0015.html (9 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
A symbolic constant may be created by a statement like the following: const double PI = 3.14159;
Symbolic constants were studied in C++ and are variables that are assigned a value when they are defined but the variable may not change its original value during the program. This was also achieved C++ by using the modifier const. In C# the const modifier may only be used for value types and not for reference types.
Boxing and Unboxing of Value Types As mentioned above, all data types both built-in and programmer defined are derived from the built-in class Object. There are times in which a programmer wants to treat a variable that is a value type as if it is an instance of Object. In this case the programmer needs to treat the variable as a reference type rather than a value type since the instances of Object are reference types. That is there is a need to store the variable's data on the heap rather than store the data on the stack. The process of converting the value type variable to a reference type variable is called boxing. The process of converting back from a reference type to a value type is called unboxing. The process of boxing and unboxing may either be implicit (i.e. it happens without explicit action by the programmer) or there may be explicit boxing or explicit unboxing. One of the needs of boxing can be to use the Console method: WriteLine() as in the following: int theNumber = 344; Console.WriteLine("The number is {0}", theNumber);
In the above statement, WriteLine() requires a reference to an instance of Object. Since the data type Integer is derived from Object, the Integer instance: theNumber may be used as if it is an instance of Object. This is accomplished without the need for the programmer to write any additional code. That is, this is an example of implicit boxing. What is done in this case is that the method: ToString() is called automatically to convert theNumber to a string. See implicitBoxing.cs There may be times later to covert variables like theNumber to objects of the class Object through specific code. In this case what is needed is explicit boxing as in the following example: int theNumber = 344; object theObject = theNumber;
The first statement stores 344 on the stack. The second statement stores 344 on the heap which is a copy of what is being stored on the stack.
file:///D|/1/final/BBL0015.html (10 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
This is called explicit boxing. See explicitBoxing1.cs. Now if the following statement occurred in the same program, then the value on the stack does not change but the value on the heap does: theObject = 356;
See explicitBoxing2.cs. Now suppose that the following statement occurred: int anotherNumber = theObject;
If this statement followed the previous statements, an error would occur. See explicitBoxing3.cs.
file:///D|/1/final/BBL0015.html (11 von 12) [01.12.2007 04:47:49]
The C# Keywords, Escape Sequences and Built-in Data Types
However if the following was used instead: int anotherNumber = (int)theObject;
This code would be acceptable. This last statement would place the value 356 into the Stack associated with anotherNumber. This process is called explicit unboxing. However this will only work if the value stored in theObject is an int. See explicitBoxing4.cs. In order for unboxing to work, the data types must match. For example if the following code was included in the program above, an error would occur: float yetAnother = (float) theObject;
In this case an System.Invalid Cast Exception would be thrown because the cast to a float is not valid. See explicitBoxing5.cs. Excessive use of boxing and unboxing may put an excessive load on the system because of all of the checking for proper types and whether an exception needs to be called. Rather than using boxing and unboxing, you should consider generics which will be discussed later. More will be discussed about the concepts boxing and unbaoxing later in the notes. Note: C# also supports the C++ style of pointers but they are rarely used. When they are used, this would be done outside of the .NET environment because the code with pointers must be unmanaged code. This topic will not be discussed in this course.
file:///D|/1/final/BBL0015.html (12 von 12) [01.12.2007 04:47:49]
Console Input and Output
Console Input and Output Console Output In a previous example, console output was illustrated using the Console method WriteLine() as in the following example (See theOutput1.cs): using System; class theProgram { static void Main() { Console.WriteLine("This is an output example."); } }
To refresh your memory as to how C# console programs work, compile and run the program above. After noting in the previous section that C# has several different data types, the question should be: How is it possible to output the data contained in a variable of any system data type? To do this, additional arguments must be provided for the method WriteLine() and the formatting symbol {theItemPosition} must be included in the string argument one for each value to be output. The theItemPosition is an integer that indicates which argument is to be placed where (other arguments in addition to theItemPosition will be discussed below). The values of these arguments are like a C++ array so that the first one listed begins with 0. For example in the following program (See theOutput2.cs): using System; class theProgram { static void Main() { double theHourlyRate = 25.45; double theHoursWorked = 45; double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}", theHourlyRate); Console.WriteLine("The hours worked is: {0}", theHoursWorked); Console.WriteLine("The gross pay is: ${0}\n", theGrossPay); } }
Notice that the theItemPosition in each of the WriteLine() statements above is 0. Compile and run this program to observe how this feature of WriteLine() works. While the program above solved the question of how to output each variable with its own Console method WriteLine(), it would be desirable to be able to output the values of as many different variables all in one Writeline (). This can be done using the formatting symbol: {theItemPosition} for each numeric argument as the following program illustrates: (See theOutput3.cs)
file:///D|/1/final/BBL0016.html (1 von 9) [01.12.2007 04:47:51]
Console Input and Output
using System; class theProgram { static void Main() { double theHourlyRate = 25.45; double theHoursWorked = 45; double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: " + "${0}\nThe hours worked is: {1}" + "\nThe gross pay is: ${2}\n", theHourlyRate,theHoursWorked, theGrossPay); } }
The two examples above demonstrate that there can be a {theItemPosition} that appears in the string argument for WriteLine() where theItemPosition is some integer from 0 to one less than the number of variables being output. Then this string is followed by each variable being output separating them with a comma as can be observed in the example above.
Console (Keyboard) Input To be useful, the C# console program above needs to have a way to input from the keyboard values that could be stored into the doubles: theHourlyRate and theHoursWorked in the previous program. To do this, the program can use the Console method: ReadLine(). This method is static and is therefore called by the class: Console. The method: ReadLine() has no arguments and has a string for output. (Notice that this method solves the problem in C++ with numeric and string input.) The ReadLine() then receives the value into a string variable theRate as in the following: string theRate; Console.WriteLine("What was the hourly rate? "); theRate = Console.ReadLine();
Note: In addition to the input method: ReadLine(), the Console class has the input method: Read(). The difference is that Read() inputs a single character while ReadLine() inputs a string. Next the string data stored in theRate needs to be stored into a double variable: theHourlyRate. This can be done by converting the string to a double with the method Parse() which in this case would be a method of the Double structure. This would be carried out as in the following statement: double theHourlyRate = Double.Parse(theRate);
The program theInput1.cs is a modification of theOutput3.cs above that implements these changes: using System; class theProgram { static void Main() { // Since the input is a string the // following variables are required to // receive the values input.
file:///D|/1/final/BBL0016.html (2 von 9) [01.12.2007 04:47:51]
Console Input and Output
// string theRate; string theHours; // The doubles required for the calculations // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // Console.WriteLine("What was the hourly rate? "); theRate = Console.ReadLine(); // The hours worked is requested and received. // Console.WriteLine("How many hours did the " + "employee work? "); theHours = Console.ReadLine(); // The strings are parsed to doubles. // theHourlyRate = Double.Parse(theRate); theHoursWorked = Double.Parse(theHours); double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}\nThe " + "hours worked is: {1} \nThe gross pay is: ${2}\n", theHourlyRate,theHoursWorked, theGrossPay); } }
To convert from a string to one of the other system data types look at the .NET Type column in the table above for the data type being converted to.
Formatting Console Output The above program does not appear as attractive as would be desired. That is, the request for each item was on a different line than where the value was entered. It would be better if they were on the same line. This can be accomplished by using the Console method: Write() which is similar to WriteLine() except that no line feed is output after the string argument is output. For example the above program could have been written as the following (See theInput2.cs) using System; class theProgram { static void Main() { // Since the input is a string the // following variables are required to // receive the values input. // string theRate; string theHours;
file:///D|/1/final/BBL0016.html (3 von 9) [01.12.2007 04:47:51]
Console Input and Output
// The doubles required for the calculations // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theRate = Console.ReadLine(); // The hours worked is requested and received. // Console.WriteLine("How many hours did the employee " + "work? "); theHours = Console.ReadLine(); // The strings are parsed to doubles. // theHourlyRate = Double.Parse(theRate); theHoursWorked = Double.Parse(theHours); double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}\nThe hours " + " worked is: {1} " + "\nThe gross pay is: ${2}\n", theHourlyRate,theHoursWorked, theGrossPay); } }
It is also possible to modify the program above and eliminate the need for the string variables by imbedding the ReadLine() method inside of the Parse() method as in the following: (See theInput3.cs) // program_id theInput3.cs // written_by don voils // date_written 12/12/2006 // description This program demonstrates how to input and // output the data using the Parse() method // to convert from a string to a double and then // output use the Console method Write(). // The ReadLine() method is embedded inside of // the Parse() method to eliminate the need for // any additional string variables to receive the // input from ReadLine(). // using System; class theProgram { static void Main() { // The doubles required for the calculations // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received.
file:///D|/1/final/BBL0016.html (4 von 9) [01.12.2007 04:47:51]
Console Input and Output
// Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine()); // The hours worked is requested and received. // Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine()); double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}\nThe " + "hours worked is: {1} \nThe gross " + "pay is: ${2}\n", theHourlyRate,theHoursWorked, theGrossPay); } }
The above examples dealt with input and output of numeric data. How about a program that would input and output string data? The following program achieves this objective: (See theInput4.cs) // program_id theInput4.cs // written_by don voils // date_written 12/12/2006 // description This program demonstrates how to input and // output the string data. // using System; class theProgram { static void Main() { string firstName; string lastName; string theName; Console.Write("What is your first name? "); firstName = Console.ReadLine(); Console.Write("What is your last name? "); lastName = Console.ReadLine(); theName = firstName + " " + lastName; Console.WriteLine("\nHello {0}.\n\nDid you say your " + "first name was: {1}\nand that your " + "last name was: {2}? \n", theName,firstName,lastName); } }
There is still something missing in the examples above. In the program: Input3.cs the output data was not formatted in a manner consistent with the way our culture displays monetary amounts. However this can be overcome by formatting the output string using the String method Format() as in the following program: (See theInput5.cs) file:///D|/1/final/BBL0016.html (5 von 9) [01.12.2007 04:47:51]
Console Input and Output
// program_id theInput5.cs // written_by don voils // date_written 12/12/2006 // description This program demonstrates how to // output the data using the String method Format() // to convert from a string to a monetary format. // using System; class theProgram { static void Main() { // The doubles required for the calculations // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine()); // The hours worked is requested and received. Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine()); double theGrossPay = theHourlyRate * theHoursWorked; string theOutput = String.Format("\nThe hourly rate is: " + "{0:c}\nThe hours " + " worked is: {1:n} \n"+ "The gross pay is: {2:c}\n", theHourlyRate,theHoursWorked, theGrossPay); Console.WriteLine(theOutput); } }
Notice in the program above, the modifications of the format symbol: {theItem} to include the type of formatting to perform and possibly the number of decimal places to display. That is if theItem is specifying the format for an number then theItem:formatCode would format the numeric variable using the formatCode. The formatCode contains a letter and possibly followed by 2 or more digits that would specify the number of digits to the right of the radix point. The codes that may be used are indicated in the following table:
Open table as spreadsheet Format Code
Description
C or c
Formats the string as currency. Precedes the number with an appropriate currency symbol ($ in the US). Separates with an appropriate separator character (comma in the US) and sets the number of decimal places to two by default but may be changed by placing a number after which would represent the number of decimal places.
D or d
Formats the string as a decimal. Displays the number as an integer
file:///D|/1/final/BBL0016.html (6 von 9) [01.12.2007 04:47:51]
Console Input and Output
N or n
Formats the string with commas and two decimal places by default but but may be changed by placing a number after which would represent the number of decimal places.
E or e
Formats the number using scientific notation with the default of six decimal places but may be changed by placing a number after which would represent the number of decimal places.
F or f
Formats the string with a fixed number of decimal places with two by default but may be changed by placing a number after which would represent the number of decimal places.
G or g
General which can be either E or F
X or x
Formats the string as hexadecimal with the hex characters are in upper case when the captial X is used and they are in lower case when the lower case x is used.
Remember that each of these format codes may be followed by an integer. For example a program could have the following format code: {0:c3}. What this would do would be to format the associated number to appear as currency but with three digits to the right of the radix point rather than the traditional two. In addition if the format code was c and there were more that three digits to the left of the decimal point, a comma would appear every third digit as is traditional in addition to the $ sign. Further if the number is negative, then parentheses will appear around the number. For example the following would show: ($6,523.33) as the numeric output of the code: double theBalance = -6523.33; Console.WriteLine("The balance of the account is: {0:c}\n\n", theBalance);
As well as formatting for dollar amounts, it is also possible to format for percentages as well. By placing a format code like the following: {0:0.00%) either in a Write(), WriteLine() or a Format(), the value that is output will be multiplied by 100 followed by a % sign to achieve the correct appearance for percentage output. This formatting will occur regardless of whether the number is positive or negative. The formatting may be accomplished within Write() and WriteLine() or the formatting may be accomplished using the static string method: Format() as in the following: string theOutput = string.Format("The interest earned by the" + " account is: {0:0.00%}\n\n", theEarning); Console.WriteLine(theOutput);
For example see format3.cs. Additional formatting may be provided by using # and 0 in the formatting string. The # would be replaced with a blank if the represented number had no digit in that place. The 0 would be replaced with a 0 if the represented number had no digit in that place otherwise the digit for that position would appear. For example: "$#,##0.00" would output the $ in all cases, a comma if required, blanks if there is no digit where the # appears and 0 when no digit appears where the 0's appear in the formatting string. It is also possible to provide formatting that would select the first format for positive number, the second for negative numbers and the third for zero values as in the following format string: "{0:$#,##0.00;($#,##0.00); zero balance}"
For example of this formatting see format4.cs. In addition to formatting with respect to the type of data and the number of digits to the right of the radix point, it is file:///D|/1/final/BBL0016.html (7 von 9) [01.12.2007 04:47:51]
Console Input and Output
also possible to specify the width of the output. For example, if you wanted the second variable to be a number that is right justified, to be in currency format and to take up 7 positions, then the output could be the following: Console.WriteLine("The number is {0,7:c3}",theVariable);
For an example see input6.cs. If you wanted the output to be left justified, then a negative value could be used for the width number as in the following: Console.WriteLine("The name is {0,-15},theName);
This would output the contents of theName in a column that is 15 characters wide and it would be left justified. There will be additional methods of formatting output discussed in later lectures. The same type of Console formatting may also be used when programming in Windows GUI. Note: In each of the examples above each formatting theItem was different and went from 0 on the left to higher numbers on the right. It is also possible to have a particular theItem appear more than once. e.g {0} could appear more than once in the formatted string. In this case the first variable being formatted would appear a second time.
Running a Program from the Executable In each of the examples so far you have compiled and run the program using Debug/Start without Debugging. When you use this approach, after the program ends it says: "Press any key to continue…". Using input6.cs, copy the program into a project, compile and run it. Next go to the project's debug folder and double click on the executable program. Notice that when the program gets to the last statement, the statement is displayed and then the program immediately closes without giving you a chance to observe the output. This can be fixed by using the Console's static method: ReadKey() as in the following: Console.ReadKey();
The program readkey.cs is the same program except this line is added at the end. Compile and run this program both from Debug/Start without Debugging and by double clicking on the executable in the debug folder. Notice how the program this time waits until the user presses a key. This works better when using the executable directly. The major reason for using ReadKey() is that it permits the programmer to use F7 (or F6 depending on your installation) to compile and then F5 to debug. Normally when the Debug option is used, the screen does not stop at the end. However if the Console method: ReadKey() is used at the end of the program, then the program execution will stop allowing the user to observe the program's output.
Clear Console Screen Another one of Console's static methods that you might find useful is Clear(). When the following line of code appears in a program: Console.Clear();
The console's screen buffer is cleared and the screen becomes blank.
Additional Console Class Members
file:///D|/1/final/BBL0016.html (8 von 9) [01.12.2007 04:47:51]
Console Input and Output
The Console class has additional members in addition to the ones listed above. Some of the more interesting ones are:
Open table as spreadsheet Member
Meaning
BackgroundColor
Permits the changing of the console's background color.
ForegroundColor
Permits the changing of the console's foreground color.
Title
Permits the presentation of text on the menu bar.
The two color members are based upon the ConsoleColor enumerated data type. For example see color1.cs.
file:///D|/1/final/BBL0016.html (9 von 9) [01.12.2007 04:47:51]
Selection in C#
Selection in C# The selection options in C# are the same as those in C++. That is C# contains: ●
The if/else selection's general construct which is:
if(aBoolean) statement1 else statement2
See ifelse.cs ●
The null else selection's general construct which is:
if(aBoolean) statement1
See nullelse.cs ●
The nested if/else selection's general construct which is:
if(aBoolean1) if(aBoolean2) statement1 else statement2 else statement3
See nestedifelse.cs Note: Warning: Be very careful with using the == relational operator between two variables as in the following: if(firstNumber == secondNumber)
The problem with the above statement is the accuracy of numbers stored in C# variables. For example floats and doubles are only accurate to 8 digits and decimals are only accurate to 15 digits. While two numbers could be equivalent, they may not test that way because of the inaccuracy of the representation. ●
The relational operator selection's general construct which is:
outputType = (theBoolean) ?(ifOption):(elseOption);
See operator.cs ●
The switch/case selection's general construct which is:
file:///D|/1/final/BBL0017.html (1 von 2) [01.12.2007 04:47:51]
Selection in C#
switch(theValue) { case firstValue: statement1; break; case secondValue: statement2; break; .... ... default: statementn; break; }
The data type of theValue is any of the system primitive data types. Any case that has a statementn must have a break statement. If a case does not have a statementn, then it does not need a break and may fall through to the next case. See switch2.cs and notice that it will not compile. Notice in the switch selection that the break is used. One of the differences with C++ is that the last case of a switch() must have a break. See switch.cs. In fact, in C# at least one case must have a break or the program will not compile. switch3.cs. Now check out and compile: switch4.cs. In this example the last case is the default. In C++ this was not necessary. Instead of using a break it is also possible to use a return or a throw to exit the case of a switch. C# has also the goto command. Instead of using a break in a case of a switch, it is also possible to use a goto to exit a case. However, since I do not support the use of the goto, no examples of this construct will be demonstrated. The continue command is also implemented in C# and works as it does in C++.
file:///D|/1/final/BBL0017.html (2 von 2) [01.12.2007 04:47:51]
Repetition in C#
Repetition in C# With respect to C# and repetition, it has the same loops as C++ with one additional new loop the foreach(). The C# loops are:
The for() loop The for() loop's general construct is: for(initialization;boolean;control) statements
See for.cs. Note: if the initialization statement contains the definition of the controlling variables, then this variable's scope will only be the block of the for() statement. For example in the following for() the variable theNumber is only defined within the for() block.: for(int theNumber=0, theNumber<10;++theNumber) { ....... }
The while() loop The while() loop's general construct is: while(boolean) statements
See while.cs
The do/while() loop The do/while() loop's general construct is: do { statements }while(boolean);
See dowhile.cs
The foreach() loop The foreach() loop's general construct is: foreach(item in collection)
file:///D|/1/final/BBL0018.html (1 von 2) [01.12.2007 04:47:52]
Repetition in C#
statements
This type of loop was inherited from Visual Basic. It will be discussed in a later lecture.
file:///D|/1/final/BBL0018.html (2 von 2) [01.12.2007 04:47:52]
The System Class: Math
The System Class: Math In addition to the class Console, System also contains the class Math. This class has implicit access meaning that no additional using statement is required. This class contains many useful static methods to include those in the following table:
Open table as spreadsheet Method
Description
Abs(x)
returns the absolute value of x
Ceiling (x)
rounds x to the smallest integer not less than x and returns this value
Cos(x)
returns the cosine of x where x is in radians
Exp(x)
returns the exponential value ex
Floor(x)
rounds x to the largest integer not greater than x and returns this value
Log(x)
returns the natural logarithm of x (base e)
Max(x,y)
returns the larger value of x and y
Min(x,y)
returns the smaller value of x and y
Pow(x,y)
returns the value of x raised to the y power i.e. xy
Sin(x)
returns the trigonometric sine of x where x is in radians
Sqrt(x)
returns the square root of x
Tan(x)
returns the trigonometric tangent of x where x is in radians
In addition to the methods listed in the table above, the class Math also has two static fields: PI (3.14159265358979323846) and E. (2.718228184590452354) What you should note from the table above is that these methods are similar to the C++ functions contained in the header file cmath. For examples see math1.cs, math2.cs and math3.cs
file:///D|/1/final/BBL0019.html [01.12.2007 04:47:52]
The System Class Random
The System Class Random C# has a class: System.Random that can be used to generate random numbers. But what you must be aware of as with the random feature of the C++ function: rand() from the cstdlib library, is that the class: Random does not generate completely random numbers. Instead it generates pseudo random numbers. These random numbers are produced by the system supplying a seed value that is dependent of the day and the time of the operating system. As each tick of the clock changes, the seed changes to make the numbers more random. However if the requests for these numbers are too rapid, the system may not have incremented an additional tick. Therefore the numbers supplied for the request may in fact be the same and not "random". In addition to the constructor, Random has two methods: Next() and NextDouble(). The method Next() returns a pseudo random integer between 0 and the Int32.MaxValue value (2,147,483,647). The NextDouble() method returns a pseudo random double between 0 and 1. See random1.cs The method: Next() is an overloaded method one of which takes one integer as an argument and the other which takes two integers as arguments. For example: Next(10) would output a pseudo random integer between 0 and 9. While Next(0,25) returns a pseudo random integer between 0 and 24. In addition Next(24,58) returns a pseudo random integer from 24 to 57. See random2.cs The method: NextDouble() is one that returns a double from 0 up to 1. See random3.cs
file:///D|/1/final/BBL0020.html [01.12.2007 04:47:53]
The System Classes: DateTime and TimeSpan
The System Classes: DateTime and TimeSpan In business programming being able to handle dates and time is very important. However in C++ it was difficult to handle these values because it required the definition of elaborate classes to handle these important properties. When C# was defined, two classes were added to the language to assist the business programmer to handle these properties: DateTime and TimeSpan. Some of the members of the class: DateTime are described in the following table:
Open table as spreadsheet * Member [ ]
Description
DateTime()
There are seven different constructors that enable the programmer to place different values into the instance that is being defined.
Date()
Retrieves the date of the instance with the time value set to midnight.
Day
Extracts the day, month and year of the instance
Month Year DayOfWeek
Extracts the day of the week represented by the instance
DayOfYear
Extracts the day of the year represented by the instance
Hour
Extracts the hour, minute, second and millisecond represented by the instance
Minute Second Millisecond MaxValue
Extracts the maximum and the minimum DateTime value
MinValue Now Today
These are static data members of the class: DateTime representing the current date and time (Now) or the current date (Today).
Ticks
Retrieves the 100-nanosecond tick count for the instance
ToLongDateString()
Converts the current value of the DateTime instance to a string representation
ToLongTimeString() ToShortDateString() ToShortTimeString () ToString()
Retrieves the calling object in a string format.
[*]The
class DateTime contains additional members than the ones listed above. To observe the additional members go to Visual Studio .NET and define an instance of the class Next type the name of the instance followed by the dot operator and observe all of the additional members.
Some of the members of the class TimeSpan are described in the following table:
Open table as spreadsheet file:///D|/1/final/BBL0021.html (1 von 3) [01.12.2007 04:47:54]
The System Classes: DateTime and TimeSpan * Member [ ]
Description
TimeSpan()
There are four different constructors that permit the programmer to set the time of the instance being defined to different values.
Days
Extracts the whole number of days, hours, minutes, seconds or millisecond represented by the instance.
Hours Minutes Seconds Milliseconds TotalDays
Returns the total number of or fractional part of days, hours, minutes, second or milliseconds represented by the instance.
TotalHours TotalMinutes TotalSeconds TotalMilliseconds Ticks
Returns the value of the number of ticks of this instance.
Add()
Adds the specified TimeSpan instance to the calling instance.
Equals()
Indicates whether the specified TimeSpan instance is equal to the calling instance.
Subtract()
Subtracts the specified TimeSpan instance from the calling instance.
ToString()
Retrieves the calling object in a string format.
[*]The
class TimeSpan contains additional members than the ones listed above. To observe the additional member go to Visual Studio .NET and define an instance of the class. Next type the name of the instance followed by the dot operator and observe all of the additional members.
The following table lists some of the format specifiers that may be used by objects of DateTime with Write(), WriteLine() or Format().
Open table as spreadsheet Specifier
Description
D
Displays the current day of the month.
Dd
Displays the current day of the month, where values <10 have a leading zero.
Ddd
Displays the three-letter abbrevation of the name of the day of the week.
dddd(+)
Displays the full name of the day of the week represented by the given DateTime values.
G
Displays the era for a given DateTime (e.g. "AD")
H
Displays the hour, in the range 1 – 12
Hh
Displays the hour, in the range 1 – 12 where values < 10 have a leading zero.
H
Displays the hour in the range 0 – 23
HH
Displays the hour in the range 0 – 23 where values < 10 have a leading zero.
M
Displays the minutes, range 0 – 59
Mm
Displays the minutes, range 0 – 59 where values < 10 have a leading zero.
M
Displays the month as a value ranging from 1 – 12.
MM
Displays the month as a value ranging from 1 – 12 where values < 10 have a leading zero.
file:///D|/1/final/BBL0021.html (2 von 3) [01.12.2007 04:47:54]
The System Classes: DateTime and TimeSpan
MMM
Displays the three-character abbreviated name of the month.
MMMM
Displays the full name of the month.
S
Displays the number of seconds in range 0 – 59
ss(+)
Displays the number of seconds in the range 0 – 59 where values < 10 have a leading zero.
T
Displays the first character of the AM/PM indicator for the given time.
tt(+)
Displays the full AM/PM indicator for the given time.
y/yy/yyyy
Displays the year for the given time
z/zz/zzz (+)
Displays the timezone offset for the given time
Using some of the formatting from the above table, the following code could be used to output different forms of a date: DateTime theDay = DateTime.Now; Console.WriteLine(theDay.ToString()); Console.WriteLine(theDay.ToString("\n\ndddd MMMM dd, yyyy g")); Console.WriteLine("\n\n{0:MM/dd/yy hh:mm tt}",theDay); Console.WriteLine("\n\n{0:hh:mm:ss tt G\\M zz}",theDay);
For this example see datetime4.cs For additional examples of the classes DateTime and TimeSpan and their methods see: ●
datetime1.cs
●
datetime2.cs
●
datetime3.cs
●
timespan1.cs
file:///D|/1/final/BBL0021.html (3 von 3) [01.12.2007 04:47:54]
The System Class: Enum
The System Class: Enum In C# it is possible to create enumerations. They are slightly different from the C and C++ enumerated data types. The class Enum is contained in System and it is the base class for all C# enumerated data types. Its access is implicit meaning that no using or additional statements are required to get access to the class' properties. The following is the general construct of the definition of the C# enumerated data types: [attributes] [modifiers] enum theName [:base-type] { enumertor-list }
Notice the lack of a semicolon after the } as in C++. The meaning of most of the words enclosed in [ ] above will be discussed later. When defining enumerated data types, the definitions should be placed outside of the classes in the program but inside of a namespace. The enumerator-list may be any of the integral types except char. That is the base-type of the enumerator-list may be any one of following types: ●
byte
●
sbyte
●
short
●
ushort
●
int
●
uint
●
long
●
ulong
The following is an example of the definition of a C# enumerated data type: enum Rates{BOTTOM, NOTBOTTOM = 5, MIDDLE, AVERAGE = 10}
In this case the enumerator BOTTOM is implicitly assigned the value 0, NOTBOTTOM is explicitly assigned the value 5, MIDDLE is implicitly assigned the value 6 and AVERAGE is explicitly assigned the value 10. As with C++, the first enumerator has the value 0 by default unless the definition sets it to another value. Further each additional enumerator by default is one more than the enumerator to the left unless this default is overwritten. Note: The name of the enumerated data type begins with a capital letter and the remainder is lower case. If there would be more than one word, each additional word should begin with a capital letter. Notice also that the enumerators are all supposed to be capital letters. Other than the missing semicolon at the end, this looks very similar to the use of enumerated data types in C and C ++. But remember that there are several differences that will be noted in this lecture and in later ones as well. For example to access an enumerator the name of the enumerated data type must be used with the name of the enumerator separated by the dot operator as in:
file:///D|/1/final/BBL0022.html (1 von 3) [01.12.2007 04:47:55]
The System Class: Enum
Rates.BOTTOM
In the enumerated data type Rates used above, the base-type is Int32 by default. However Rates could have been defined as one of the following: enum Rates : byte {BOTTOM, NOTBOTTOM = 5, MIDDLE, AVERAGE = 10}
or enum Rates : long {BOTTOM, NOTBOTTOM = 5, MIDDLE, AVERAGE = 10}
While there are all of these types an enumerated data type may be based upone and while the default is int32, it is recommended that byte or sbyte be used if the number of enumerators is small. The resulting definition in this case would have much smaller memory requirements. For examples using Rates with selection statements see enum4.cs and enum5.cs. Note: In the examples so far, each enumerator has had a value higher than the enumerator to the left. However, this is not a requirement. In fact the enumerated data type Rates above could have been defined as the following: enum Rates:byte {BOTTOM = 6, NONBOTTOM = 8, MIDDLE = 1, AVERAGE = 3}
An enumerated data type based on byte as in the previous example rather than a long might be the preferred approach if it is to be used in a pocket PC or a .NET enabled cellular phone. Since enumerators are really integers, it is possible to use the arithmetic and the relational operators on them. See enum1.cs as an example that uses enumerators with a for() loop and a switch() . Notice that the for() loop does not require a type casting in the control statement as was required in C++. What is used is just the arithmetic operator +. While it is syntactically correct for two enumerators to have the same value, it is recommended that this not be done or for() loops and switch() expressions may not work as desired. One of the questions that might arise is that, since variables of an enumerated data type are integers and since it is possible to use the arithmetic operators on integers then what happens if the results of the operation are outside of the enumerators. The answer is that the result is just an integer. The next question is that since an enumerator is an integer, is it possible to use the * operator on enumerators. The answer to this question is that this is not syntactically possible. For example see enum10.cs. Remember that Enum is a class and that it has methods including the following:
Open table as spreadsheet Method
Meaning
Format()
Converts a value of a specified enumerated type to its equivalent string representation according to the specified format.
GetName()
Retrieves a name (or an array containing all names) for the constant in the specified enumeration that has the specified value.
GetNames()
file:///D|/1/final/BBL0022.html (2 von 3) [01.12.2007 04:47:55]
The System Class: Enum
GetUnderlyingType ()
Returns the underlying data type used to hold the values for a given enumeration.
GetValues()
Retrieves an array of the values of the constants in a specified enumeration.
IsDefined()
Returns an indication of whether a constant with a specified value exists in a specified enumeration.
Parse()
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
In addition to the Enum methods listed above, the class Convert can also be used on enumerated data type's variables like the following: Convert.ToString(theEnumVariable); Convert.ToInt32(theEnumVariable);
Check out the following examples that use some of the Enum methods above: ●
enum3.cs uses the method: ToString() to display the string name of the enumerated variable.
●
enum6.cs uses the method Format() to display the decimal and hexadecimal value of the enumerated variable.
Note: Although none of the enumerators in these examples used access modifiers, some programs require either public or internal to precede the definition of the enumerated data type. This will be observed later in the notes when a class is defined and one of the data members is an instance of an enumerated data type. In this case, the program would not compile until the access modifier public precedes the definition of the enumerated data type.
file:///D|/1/final/BBL0022.html (3 von 3) [01.12.2007 04:47:55]
Introduction to Windows Forms
Introduction to Windows Forms The purpose of this part of the lecture is to begin the study of programming using the Visual Studio .NET 2005 IDE to create a Graphics User Interface (GUI) rather than using the console approach as was done in the programs viewed above. In this course only the Windows GUI will be considered. Looking at programs that implement a Web GUI belong in another course. Some authors are suggesting that in future versions of Visual Studio .NET these two will be merged into one coding approach. To start this example, open the Visual Studio .NET 2005. Next select Project Types: Visual C# and Visual Studio installed templates: Windows Application. In addition, select as the name of the program: accountsReceivable. What you should see is something like the following:
Now click OK. What should appear next will be like the following:
file:///D|/1/final/BBL0023.html (1 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
Notice on the left should be the Solution Explore options (unless there is a different default menu appearing). On the right should be the Windows form: Form1 The next objective is to view the code that has been written automatically by the IDE. To see the code, click a right mouse button on the Form1. When you do this, a window like the following will pop up:
Now select View Code. In the middle of the screen should appear code like the following: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace accountsReceivable { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
In looking at the code above, notice all of the namespaces that were automatically inserted into the program by the IDE. Next notice that the main class for the program: Form1 that is derived from the class: System.Windows. Forms.Form. (Note: Of course it is possible to change the name of the class Form1 to something else, if desired. If you do this, you should also change the name in the constructor and all other occurrences of the name in the other files as well.) As the program in this section is developed, click back and forth to view the code and notice all of the code that is automatically being written by the IDE. Notice in the code listed above the word: partial between the word: public and the word: class. What this means is that not all of the class' code is listed in this file. Part of the definition of the class: Form1 is defined in another file. (This is new to 2005. In the previous version the entire class had to be in one file and in one class definition.) To view this additional code look back at the listing in the Solution Explorer. Notice to the left of Form1.cs is a + sign. Click this plus sign and you will see the following:
file:///D|/1/final/BBL0023.html (2 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
Notice the file: Form1.Designer.cs is listed below Form1.cs. Next double click this link and you will see the following code (Note: If the name of the class had been changed in Form1.cs, then it would have to be changed here as well.):
Click on this code followed a CtrlA and then a CtrlC. Paste the code into NotePad. What you should see will be something like the following: namespace accountsReceivable { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources /// shouldbe disposed; otherwise, false. file:///D|/1/final/BBL0023.html (3 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Text = "Form1"; } #endregion } }
Note: The code you saw when viewing the file in the IDE looks different than the code in Notepad does. Notice the use of the preprocessor statements: #region and #endregion in the code listing above. Now click to the IDE and view the same code again. Notice that the code that these two statements and the code between does not appear automatically. These two statements enclose code that is not visible when viewed. To see this code in the window, click the + on the left side near the bottom of the window. When you do, the complete code as seen in Notepad will appear. The purpose of #region and #endregion is to hide code that does not need to be viewed or directly changed by the programmer. This code will be changed by the IDE. At the top of this code again notice the keyword: partial and the name of the class: Form1 again. The code in this file will contain the remaining code for the class Form1. When this project is completed, this file will again be viewed to notice all of the code in addition to that which appears in Form1.cs. The code in this file is created by the IDE and is a part of the program but traditionally it does not need to be viewed by the programmer. Note: In the above code notice the /// symbols used throughout the code. These are XML single line comment symbols that may be used for XML. In addition to this XML comment symbol for single lines, the following pair of XML symbols: //* and */ may be used for commenting several lines. This topic will not be discussed further in the notes. (XML will be a significantly important topic to your future and you should do what you can to learn about XML and its uses.) In addition to the two files discussed above, notice the file: Program.cs is also listed in the Solution Explorer. This file is also part of the program's project. (In the Console programs only the Program.cs was the code part of the program's solution.) Double click on this file. When you do, you should see code that looks like the following: using System; using System.Collections.Generic; using System.Windows.Forms;
file:///D|/1/final/BBL0023.html (4 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
namespace accountsReceivable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
Notice that Program.cs contains Main(). In addition note that Main() calls methods that activate the code in Form1. cs and Form1.Designer.cs. In particular Application.Run() calls the Form1 constructor. Once this discussion is completed, each of these three files will be viewed again to notice how they have changed. There is a fourth file but there will be no discussion of that file until later in the notes. The next step is to create the form for the program. Click on the Form1.cs table at the top of the project window. To switch back to view the window's form, click View on the menu bar and select Designer as in the following graphic:
file:///D|/1/final/BBL0023.html (5 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
What is needed next is the drop down menu: Toolbox options. To view this menu, select View on the menu bar and then select Toolbox as in the following:
file:///D|/1/final/BBL0023.html (6 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
Once you have selected the Toolbox, it should look like the following:
Depending on the set up of your copy of Visual Studio .NET, the Toolbox may be on the right or the left. Notice to the right of the word: Toolbox what looks like a posting pin. By selecting this pin, you can make this or any other of these menu choices appear or disappear. For example, if you click the pin opposite Toolbox it should collapse and now you should see something like the following:
file:///D|/1/final/BBL0023.html (7 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
If you click on the Toolbox graphic on the right side (it may be on the left for your setup), you will have the option to again make the Toolbox visible. If you want it to stay there, then just click the posting pin and the Toolbox will remain open. The purpose of the Toolbox is to present tools for the programmer to drag and drop onto the form of the program being created. By dragging and dropping these tools, the IDE will automatically write the code into the editor to implement the tools added. Click on the form. The next step is to change the title at the top of the form to Accounts Receivable. To do this, make the Properties menu appear by doing a right mouse button on the form as you did to View Code. Notice that one of the other options is: Properties. The purpose of the Properties is to list the static properties of a tool to permit the programmer to easily set the values of these tools. Scroll up on the Properties until the Text option is visible as in the following:
file:///D|/1/final/BBL0023.html (8 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
Click in the Text box and change it from Form1 to Accounts Receivable.
file:///D|/1/final/BBL0023.html (9 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
The form will then appear as in the following:
Specification: The next objective is to develop a program that will help to process your customer's accounts i.e. file:///D|/1/final/BBL0023.html (10 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
to process their accounts receivable. The objective will be to enter an amount into a text box that is either a payment (or a credit) or a charge to the account. Once the amount is entered, one of two buttons may be clicked (either Payment or Charge). After the button has been clicked, the amount entered will disappear from its text box and the current (updated) balance for the account will replace the balance that appeared in the text box before the transaction. The screen should look similar to the following where the top is the form's bar and the bottom is the form's contents:
The top lines are the text boxes and the bottom lines are the buttons. The following table contains sample data to be used for testing:
Amount Balance Button
0.00
100.00
10.00
50.00
100.00
90.00
140.00
Charge
Payment
Charge
Open table as spreadsheet
Design Phase: Note: The pseudo code should be like the following. It should represent the actions of the program: Form1 InitializeComponent() theAmount.Text = " " theBalance.Text = "0.00" End Payment_click amount = decimal(theAmount.Text) balance = decimal(theBalance.Text) balance -= amount theBalance.Text = String.Format(balance) theAmount.Text = "" End Charge_click amount = decimal(theAmount.Text) balance = decimal(theBalance.Text) balance += amount theBalance.Text = String.Format(balance) theAmount.Text = "" End
file:///D|/1/final/BBL0023.html (11 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
Coding Phase: Step 1: Open the Toolbox. Using your mouse, click the tool: Label that is listed in the Toolbox and drag it into the middle of the form. What should appear is the following:
Notice the word: label1 appears inside of the Label. What needs to be done now is to change this text to say: Accounts Receivable. Click on the label and select the Properties menu options for label1. Notice in Properties that one of the options is Text. Change the Text from label1 to Accounts Receivable the Form should now look like the following:
The next step is to change the font type, the font size and make the words bold. To do this, notice that one of the
file:///D|/1/final/BBL0023.html (12 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
options on Properties is Font. Notice the button with the three dots as in the following:
Click this button to the right of the word Font. Several options should now appear. Scroll down the Font options until it is possible to select Times New Roman. Scroll down the Font style until it is possible to select: Bold. Scroll down the Size until it is possible to select 12. (These particular options are not required and any of the other options may be selected instead.) When each of these has been selected, the Font dialog box should appear as the following:
file:///D|/1/final/BBL0023.html (13 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
After making these selections, click the OK button. What should appear on the screen should be the following:
As can be seen, the words do not appear attractive. What needs to be done is to change the size and location of this Label so that it appears more attractive. One way to do this would be to use the mouse and stretch the size and change the location of the Label so that it appears more attractive. Another way would be to use the Properties. Scroll down to the bottom of the Properties where the options: Location and Size are located. Using the Properties, change the Location to: 95, 20 and change the Size to: 185, 23. (Usually the second value for the Size is fixed by the size of the font used.) As appears in the following graphic):
file:///D|/1/final/BBL0023.html (14 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
The form will now appear as in the following graphic:
To see how the window will look, click on Build (F7 or F6 depending on your installation) and then Debug (F5). What will appear should be like the following graphic:
Step 2: The next step is to place on the form, two Labels, two TextBoxes and two Buttons. Following the approach used for the Label discussed above, drag and drop these six items on to the form. As you do this, notice that one of the tools of the IDE is to place blue alignment lines on the form to show where to place an item so that it is aligned with the other items on the screen as in the following graphic:
file:///D|/1/final/BBL0023.html (15 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
After these six items are on the form, they should appear as shown in the following graphic:
Using the same techniques in the Properties of each of these tools as with label1 make the following changes (the locations and sizes do not have to be exact in order to achieve the objective of this example): 1. change the Labels to have the following properties: ❍
❍
label2: change Text to: Amount with Font as: New Times Roman, Bold and font size: 12, Location to: 44, 84 and Size to: 77, 23 label3: change Text to: Balance with Font as: New Times Roman, Bold and font size: 12, Location to: 44, 125 and Size to: 77, 23
2. change the Buttons to have the following properties: ❍
❍
button1: change Name to: thePayment, Text to : Payment with Font as: New Times Roman, Bold and font size 12, Location to: 46, 205 and Size to: 97, 34. Set the Tab Index to 2. button2: change Name to: theCharge, Text to: Charge with Font as: New Times Roman, Bold and font size 12, Location to: 179, 205 and Size to: 88, 34. Set the Tab Index to 3.
3. change the textBoxes to have the following properties:
file:///D|/1/final/BBL0023.html (16 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms ❍
❍
textBox1: change Name to: theAmount, the Text to: Bold and Location to: 167, 84 and Size to: 100, 22. Set the Tab Index to 1. textBox2: change Name to: theBalance, the Text to: Bold and Location to: 167, 125 and Size to: 100, 22. Set the Tab Index to 4. Set the TabStop to False. Set ReadOnly to True.
Once you have made all of these changes, Build and Debug. What you should see will be something like the following:
Step 3: The only thing left to do is to create the ability of each of the buttons to place the mathematical results into the textboxes. To begin, select the Code View and make the following changes (high lighted in red) in the constructor Form1(): namespace accountsReceivable { public partial class Form1 : Form { public Form1() { InitializeComponent(); theAmount.Text = " "; theBalance.Text = "0.00"; } } }
The above method is the constructor for the class: Form1 so that when the program begins, the constructor is called and the first textbox will be empty while the second will be filled with 0.00 as the starting values. Notice that these variables were not defined in this file. Definitions for these variables in this file are not needed because as will be seen below, these variables were already defined in Form1.Designer.cs by creating the form. If you compile and run the program, you should see something like the following:
file:///D|/1/final/BBL0023.html (17 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
After making these modifications, return to the Designer mode. Next double click on the Payment button. What will appear in the Code Mode will be the following which is called an event handler (event handlers will be discussed later in the notes.) private void thePayment_Click(object sender, EventArgs e) { }
When the Payment button is clicked while the program is running, this function will be called and the body of the function will be executed. To achieve this objective, change the body of this method to the following: private void thePayment_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance -= amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; }
This code will receive the Text values stored in each of the two textboxes: theAmount and theBalance converting them to decimals and storing them in their respective decimal variables amount and balance. Recall that the variables theAmount and theBalance are defined as data members of the class: Form1 in the file: Form1.Designer.cs. The variables amount and balance are defined here as local variable for this methods. After storing in the variables: amount and balance, the value the user entered, the calculation is used to modify the balance. The calculation results are then stored into the theBalance textbox. This is followed by clearing the theAmount textbox. Warning: Notice that n instead of c is used to help to format the output of balance. If c was used to format the output to have a dollar sign ($), the program would not work because the $ would not convert to a number for the later calculations. Again return to the Designer Mode. Next double click the Charge button. What will appear in the Code Mode will be the following event handler:
file:///D|/1/final/BBL0023.html (18 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
private void theCharge_Click(object sender, EventArgs e) { }
As was just done for the Payment button, change the body of this method to the following: private void theCharge_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance += amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; }
This code takes the values stored in the textboxes: theAmount and theBalance, performs the calculation, stores the value in theBalance textbox and then clears theAmount textbox. Next Build and Debug/Start without Debugging. Run the program and the startup results should appear as the following:
Testing Phase: Use the tab key clicking it several times to observe where the cursor moves according to the current tab. Next try the program with several different values clicking either the Payment or the Charge button. Are the calculations correct? After making several test runs of the program, switch to the Code view to see what the code in Form1.cs looks like. It should like the following:
file:///D|/1/final/BBL0023.html (19 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace accountsReceivable { public partial class Form1 : Form { public Form1() { InitializeComponent(); theAmount.Text = " "; theBalance.Text = "0.00"; } private void thePayment_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance -= amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; } private void theCharge_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance += amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; } } }
Notice the following in the code above: public partial class Form1 : Form
Notice the word; Form to the right of Form1 and preceeded by :. You will recall from your C++ class, that this implies that Form1 is derived from the class Form. More will be discussed about this property later in the notes. Further notice the word partial. Remember that the keyword partial implies that part of the class: Form1 is located in another file. Therefore if you try to take the code in this file and paste it into a project, it will not compile because this is not all of the code. What is needed to also use the files: Form1.Designer.cs and Program.cs along with the file: Form1.cs. To observe the rest of the program begin by opening Form1.Designer.cs using the techniques discussed above. What you should see is something like the following (of course the #region needs to be opened to see all of this code):
file:///D|/1/final/BBL0023.html (20 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
namespace accountsReceivable { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed /// resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.theAmount = new System.Windows.Forms.TextBox(); this.theBalance = new System.Windows.Forms.TextBox(); this.thePayment = new System.Windows.Forms.Button(); this.theCharge = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(50, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(185, 23); this.label1.TabIndex = 0; this.label1.Text = "Accounts Receivable"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(44, 84); file:///D|/1/final/BBL0023.html (21 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(76, 23); this.label2.TabIndex = 1; this.label2.Text = "Amount"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(44, 125); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(77, 23); this.label3.TabIndex = 2; this.label3.Text = "Balance"; // // theAmount // this.theAmount.Location = new System.Drawing.Point(167, 84); this.theAmount.Name = "theAmount"; this.theAmount.Size = new System.Drawing.Size(100, 22); this.theAmount.TabIndex = 1; // // theBalance // this.theBalance.Location = new System.Drawing.Point(167, 125); this.theBalance.Name = "theBalance"; this.theBalance.ReadOnly = true; this.theBalance.Size = new System.Drawing.Size(100, 22); this.theBalance.TabIndex = 4; this.theBalance.TabStop = false; // // thePayment // this.thePayment.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.thePayment.Location = new System.Drawing.Point(46, 205); this.thePayment.Name = "thePayment"; this.thePayment.Size = new System.Drawing.Size(97, 34); this.thePayment.TabIndex = 2; this.thePayment.Text = "Payment"; this.thePayment.UseVisualStyleBackColor = true; this.thePayment.Click += new System.EventHandler(this.thePayment_Click); // // theCharge // this.theCharge.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.theCharge.Location = file:///D|/1/final/BBL0023.html (22 von 23) [01.12.2007 04:47:57]
Introduction to Windows Forms
new System.Drawing.Point(179, 205); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(88, 34); this.theCharge.TabIndex = 3; this.theCharge.Text = "Charge"; this.theCharge.UseVisualStyleBackColor = true; this.theCharge.Click += new System.EventHandler(this.theCharge_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 267); this.Controls.Add(this.theCharge); this.Controls.Add(this.thePayment); this.Controls.Add(this.theBalance); this.Controls.Add(this.theAmount); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Accounts Receivable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox theAmount; private System.Windows.Forms.TextBox theBalance; private System.Windows.Forms.Button thePayment; private System.Windows.Forms.Button theCharge; } }
Next look at the code in the file: Program.cs. When you do, you will see that it is the same as the code listed in this file prior to the modifications. These three files should look like the following: Form1.cs, Form1.Designer.cs and Program.cs Nnote: If this program had been written using Visual Studio .NET 2003, then all of the code would have been in the same file: Program.cs Maintenance: What could be added to the program would be a button that would store the data to a file or to a database. This topic will be discussed in an example later in the lectures
file:///D|/1/final/BBL0023.html (23 von 23) [01.12.2007 04:47:57]
UML Charts and Class Diagram for Enumerated Data Types
UML Charts and Class Diagram for Enumerated Data Types Example 1: Suppose that a program needed to be created that would contain the enumerated data type: Months. What should be done would be to create a graphical representation of the enumerated data type during the Design Phase. This can be done with Visio. Design Phase: Suppose that the following was going to be the enumeration in the program being written: public enum Months { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER, }
Going to Visio in the Design Phase, it is possible to create a UML chart for an enumerated data type. Bringing up Visio using the software mode, the following should appear:
file:///D|/1/final/BBL0024.html (1 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
Selecting the Data Type icon near the top and dragging it onto the grid. The following should appear:
Next double click on the icon. When this is done, the following should appear:
Change the Name: option to Months. Change the Stereotype: option to enumeration and click the OK button. The Data Type icon will now be changed to the following:
file:///D|/1/final/BBL0024.html (2 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
What is needed now is to add the enumerators. To add them, again double click on the Data Type icon once again. When the UML Datatype Properties window appears, click on the Enumeration option under Categories. What should appear is the following:
Click in the Enumeration column under in the Enumeration Literals' window, type in the names of each of the months. What should appear would be like the following graphic:
file:///D|/1/final/BBL0024.html (3 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
Follow this action by clicking on the OK button and the following should appear:
The UML chart for the enumerated data type Months when saved should now appear like the following:
file:///D|/1/final/BBL0024.html (4 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
Coding Phase: Once the UML chart has been created in the Design Phase, this will inform the programmer(s) what needs to be coded. Visual Studio .NET 2005 provides a way to have the IDE code the enumerated data type after creating a representation similar to the one done in Visio. To see how this is done, create a console project and call it GeneralLedger. After the project has appeared, click on Project on the menu bar. When you do, you should see something like the following:
file:///D|/1/final/BBL0024.html (5 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
Select the option Add New Item. When you do, you should see the following:
Next select the Class Diagram option under Templates: using the default Name: ClassDiagram1.cd. When this option is selected, a box will appear listing links one of which is: Toolbox. Click this link and the Toolbox should appear like the following:
Click the Enum option and drag it onto the ClassDiagram1.cd. A form like the following should appear.
file:///D|/1/final/BBL0024.html (6 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
For the Enum name: enter Months. When this step is completed, the File name will appear as Months.cs under the option: Create new file. By this is meant that the enumerated data type will be placed in the file Months.cs. Instead, select the Add to existing file option and enter Program.cs. Follow this by clicking the OK button. This will place the graphic for Months in the file Classdiagran1.cd and it should appear like the following:
What needs to be done next is to place the enumerators into Months. Begin by doing a right mouse click in the blank space near the bottom of the graphic. When this comes up click: Add and then Member as in the following graphic:
file:///D|/1/final/BBL0024.html (7 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
When the cursor returns to the Months graphic, type in JANUARY and continue this process until the names of each of the twelve months have been added. When you do, the graphic should appear as in the following:
file:///D|/1/final/BBL0024.html (8 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
If Months was to be used in a GUI program, you could have chosen Form1.cs rather than Program.cs above. If Months was to be used in other programs, then it should have been stored into the default file: Months.cs. In this way, the file Months.cs could be added to the company's component library. What has been done, is that the enumerated data type: Months has been coded into the program. To view the code, do a right mouse on the Months graphic and the following menu should appear. Next, click on the View Code option.
The IDE will then switch to Program.cs showing the following code: public enum Months { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER, }
The IDE may also be used to create a graphic document of this enumerated data type. Return to Classdiagran1. cd. Right clicking the mouse on the Months enumerated data type, the following menu will appear:
file:///D|/1/final/BBL0024.html (9 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
This time click the Copy Image option. Open the program: Paint and Paste the image into it. Save the graphic as Months2.jpg. The file should appear like the following:
file:///D|/1/final/BBL0024.html (10 von 11) [01.12.2007 04:47:58]
UML Charts and Class Diagram for Enumerated Data Types
Remember that both the UML chart created with Visio and the UML chart created with Visual Studio .NET 2005 should become a part of the program's repository file. Example 2: Next go through the same steps used above except this time create the enumerated data type: 2006Models as in the following: public enum 2006Models { 2GX, 45KM, 19LJ4, 67RTV }
Create the UML chart for the Design Phase, then using this graphic as a model, create the enumerated data type: 2006Models in the C# project: Production.cs. When the enumerated data type: 2006Models is created in Visual Studio .NET 2005, have it placed into its own file: 2006Models.cs so that it could be used in other projects. Save both the graphics of the enumerated data type that were created in Visio and in Visual Studio .NET 2005 for the program repository file. Note: This IDE tool may be used to assist in the coding of structures, classes and other C# constructs as will be demonstrated in examples in lectures to follow.
file:///D|/1/final/BBL0024.html (11 von 11) [01.12.2007 04:47:58]
Lecture 2 Examples
Lecture 2 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
Accounts Receivable Windows Forms
Demonstrates a Windows program dealing with accounts receivable.
●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
booleanOperators.cs
Demonstrates some of the uses of the Boolean operators: &, | and ^.
color1.cs
Demonstrates how use colors in Console output.
Conversion.cs
Demonstrates some of the uses of the methods of the class System.Convert.
datetime1.cs
Demonstrates some of the properties of the class: DateTime.
datetime2.cs
Demonstrates some of the properties of the class: DateTime.
datetime3.cs
Demonstrates some of the properties of the class: DateTime.
datetime4.cs
Demonstrates some of the formatting properties for the class DateTime.
DefiniteAssignmentRule.cs
Demonstrates the Definite Assignment Rule. It will not compile because an defined variable is being used prior to assigning it a value
dowhile.cs
Demonstrates how to use the do/while loop.
enum1.cs
Demonstrates how to use enumerated data types with a for() loop and a switch. In addition it shows that an enumerated data type may be used as an argument and as an output data type.
enum2.cs
Demonstrates how to use enumerated data types.
enum3.cs
Demonstrates how to use enumerated data types.
enum4.cs
Demonstrates how to use enumerated data types with a selection statement.
enum5.cs
Demonstrates how to use enumerated data types with a selection statement.
enum6.cs
Demonstrates how to use enumerated data types.
enum10.cs
Demonstrates that it is possible to add or subtract numbers to an enumerated variable to obtain a value beyond the end of the enumerators. The line with multiplication is blocked out because it will not compile.
explicitBoxing1.cs
Demonstrates explicit boxing.
explicitBoxing2.cs
Demonstrates explicit boxing.
explicitBoxing3.cs
Demonstrates explicit boxing.
explicitBoxing4.cs
Demonstrates explicit unboxing.
explicitBoxing5.cs
Demonstrates explicit unboxing. The program will compile but an exception will be thrown.
for.cs
Demonstrates how to use the for() loop.
format1.cs
Demonstrates how to use some of the escape sequences.
format2.cs
Demonstrates how to use the @ symbol rather that using escape sequences.
format3.cs
Demonstrates some of the properties of the string class formatting for output.
format4.cs
Demonstrates some of the formatting properties.
hello1.cpp
This is a simple C++ console program that demonstrates program output to the screen.
hello2.cs
This is a simple C# console program that demonstrates program output to the screen
hello3.cpp
This is a simple C++ console program that demonstrates program output to the screen
hello4.cs
This is a simple C# console program that demonstrates program output to the screen
ifelse.cs
Demonstrates how to use the if/else selection.
implicitBoxing.cs
Demonstrates implicit boxing.
math1.cs
Demonstrates how to use the class Math.
math2.cs
Demonstrates how to use the class Math.
math3.cs
Demonstrates how to use the class Math.
nestedifelse.cs
Demonstrates how to use the null else selection.
nullelse.cs
Demonstrates how to use the null else selection.
operator.cs
Demonstrates how to use the selection operator.
file:///D|/1/final/BBL0025.html (1 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
random1.cs
Demonstrates the use of the maximum values of the Int32 and the Double classes.
random2.cs
Demonstrates the use of the overloaded methods Next() for the class Random.
random3.cs
Demonstrates the use of the methods NextDouble() for the class Random.
readkey.cs
Demonstrates how to output the data using the String method Format() to convert from a string to a monetary format and to also format the width of the output.
string1.cs
Demonstrates the addition of strings and the addition of strings to numbers.
switch.cs
Demonstrates how to use the switch.
switch2.cs
Illustrates how each case in a switch hat has a statement must have a break. Therefore this program does not compile.
switch3.cs
Illustrates how each case in a switch that has a statement must have a break. This program is the same as switch2.cs except that there is an additional break in case 3 that was not there in the other example.
switch4.cs
Illustrates how each case in a switch that has a statement must have a break. This program including the default case. Notice that this program is similar to switch2.cs except that there is no break in the default case.
theInput1.cs
Demonstrates how to input and output the data using the Parse() method to convert from a string to a double and then output use the Console method WriteLine().
theInput2.cs
Demonstrates how to input and output the data using the Parse() method to convert from a string to a double and then output use the Console method Write().
theInput3.cs
Demonstrates how to input and output the data using the Parse() method to convert from a string to a double and then output use the Console method Write(). The ReadLine() method is embedded inside of the Parse() method to eliminate the need for any additional string variables to receive the input from ReadLine().
theInput4.cs
Demonstrates how to input and output the string data.
theInput5.cs
Demonstrates how to output the data using the String method Format() to convert from a string to a monetary format.
theInput6.cs
Demonstrates how to output the data using the String method Format() to convert from a string to a monetary format and to also format the width of the output.
theOutput1.cs
Demonstrates the use of the Console method Writeline() to output strings data.
theOutput2.cs
Demonstrates how to output data value using the Console method: WriteLine().
theOutput3.cs
Demonstrates how to output the data in more than one variable using only one Console method WriteLine().
timespan1.cs
Demonstrates some of the properties of the class: TimeSpan.
while.cs
Demonstrates how to use the while() loop.
// program_id Form1.Designer.cs // written_by don voils // date_written 4/2/2006 // description This file is part of a program which simulates a Windows accounts // receivable program. // namespace accountsReceivable { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> file:///D|/1/final/BBL0025.html (2 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
/// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.theAmount = new System.Windows.Forms.TextBox(); this.theBalance = new System.Windows.Forms.TextBox(); this.thePayment = new System.Windows.Forms.Button(); this.theCharge = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(50, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(185, 23); this.label1.TabIndex = 0; this.label1.Text = "Accounts Receivable"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(44, 84); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(76, 23); this.label2.TabIndex = 1; this.label2.Text = "Amount"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(44, 125); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(77, 23); this.label3.TabIndex = 2; this.label3.Text = "Balance"; // // theAmount // this.theAmount.Location = new System.Drawing.Point(167, 84); this.theAmount.Name = "theAmount"; this.theAmount.Size = new System.Drawing.Size(100, 22); this.theAmount.TabIndex = 1; // // theBalance // this.theBalance.Location = new System.Drawing.Point(167, 125); this.theBalance.Name = "theBalance"; this.theBalance.ReadOnly = true; this.theBalance.Size = new System.Drawing.Size(100, 22); this.theBalance.TabIndex = 4; this.theBalance.TabStop = false; // // thePayment // this.thePayment.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.thePayment.Location = new System.Drawing.Point(46, 205); this.thePayment.Name = "thePayment"; this.thePayment.Size = new System.Drawing.Size(97, 34); this.thePayment.TabIndex = 2; this.thePayment.Text = "Payment"; this.thePayment.UseVisualStyleBackColor = true; this.thePayment.Click += new System.EventHandler(this.thePayment_Click); // file:///D|/1/final/BBL0025.html (3 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// theCharge // this.theCharge.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.theCharge.Location = new System.Drawing.Point(179, 205); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(88, 34); this.theCharge.TabIndex = 3; this.theCharge.Text = "Charge"; this.theCharge.UseVisualStyleBackColor = true; this.theCharge.Click += new System.EventHandler(this.theCharge_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 267); this.Controls.Add(this.theCharge); this.Controls.Add(this.thePayment); this.Controls.Add(this.theBalance); this.Controls.Add(this.theAmount); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Accounts Receivable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox theAmount; private System.Windows.Forms.TextBox theBalance; private System.Windows.Forms.Button thePayment; private System.Windows.Forms.Button theCharge; } }
// program_id Form1.cs // written_by don voils // date_written 4/2/2006 // description This file is part of a program which simulates a Windows accounts // receivable program. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace accountsReceivable { public partial class Form1 : Form { public Form1() { InitializeComponent(); theAmount.Text = " "; theBalance.Text = "0.00"; } private void thePayment_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance -= amount; theBalance.Text = String.Format("{0:n}", balance);
file:///D|/1/final/BBL0025.html (4 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
theAmount.Text = ""; } private void theCharge_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance += amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; } } }
// program_id Program1.cs // written_by don voils // date_written 4/2/2006 // description This file is part of a program which simulates a Windows accounts // receivable program. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace accountsReceivable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
//program_id booleanOperators.cs //written_by don voils //date_written 6/28/2006 //description This program demonstrates some of the uses of // the boolean operators: &, | and ^. // using System; namespace Conversion { class theProgram { static void Main() { bool a = true; bool b = true; Console.WriteLine("a = {0}, b = {1}, a&b = {2}\n", a, b, a & b); Console.WriteLine("a = {0}, b = {1}, a|b = {2}\n", a, b, a | b); Console.WriteLine("a = {0}, b = {1}, a^b = {2}\n\n", a, b, a ^ b); } } }
// program_id color1.cs // written?_by don voils // date_written 7/9/2006 // description This program demonstrates how // use colors in Console output. file:///D|/1/final/BBL0025.html (5 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// using System; class theProgram { static void Main() { int a = 5; int b = a; Console.Title = "This is a test of Console colors"; Console.WriteLine("a stored {0} and b stored {1}\n", a, b); Console.BackgroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("a stored {0} and b stored {1}\n", a, b); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine("a stored {0} and b stored {1}\n", a, b); Console.ReadKey(); } }
//program_id Conversion.cs //written_by don voils //date_written 1/28/2006 //description This program demonstrates some of the uses of // the methods of the class System.Convert. // using System; namespace Conversion { class theProgram { static void Main() { int theInt = Convert.ToInt32("32",10); Console.WriteLine("In example 1 theInt = {0} when converted from the string " + "\"32\".\n",theInt); theInt = Convert.ToInt16("32",16); Console.WriteLine("In example 2 theInt = {0} when converted from 32 base 16.\n", theInt); theInt = Convert.ToInt16("10101",2); Console.WriteLine("In example 3 theInt = {0} when converted from 10101 base 2.\n", theInt); decimal theDecimal = Convert.ToDecimal(23.45); Console.WriteLine("In example 4 theDecimal = {0} when converted from the " + "double 23.45.\n",theDecimal); theDecimal = Convert.ToDecimal("45.67"); Console.WriteLine("In example 5 theDecimal = {0} when converted from the string " + "\"45.67\".\n",theDecimal); string theString = Convert.ToString(34,2); Console.WriteLine("In example 6 theString = {0} when converted from the int 234 to " + "base 2.",theString); Console.WriteLine("\n\n"); } } }
// program_id datetime1.cs // written_by don voils // date_written 12/27/2006 // description This program demonstrates some of the // properties of the class: DateTime. //
file:///D|/1/final/BBL0025.html (6 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
using System; class theProgram { static void Main() { DateTime theDate = new DateTime(2005,12,27); Console.WriteLine("This program was written on:\n{0} {1}\n" + "which was the {2} day of the year {3}", theDate.DayOfWeek,theDate.Date, theDate.DayOfYear,theDate.Year); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id datetime2.cs // written_by don voils // date_written 12/27/2006 // description This program demonstrates some of the // properties of the class: DateTime. // using System; class theProgram { static void Main() { int month; int day; int year; Console.Write("What is the month of the invoice? "); month = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the day of the month of the invoice? "); day = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the year of the invoice? "); year = Int32.Parse(Console.ReadLine()); DateTime theDate = new DateTime(year,month,day); Console.WriteLine("\n\nThe invoice was issued on: {0}", theDate.ToLongDateString()); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id datetime3.cs // written_by don voils // date_written 12/27/2006 // description This program demonstrates some of the // properties of the class: DateTime. // // Run this program several times to see // what effect this will have on the number // of ticks. // using System; class theProgram { static void Main() { DateTime theDate = new DateTime(); file:///D|/1/final/BBL0025.html (7 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
theDate = DateTime.Now; Console.WriteLine("\n\nThe invoice was issued on: {0}",theDate.ToShortDateString()); Console.WriteLine("and the number of ticks today were: {0:n0}",theDate.Ticks); theDate = DateTime.Today; Console.WriteLine("\n\nor was the invoice issued on: {0}",theDate.ToLongDateString()); Console.WriteLine("and the number of ticks up to today were: {0:n0}",theDate.Ticks); DateTime newDate = new DateTime(2005,12,27,14,31,0); Console.WriteLine("\n\nThis program was written on: {0}",newDate.ToString()); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id datetime4.cs // written_by don voils // date_written 8/5/2006 // description This program demonstrates some of the // formatting properties for the class DateTime. // using System; class theProgram { static void Main() { DateTime theDay = DateTime.Now; Console.WriteLine(theDay.ToString()); Console.WriteLine(theDay.ToString("\n\ndddd MMMM dd, yyyy g")); Console.WriteLine("\n\n{0:MM/dd/yy hh:mm tt}",theDay); Console.WriteLine("\n\n{0:hh:mm:ss tt G\\M zz}",theDay); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id DefiniteAssignmentRule.cs // written_by don voils // date_written 5/6/2006 // description This program demonstrates the Definite Assinment Rule. // It will not compile because an defined variable is // being used prior to assigning it a value. // using System; using System.Collections.Generic; using System.Text; namespace testingCsharp { class Program { static void Main(string[] args) { // The following lines will not compile. // int theNumber; Console.WriteLine(theNumber); // If the following statements were uncommented // and the statements above were commented out // the program would compile. // //int theNumber = 0; //Console.WriteLine(theNumber); }
file:///D|/1/final/BBL0025.html (8 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
} }
// program_id dowhile.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to // use the do/while loop. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double totalPayroll = 0; // This char used to control the loop // char toContinue = 'y';
// this int keeps track of the number of employees // int numberEmployees = 0; // Receives and adds the value of each emplyee's payroll // until the user requests to stop.. // do { ++numberEmployees; // Clears the screen. // Console.Clear(); // Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); totalPayroll += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); }while((toContinue == 'y') || (toContinue == 'Y')); // Clears the screen. // Console.Clear();
// Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",totalPayroll); // Improves the vertical spacing. Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id enum1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use enumerated data types: file:///D|/1/final/BBL0025.html (9 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// i) with type conversion // ii) with relational operators // iii) with arithmetic operators // iv) with a for() loop and a switch. // v) In addition it shows // that an enumerated data type may be // used as an argument and as an output // data type. // using System;
class theProgram { enum Colors:int { BLACK, RED, YELLOW, GREEN, BLUE } static void Main() { string theColor; Colors yourCar = Colors.YELLOW; theColor = yourCar.ToString(); Console.WriteLine("The color of your car is {0}",theColor); int theNumber = (int)yourCar; Console.WriteLine("\nThe number of your car is {0}",theNumber); Colors hisCar = Colors.GREEN; if(yourCar < hisCar) Console.WriteLine("\nYour car's color is less than his car's color.\n"); else Console.WriteLine("\nHis car's color is less than your car's color.\n"); Colors myCar; // Notice that type casting is not required in the control // statement // for(myCar = Colors.BLACK ;myCar <= Colors.BLUE;myCar = myCar + 1) { Console.WriteLine("\nThe output of the function basicColor() is {0}\n", basicColor(myCar)); } Console.Write("My car is no longer one of the basic colors.\n\n"); // Notice how type conversion may be used to convert an int to an // enumerator and then what happens when the variable being converted // exceeds the number of the enumarators. // for(int index = 0; index < 6;++index) Console.WriteLine("The color of the cars can be {0}",(Colors)index); Console.ReadKey(); } // Notice that the function basicColor has an argument and as output // a variable of the enumerated data type Colors. // static Colors basicColor(Colors theCar) {
switch(theCar) { case Colors.BLACK: Console.WriteLine("My car is black.\n");
file:///D|/1/final/BBL0025.html (10 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
break; case Colors.RED: Console.WriteLine("My car is red.\n"); break; case Colors.YELLOW: Console.WriteLine("My car is yellow.\n"); break; case Colors.GREEN: Console.WriteLine("My car is green.\n"); break; case Colors.BLUE: Console.WriteLine("My car is blue.\n"); break; default: Console.WriteLine("My car is not one of the basic colors.\n"); break; } return theCar; } }
// program_id enum2.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use enumerated data types. // using System;
class theProgram { enum Colors:int { Black, Red, Yellow, Green, Blue} static void Main() { Colors myCar; for(myCar = Colors.Black ;myCar <= Colors.Blue;myCar = myCar + 1) { Console.WriteLine("The output of the function basicColor() is {0}\n", Format(myCar)); } Console.WriteLine("\n\n"); }
}
// program_id enum3.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use enumerated data types. // using System;
class theProgram { enum Colors:int { BLACK, file:///D|/1/final/BBL0025.html (11 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
RED, YELLOW, GREEN, BLUE} static void Main() { Colors myCar; for(myCar = Colors.BLACK ;myCar <= Colors.BLUE;myCar = myCar + 1) { Console.WriteLine("My car is now {0}\n", myCar.ToString()); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id enum4.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use enumerated data types with // a selection statement. // using System; class theProgram { enum Rates { BOTTOM, NOTBOTTOM = 5, MIDDLE, AVERAGE = 10 } static void Main() { Rates myRate = Rates.BOTTOM; if(myRate == Rates.BOTTOM) Console.WriteLine("\n\nMy rate is the bottom rate.\n\n"); Console.ReadKey(); } }
// program_id enum5.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use enumerated data types with // a selection statement. // using System;
class theProgram { enum Rates { BOTTOM, NOTBOTTOM = 5, MIDDLE, AVERAGE = 10 }
file:///D|/1/final/BBL0025.html (12 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
static void Main() { Rates myRate = Rates.BOTTOM; Rates yourRate = Rates.MIDDLE; if(myRate < yourRate) Console.WriteLine("\n\nMy rate is lower than your rate\n\n"); else Console.WriteLine("\n\nMy rate is greater than or equal to your rate\n\n"); Console.ReadKey(); } }
// program_id enum6.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use some of the enumerated data types methods. // using System;
class theProgram { enum Colors:int { BLACK=10, RED, YELLOW, GREEN, BLUE } static void Main() { Colors myCar; for(myCar = Colors.BLACK;myCar <= Colors.BLUE;myCar = myCar + 1) { Console.WriteLine("My car is now {0}", myCar.ToString()); Console.WriteLine("My car in int: {0}", Enum.Format(typeof(Colors),myCar,"D")); Console.WriteLine("My car in hex: {0}\n", Enum.Format(typeof(Colors),myCar,"X")); } Console.ReadKey(); } }
// program_id enum10.cs // written_by don voils // date_written 6/10/2006 // description This program demonstrates that it is // possible to add or subtract numbers to an enumerated // variable to obtain a value beyond the // end of the enumerators. // // The line with multiplication is blocked out // because it will not compile. // using System;
class theProgram { enum Colors : int file:///D|/1/final/BBL0025.html (13 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
{ BLACK, RED, YELLOW, GREEN, BLUE } static void Main() { Colors yourCar = Colors.YELLOW; yourCar = yourCar + 5; Console.WriteLine("The color of your car is {0}", yourCar); yourCar = yourCar - 10; Console.WriteLine("The color of your car is {0}", yourCar); // The following statement will not compile. // //yourCar = yourCar * 2; Console.ReadKey(); } }
// program_id explicitBoxing1.cs // written_by don voils // date_written 5/6/2006 // description This program demonstrates explicit boxing. // using System; using System.Collections.Generic; using System.Text; namespace testingCsharp { class Program { static void Main(string[] args) { int theNumber = 344; object theObject = theNumber; Console.WriteLine("The value of theObject is {0}", theObject); } } }
// program_id explicitBoxing2.cs // written_by don voils // date_written 5/6/2006 // description This program demonstrates explicit boxing. // using System; using System.Collections.Generic; using System.Text; namespace testingCsharp { class Program { static void Main(string[] args) { int theNumber = 344; object theObject = theNumber; Console.WriteLine("The value of theObject is {0}", theObject); // The value on the heap is now 356.
file:///D|/1/final/BBL0025.html (14 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// theObject = 356; Console.WriteLine("The value of theObject is {0}", theObject); } } }
// program_id explicitBoxing3.cs // written_by don voils // date_written 5/6/2006 // description This program demonstrates explicit boxing. // using System; using System.Collections.Generic; using System.Text; namespace testingCsharp { class Program { static void Main(string[] args) { int theNumber = 344; object theObject = theNumber; Console.WriteLine("The value of theObject is {0}", theObject); // The value on the heap is now 356. // theObject = 356; Console.WriteLine("The value of theObject is {0}", theObject); int anotherNumber = theObject; } } }
// program_id explicitBoxing4.cs // written_by don voils // date_written 5/6/2006 // description This program demonstrates explicit unboxing. // using System; using System.Collections.Generic; using System.Text; namespace testingCsharp { class Program { static void Main(string[] args) { int theNumber = 344; object theObject = theNumber; Console.WriteLine("The value of theObject is {0}", theObject); // The value on the heap is now 356. // theObject = 356; Console.WriteLine("The value of theObject is {0}", theObject); int anotherNumber = (int)theObject; Console.WriteLine("The value of anotherNumber is {0}", anotherNumber); } } }
// program_id explicitBoxing5.cs // written_by don voils // date_written 5/6/2006 file:///D|/1/final/BBL0025.html (15 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// description This program demonstrates explicit unboxing. // The program will compile but an exception will // be thrown. // using System; using System.Collections.Generic; using System.Text; namespace testingCsharp { class Program { static void Main(string[] args) { int theNumber = 344; object theObject = theNumber; Console.WriteLine("The value of theObject is {0}", theObject); // The value on the heap is now 356. // theObject = 356; Console.WriteLine("The value of theObject is {0}", theObject); float yetAnother = (float)theObject; } } }
// program_id for.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to // use the for() loop. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double invoiceTotal = 0; // These number are used to control the loop // int numberItems; int control; // Record the number of items in the invoice // Console.Write("How many items are there in the invoice? "); numberItems = Int32.Parse(Console.ReadLine()); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Receives and adds the value of each invoice item. // for(control = 1;control <= numberItems; ++control) { Console.Write("\nWhat is the cost of item {0}? ",control); invoiceTotal += Double.Parse(Console.ReadLine()); } // Improves the vertical spacing. Console.WriteLine("\n\n"); // Displays the invoice total. // Console.WriteLine("The invoice total is {0:c}",invoiceTotal);
file:///D|/1/final/BBL0025.html (16 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// Improves the vertical spacing. Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id format1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use some of the escape sequences. // using System;
class theProgram { static void Main() { Console.WriteLine("This is\na quotations:\t \"To be or not to be\"\n\n"); } }
// program_id format2.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use the @ symbol rather that using // escape sequences. // using System;
class theProgram { static void Main() { Console.WriteLine("Instead of displaying:\n\n"); Console.WriteLine("To be or not to be \nthat is the question."); Console.WriteLine("\n\n"); Console.WriteLine("this program displays\n\n"); Console.WriteLine(@"To be or not to be that is the question."); Console.WriteLine("\n\n"); } }
// program_id format3.cs // written_by don voils // date_written 8/2/2006 // description This program demonstrates some of the // properties of the string class formatting for output. // using System; class theProgram { static void Main() { double theBalance = -6523.33; Console.WriteLine("The balance of the account is: {0:c}\n\n", theBalance); double theInterest = 0.205; Console.WriteLine("The interest being charged to the account is: {0:00.00%}\n\n",theInterest); double theEarning = -0.035; file:///D|/1/final/BBL0025.html (17 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
string theOutput = string.Format("The interest earned by the account is: {0:0.00%}\n\n", theEarning); Console.WriteLine(theOutput); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id format4.cs // written_by don voils // date_written 8/5/2006 // description This program demonstrates some of the // formatting properties. // using System; class theProgram { static void Main() { double firstAccount = .3; double secondAccount = -3643; double thirdAccount = 0.00; Console.Write("The first account has a balance of: "); Console.WriteLine("{0:$#,##0.00;($#,##0.00); zero balance}", firstAccount); Console.Write("\n\nThe second account has a balance of: "); Console.WriteLine("{0:$#,##0.00;($#,##0.00); zero balance}", secondAccount); Console.Write("\n\nThe third account has a balance of: "); Console.WriteLine("{0:$#,##0.00;($#,##0.00); zero balance}", thirdAccount); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id: hello1.cpp // written_by: don voils // date_written: 12/11/2006 // description: This is a simple C++ console program that // demonstrates program output to the screen // #include void main() { std::cout << "Hello students!!" << std::endl; }
// program_id: hello2.cs // written_by: don voils // date_written: 12/11/2006 // description: This is a simple C# console program that // demonstrates program output to the screen // class Hello { static void Main() { System.Console.WriteLine("Hello students!!"); } }
file:///D|/1/final/BBL0025.html (18 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// program_id: hello3.cpp // written_by: don voils // date_written: 12/11/2006 // description: This is a simple C++ console program that // demonstrates program output to the screen // #include using namespace std; void main() { cout << "Hello students!!" << endl; }
// program_id: hello4.cs // written_by: don voils // date_written: 12/11/2006 // description: This is a simple C# console program that // demonstrates program output to the screen // using System; class Hello { static void Main() { Console.WriteLine("Hello students!!"); } }
// program_id ifelse.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use the if/else // selection. using System;
class theProgram { static void Main() { // The doubles required for the calculatiolns // double theHourlyRate; double theHoursWorked; double theGrossPay; double theLimit; // The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine());
// The hours worked is requested and received. // Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine());
// The budgeted limit is requested and received. // Console.Write("What is the budgeted limit for this work? "); theLimit = Double.Parse(Console.ReadLine());
// The gross pay is calculated. //
file:///D|/1/final/BBL0025.html (19 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
theGrossPay = theHourlyRate * theHoursWorked;
if(theGrossPay <= theLimit) Console.WriteLine("\n\nThe hourly rate is: {0:c}\nThe hours worked is: {1:n} \nThe gross pay is: {2:c}\nand this was below the budgeted limit: {3:c}\n\n", theHourlyRate,theHoursWorked,theGrossPay,theLimit); else Console.WriteLine("\n\nThe hourly rate is: {0:c}\nThe hours worked is: {1:n} \nThe gross pay is: {2:c}\nand this was over the budgeted limit by: {3:c}\n\n", theHourlyRate,theHoursWorked,theGrossPay,theGrossPay-theLimit); } }
// program_id implicitBoxing.cs // written_by don voils // date_written 5/6/2006 // description This program demonstrates implicit boxing. // using System; using System.Collections.Generic; using System.Text; namespace testingCsharp { class Program { static void Main(string[] args) { int theNumber = 344; Console.WriteLine(" The number is {0}", theNumber); } } }
// program_id math1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use the class Math. // using System;
class theProgram { static void Main() { int numberPowers; Console.Write("How many entries do you want ? "); numberPowers = Int32.Parse(Console.ReadLine()); Console.WriteLine("\n\n"); for(int index = 1;index <= numberPowers;++index) Console.WriteLine("{0} {1} {2}", index,Math.Pow(index,2),Math.Pow(index,3)); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id math2.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to
file:///D|/1/final/BBL0025.html (20 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// use the class Math. // using System;
class theProgram { static void Main() { double leg1; double leg2; double hypotenus; Console.Write("What is the length of the first leg? "); leg1 = Double.Parse(Console.ReadLine()); Console.WriteLine("\n\n"); Console.Write("What is the length of the second leg? "); leg2 = Double.Parse(Console.ReadLine()); hypotenus = Math.Sqrt(Math.Pow(leg1,2) + Math.Pow(leg2,2)); Console.WriteLine("\n\nThe length of the hypotenus is {0}.\n\n",hypotenus); Console.ReadKey(); } }
// program_id math3.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use the class Math. // using System;
class theProgram { static void Main() { double radius; double area; double circumference; Console.Write("What is the length of the radius? "); radius = Double.Parse(Console.ReadLine()); area = Math.PI * Math.Pow(radius,2); Console.WriteLine("\n\nThe area of the circle is {0}.\n",area); circumference = Math.PI * 2 * radius; Console.WriteLine("\nThe circumference of the circle is {0}.\n\n",circumference); Console.ReadKey(); } }
// program_id nestedifelse.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use the null else // selection. using System;
class theProgram { file:///D|/1/final/BBL0025.html (21 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
static void Main() { // The doubles required for the calculatiolns // double theHourlyRate; double theHoursWorked; double theGrossPay; double theLimit; double budgetExcessLimit; // The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine()); // The hours worked is requested and received. // Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine()); // The budgeted limit is requested and received. // Console.Write("What is the budgeted limit for this work? "); theLimit = Double.Parse(Console.ReadLine()); // The budgeted limit is requested and received. // Console.Write("What is the budgeted excess limit for this work? "); budgetExcessLimit = Double.Parse(Console.ReadLine()); // The gross pay is calculated. // theGrossPay = theHourlyRate * theHoursWorked; if(theGrossPay <= theLimit) Console.WriteLine("\n\nThe hourly rate is: {0:c}\nThe hours worked is: {1:n}\n"+ "The gross pay is: {2:c}\nand this was below the budgeted limit: {3:c}\n\n", theHourlyRate,theHoursWorked,theGrossPay,theLimit); else if((theGrossPay - theLimit) <= budgetExcessLimit) Console.WriteLine("\n\nThe hourly rate is: {0:c}\nThe hours worked is: {1:n}"+ "\nThe gross pay is: {2:c}\nand this was over the budgeted limit: {3:c}\n"+ "but below the excess.\n\n",theHourlyRate,theHoursWorked,theGrossPay,theLimit); else Console.WriteLine("\n\nThe hourly rate is: {0:c}\nThe hours worked is: {1:n} \n"+ "The gross pay is: {2:c}\nand this was over the budgeted limit: {3:c}\n"+ "and over the budget excess limit by: {4:c}.\n\n", Console.ReadKey(); theHourlyRate,theHoursWorked,theGrossPay,theLimit,(theGrossPay - budgetExcessLimit)); } }
// program_id nullelse.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use the null else // selection. using System;
class theProgram { static void Main() { // The doubles required for the calculatiolns // double theHourlyRate; double theHoursWorked; double theGrossPay; double theLimit;
file:///D|/1/final/BBL0025.html (22 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine());
// The hours worked is requested and received. // Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine());
// The budgeted limit is requested and received. // Console.Write("What is the budgeted limit for this work? "); theLimit = Double.Parse(Console.ReadLine());
// The gross pay is calculated. // theGrossPay = theHourlyRate * theHoursWorked;
if(theGrossPay <= theLimit) Console.WriteLine("\n\nThe hourly rate is: {0:c}\nThe hours worked is: {1:n} \nThe gross pay is: {2:c}\nand this was below the budgeted limit: {3:c}\n\n", theHourlyRate,theHoursWorked,theGrossPay,theLimit); Console.ReadKey(); } }
// program_id operator.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use the // selection operator. using System;
class theProgram { static void Main() { // The doubles required for the calculatiolns // double theHourlyRate; double theHoursWorked; double theGrossPay; double theLimit;
// The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine());
// The hours worked is requested and received. // Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine());
// The budgeted limit is requested and received. // Console.Write("What is the budgeted limit for this work? "); theLimit = Double.Parse(Console.ReadLine()); // The gross pay is calculated. file:///D|/1/final/BBL0025.html (23 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("\n\nThe hourly rate is: {0:c}\nThe hours worked is: {1:n} \n"+ "The gross pay is: {2:c}\nand the budgeted limit is: {3:c}\n\n", theHourlyRate,theHoursWorked,theGrossPay,theLimit); string theResponse = (theGrossPay <= theLimit)? (" below limit."):(" over limit."); Console.WriteLine("\nYou are{0}\n\n",theResponse); Console.ReadKey(); } }
// program_id random1.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates the // use of the maximum values of // the Int32 and the Double classes. // using System; class theProgram { static void Main() { int theInt32Number = Int32.MaxValue; Console.WriteLine("The maximum output of Int32.MaxValue is {0}",theInt32Number); Console.WriteLine("\n\n"); double theDoubleNumber = Double.MaxValue; Console.WriteLine("The maximum output of Double.MaxValue is {0}",theDoubleNumber); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id random2.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates the // use of the overloaded methods // Next() for the class Random. // using System; class theProgram { static void Main() { Random randomNumber = new Random(); Console.WriteLine("Ten pseudo-random numbers between 0 and 9 inclusive."); for(int index=0;index<10;++index) { int theNumber = randomNumber.Next(10); Console.WriteLine("Random number {0,3} is {1,3}",index+1,theNumber); } Console.WriteLine("\n\n"); Console.WriteLine("Twenty five pseudo-random numbers between 0 and 24 inclusive."); for(int index=0;index<25;++index) { int theNumber = randomNumber.Next(0,25); Console.WriteLine("Random number {0,3} is {1,3}",index+1,theNumber); } Console.WriteLine("\n\n");
file:///D|/1/final/BBL0025.html (24 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
Console.WriteLine("Twenty five pseudo-random numbers between 24 and 57 inclusive."); for(int index=0;index<25;++index) { int theNumber = randomNumber.Next(24,58); Console.WriteLine("Random number {0,3} is {1,3}",index+1,theNumber); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id random3.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates the // use of the methods // NextDouble() for the class Random. // using System; class theProgram { static void Main() { Random randomNumber = new Random(); Console.WriteLine("Ten pseudo-random doubles from 0 to 1."); for(int index=0;index<10;++index) { double theNumber = randomNumber.NextDouble(); Console.WriteLine("Random number {0,2} is {1}",index+1,theNumber); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id readkey.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to // output the data using the String method Format() // to convert from a string to a monetary format // and to also format the width of the output. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine()); // The hours worked is requested and received. Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine()); // The formatting below sets the column of the theHourlyRate to 5, the // column width of theHoursWorked to 7 and the and the width of // theGrossPay to 8. double theGrossPay = theHourlyRate * theHoursWorked; string theOutput = String.Format("\nThe hourly rate is: {0,5:c}\n" + "The hours worked is: {1,7:n} \nThe gross pay is: {2,8:c}\n", theHourlyRate,theHoursWorked,theGrossPay); file:///D|/1/final/BBL0025.html (25 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
Console.WriteLine(theOutput); Console.ReadKey(); } }
// program_id region.cs // written_by don voils // date_written 6/6/2006 // description This program demonstrates how to // use the preprocessor commands: // #region and #endregion to hide // code. // using System;
class theProgram { static void Main() { #region Console.WriteLine("Instead of displaying:\n\n"); Console.WriteLine("To be or not to be \nthat is the question."); Console.WriteLine("\n\n"); #endregion Console.WriteLine("this program displays\n\n"); Console.WriteLine(@"To be or not to be that is the question."); Console.WriteLine("\n\n"); } }
// program_id string1.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates the // addition of strings and the // addition of strings to numbers. // using System;
class theProgram {
static void Main() { string firstName = "George"; string lastName = "Washington"; string theName = firstName + " " + lastName; Console.WriteLine("First name is {0}",firstName); Console.WriteLine("Last name is {0}",lastName); Console.WriteLine("The name is {0}",theName); Console.WriteLine("\n\n"); string item = "Widget"; Console.WriteLine("The item's name is {0}",item); item = item + 5 + 6.78; Console.WriteLine("and item + 5 + 6.78 is {0}",item); Console.WriteLine("\n\n");
} }
file:///D|/1/final/BBL0025.html (26 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
//program_id switch2.cs //author don voils //date written 1/22/2006 //Description This program illustrates how each case in a switch // that has a statement must have a break. Therefore // this program does not compile. // // using System;
class theProgram { static void Main() { int theChoice; Console.Write("Which choice do you want to make (1 - 5)?"); theChoice = Int16.Parse(Console.ReadLine()); switch(theChoice) { case 1: case 2: case 3: Console.WriteLine("You selected a number between 1 and 3"); case 4: case 5: default: Console.WriteLine("You must select 1 - 5"); break; } Console.WriteLine("\n\n"); } }
//program_id switch3.cs //author don voils //date written 1/22/2006 //Description This program illustrates how each case in a switch // that has a statement must have a break. This program // is the same as switch2.cs except that there is an // additional break in case 3 that was not there // in the other example. // // using System;
class theProgram { static void Main() { int theChoice; Console.Write("Which choice do you want to make (1 - 5)?"); theChoice = Int16.Parse(Console.ReadLine()); Console.Clear(); switch(theChoice) { case 1: case 2: case 3: Console.WriteLine("You selected a number between 1 and 3"); break; case 4: case 5: default: Console.WriteLine("You must select 1 - 5"); break; } file:///D|/1/final/BBL0025.html (27 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
Console.WriteLine("\n\n"); Console.ReadKey(); } }
//program_id switch4.cs //author don voils //date written 1/22/2006 //Description This program illustrates how each case in a switch // that has a statement must have a break. This program // including the default. Notice that this program // is similar to switch2.cs except that the break // in the default case does not have a break. // // using System;
class theProgram { static void Main() { int theChoice; Console.Write("Which choice do you want to make (1 - 5)?"); theChoice = Int16.Parse(Console.ReadLine()); switch(theChoice) { case 1: case 2: case 3: Console.WriteLine("You selected a number between 1 and 3"); break; case 4: case 5: default: Console.WriteLine("You must select 1 - 5"); } Console.WriteLine("\n\n"); } }
// program_id switch.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use the // switch. using System;
class theProgram { static void Main() { // The doubles required for the calculatiolns // string option1 = "Accounts Payable"; string option2 = "Accounts Receivable"; string option3 = "Payroll"; string option4 = "Inventory"; string option5 = "Customer Information"; string option6 = "General Ledger"; Console.WriteLine("Menu"); Console.WriteLine("1." +option1); Console.WriteLine("2." +option2); Console.WriteLine("3." +option3); Console.WriteLine("4." +option4);
file:///D|/1/final/BBL0025.html (28 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
Console.WriteLine("5." +option5); Console.WriteLine("6." +option6); Console.WriteLine("\nWhich option do you want to use? "); int theSelection = Int32.Parse(Console.ReadLine()); Console.Clear(); switch(theSelection) { case 1: Console.WriteLine("\nYou have selected: " + option1 +"\n"); break; case 2: Console.WriteLine("\nYou have selected: " + option2 +"\n"); break; case 3: Console.WriteLine("\nYou have selected: " + option3 +"\n"); break; case 4: Console.WriteLine("\nYou have selected: " + option4 +"\n"); break; case 5: Console.WriteLine("\nYou have selected: " + option5 +"\n"); break; case 6: Console.WriteLine("\nYou have selected: " + option6 +"\n"); break; default: Console.WriteLine("\n\nYou did not make a correct selection. " + option1 +"\n"); break; } Console.ReadKey(); } }
// program_id theInput1.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to input and // output the data usinge the Parse() method // to convert from a string to a double and then // output use the Console method WriteLine() // using System;
class theProgram { static void Main() { // Since the input is a string the // following variables are required to // receive the values input. // string theRate; string theHours; // The doubles required for the calculatiolns // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // Console.WriteLine("What was the hourly rate? "); theRate = Console.ReadLine(); // The hours worked is requested and received. Console.WriteLine("How many hours did the employee work? "); theHours = Console.ReadLine(); // The strings are parsed to doubles. // theHourlyRate = Double.Parse(theRate); theHoursWorked = Double.Parse(theHours); file:///D|/1/final/BBL0025.html (29 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}\nThe hours worked is: {1} \nThe gross pay is: ${2}\n", theHourlyRate,theHoursWorked,theGrossPay); } }
// program_id theInput2.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to input and // output the data usinge the Parse() method // to convert from a string to a double and then // output use the Console method Write() // using System;
class theProgram { static void Main() { // Since the input is a string the // following variables are required to // receive the values input. // string theRate; string theHours; // The doubles required for the calculatiolns // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theRate = Console.ReadLine(); // The hours worked is requested and received. Console.Write("How many hours did the employee work? "); theHours = Console.ReadLine(); // The strings are parsed to doubles. // theHourlyRate = Double.Parse(theRate); theHoursWorked = Double.Parse(theHours); double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}\nThe hours worked is: {1} \nThe gross pay is: ${2}\n", theHourlyRate,theHoursWorked,theGrossPay); } }
// program_id theInput3.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to input and // output the data using the Parse() method // to convert from a string to a double and then // output use the Console method Write(). The ReadLine() // method is embedded inside of the Parse() method to // eliminate the need for any additional string // variables to receive the input from ReadLine(). // using System;
class theProgram { static void Main()
file:///D|/1/final/BBL0025.html (30 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
{ // The doubles required for the calculations // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine()); // The hours worked is requested and received. Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine());
double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}\nThe hours worked is: {1} \nThe gross pay is: ${2}\n", theHourlyRate,theHoursWorked,theGrossPay); } }
// program_id theInput4.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to input and // output the string data. // using System;
class theProgram { static void Main() { string firstName; string lastName; string theName; Console.Write("What is your first name? "); firstName = Console.ReadLine(); Console.Write("What is your last name? "); lastName = Console.ReadLine(); theName = firstName + " " + lastName; Console.WriteLine("\nHello {0}.\n\nDid you say your first name was: {1}\nand that your last name was: {2}? \n", theName,firstName,lastName); } }
// program_id theInput5.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to // output the data using the String method Format() // to convert from a string to a monetary format. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // file:///D|/1/final/BBL0025.html (31 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine()); // The hours worked is requested and received. Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine());
double theGrossPay = theHourlyRate * theHoursWorked; string theOutput = String.Format("\nThe hourly rate is: {0:c}\n" + "The hours worked is: {1:n} \nThe gross pay is: {2:c}\n", theHourlyRate,theHoursWorked,theGrossPay); Console.WriteLine(theOutput); } }
// program_id theInput6.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to // output the data using the String method Format() // to convert from a string to a monetary format // and to also format the width of the output. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double theHourlyRate; double theHoursWorked; // The hourly rate is requested and received. // Console.Write("What was the hourly rate? "); theHourlyRate = Double.Parse(Console.ReadLine()); // The hours worked is requested and received. Console.Write("How many hours did the employee work? "); theHoursWorked = Double.Parse(Console.ReadLine()); // The formatting below sets the column of the theHourlyRate to 5, the // column width of theHoursWorked to 7 and the and the width of // theGrossPay to 8. double theGrossPay = theHourlyRate * theHoursWorked; string theOutput = String.Format("\nThe hourly rate is: {0,5:c}\n" + "The hours worked is: {1,7:n} \nThe gross pay is: {2,8:c}\n", theHourlyRate,theHoursWorked,theGrossPay); Console.WriteLine(theOutput); } }
// program_id theOutput1.cs // written_by don voils // date_written 12/11/2006 // description This program demonstrates the // use of the Console method Writeline() // to output strings data. using System; class theProgram { static void Main() { Console.WriteLine("This is an output example.");
file:///D|/1/final/BBL0025.html (32 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
} }
// program_id theOutput2.cs // written_by don voils // date_written 12/11/2006 // description This program demonstrates how to output data value // using the Console method: WriteLine() using System;
class theProgram { static void Main() { double theHourlyRate = 25.45; double theHoursWorked = 45; double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}", theHourlyRate); Console.WriteLine("The hours worked is: {0}", theHoursWorked); Console.WriteLine("The gross pay is: ${0}\n", theGrossPay); } }
// program_id theOutput3.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to output the data in more than // one variable using only one Console method WriteLine() // using System;
class theProgram { static void Main() { double theHourlyRate = 25.45; double theHoursWorked = 45; double theGrossPay = theHourlyRate * theHoursWorked; Console.WriteLine("The hourly rate is: ${0}\nThe hours worked is: {1} \nThe gross pay is: ${2}\n", theHourlyRate,theHoursWorked,theGrossPay); } }
// program_id timespan1.cs // written_by don voils // date_written 12/27/2006 // description This program demonstrates some of the // properties of the class: TimeSpan. // using System; class theProgram { static void Main() { TimeSpan theTime = new TimeSpan(27,14,32,0); Console.WriteLine("\n\nThe time when the object was defined: {0}", theTime.ToString()); Console.WriteLine("\n\nThe day of the month was: {0}",theTime.Days); Console.WriteLine("\n\nThe fractional number of days of the month was: {0:n2}", theTime.TotalDays); Console.WriteLine("\n\nThe fractional number of hours of the month was: {0}", theTime.TotalHours); Console.WriteLine("\n\nThe total number of minutes of the month was: {0}", file:///D|/1/final/BBL0025.html (33 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
theTime.TotalMinutes); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id while.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to // use the while() loop. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double totalPayroll = 0; // This char used to control the loop // char toContinue = 'y';
// this int keeps track of the number of employees // int numberEmployees = 0;
// A request as to whether to enter loop. // Console.Write("Do you want to calculate the total payroll? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Receives and adds the value of each emplyee's payroll // until the user requests to stop.. // while(toContinue=='y' || toContinue=='Y') { ++numberEmployees; // Clears the screen. // Console.Clear();
// Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); totalPayroll += Double.Parse(Console.ReadLine()); Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); } // Clears the screen. // Console.Clear();
// Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",totalPayroll); // Improves the vertical spacing.
file:///D|/1/final/BBL0025.html (34 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
Console.WriteLine("\n\n"); Console.ReadKey(); } }
file:///D|/1/final/BBL0025.html (35 von 35) [01.12.2007 04:48:02]
Lecture 3: Methods in C#, Text File I/O and Structures
Lecture 3: Methods in C#, Text File I/O and Structures Methods and Modularization In C++ modularization was implemented by global functions (By global functions is meant functions that are not methods of classes or structures.) In C# there are no global functions. All functions in C# are methods of a class. However, in C# the static methods of the main class along with Main() act the part of the global functions in C++. These methods will be the modules that are discussed from this point on with respect to modularization. All other methods will be listed as a part of the UML chart for the respective classes. Methods are an important tool in C#. They are used to: ●
enable structured programming
●
reduce code size (but this slows program speed)
●
capture objectives of the program into modules
●
create useable and reusable code
●
increase a programmer's productivity.
Therefore methods should ●
have a clear cut objective,
●
be at most one page of printed code,
●
have a name suggestive of its objective.
In order for a C# programmer to use a method, the following must be done in the program. That is the program must: ●
define the method,
●
execute/call the method.
Note: One of the things you should note from the above listing is that method declarations that are required in C+ + are not used in C#. In C++ method declarations were required for global functions and since C# does not permit global functions, this feature is not allowed. In C#, if a method is: ●
called (executed), where access (in some cases) may be permitted by using the namespace, the class' name in which the definition is included or an object of the class,
●
defined, it must have been defined outside all methods but inside one of the class' definitions. (The definition is either in the same file, in a header file or in another file compiled with the program).
Construct of the Method Definition The construct of the method definition is: [modifiers] returnType methodName(signature) { statement(s); return outputValue;
file:///D|/1/final/BBL0026.html (1 von 6) [01.12.2007 04:48:04]
Lecture 3: Methods in C#, Text File I/O and Structures
}
Notice that if the method is going to be called without the use of a class object, then the keyword static must be one of the modifiers that must precede the returnType. In addition if a static method is called inside of its class, then the class' name is not required in the call. The returnType may be any system or programmer data type including void. If no output data type is listed, then a compiling error should occur. The returnType of the method must be of the same data type as that of outputValue being returned by the method. The literal or value of the expression outputValue must follow the keyword return. The value of outputValue is stored in a part of memory called the stack to be retrieved by the calling method and is returned to the system once the method terminates. When the return statement is encountered, the method will terminate. While C# syntax would permit it, there should be no return statement, if there is no value being returned. In the case where there is no return value, then void must be returnType in the construct above. The methodName may be any C# legal variable name (meaning it should not be too long, it should not be a keyword and it should start with a letter of the alphabet or underscore while the remaining characters can be letters of the alphabet, digits or the underscore). Further the name should be suggestive of the method's objective. If the methodName is only one word, then it is recommended that it be in lower case. If it is two or more words, then it is recommended that the second or additional words should have the first letter of the words in caps and the remaining letters in lower case.
Signature of a Method Definition The signature of the method definition is composed of ●
a list of variables (also called arguments, parameters or formal arguments but they can not be methods)
●
the respective data type names of the variables
●
the order in which they appear from left to right
●
and possibly additional modifiers
The variables, their data types and modifiers are a unit of the signature and each of these units are separated from the others by commas. The data types of the values used in the call must agree with the data types of the definition or there will be an error. See function1.cs (Notice that each of the methods listed in this program are static.)
Methods and Memory Allocation The variables defined within the method block are not visible outside the block (i.e. they are not accessible outside of the method's block) and are called local variables. These local variables are stored in a part of memory called the stack memory. They are created each time the method is called and returned to the system each time the method terminates. When a C# program is compiled, the methods' definitions are translated into machine language. Machine language jumps are created so that when the method is called, the program will be diverted to these instructions. All of the method's instructions are stored in memory when the program is loaded but neither the arguments, the outputvalue nor the variables defined within the method's body are stored into memory. These variables do not exist until the method is called and then they are stored in the stack memory for that particular method call.
Types of Method Arguments In C# there are two types of method arguments. 1. There are those arguments that pass their values to the stack but the variables themselves are not accessible within the body of the module. This type of variable passing is called passing by value. In addition the variables that are the arguments can not have their value changed by the body of the called method since the variable's memory is not accessible within the called method.
file:///D|/1/final/BBL0026.html (2 von 6) [01.12.2007 04:48:04]
Lecture 3: Methods in C#, Text File I/O and Structures
2. There are those methods that create another reference to the argument and pass the reference of the variable into the body of the method thereby providing an opportunity to get access to the argument and to change its contents (this type of method uses what is called passing by reference). C# has two different ways to do this for variables. This may be done by using the keywords: ref or out. Since a method argument that has either a ref or an out in it may be changed, when these methods are called, then these arguments must be variables defined outside of the method and may not be literal values. Note: These keywords must be used both in the definition and in the call. The difference between these two is that ref requires that the variable being passed to have been initialized prior to the call while it is not necessary for the variable to be initialized prior to the call when using the out. Another feature of out is that syntax requires the variable being passed with the out modifier to be changed within the body of the function (or there will be a compiler error) but it is not necessary for the variable to be changed in the call when using the ref. Note: In C# there is no passing by pointer as there is with C++.
Passing Arguments Using the out Reference Operator The following method: findPay() demonstrates using out which does not require prior initialization of the variable passed to grosspay: static void findPay(double hoursWorked, double hourlyRate, out double grossPay) { grossPay = hoursWorked * hourlyRate; }
with a call to findPay() like the following: // Obviously the variables myHours and myRate are initialized // in this case and are being passed by value. // double myPay; findPay(myHours,myRate,out myPay);
After the two statements above, the result of the calculation within the method findPay() will be transferred to the variable myPay and this variable did not need to be initialized prior to the call. For an example that illustrates the use of the keyword out see function3.cs
Passing Arguments Using the ref Reference Operator Using ref requires that the variable passed must have been initialized prior to the call as in the following: static void invoiceTotal(ref double invoiceTotal) { ..... }
(assume that the method: invoiceTotal() would ask for the amount of each item purchased and then these values would be added to invoiceTotal within the method's body.) A call to the method would be like the following: double myTotal = 0.00; invoiceTotal(ref myTotal)
file:///D|/1/final/BBL0026.html (3 von 6) [01.12.2007 04:48:04]
Lecture 3: Methods in C#, Text File I/O and Structures
Note: The ref is used both in the definition and in the call above. After the two statements above, the result of the calculations in the method: invoiceTotal() will transfer to the variable myTotal and the variable needed to have been initialized prior to the call. For an example of a program using ref see function2.cs.
Methods Returning Values The following is an example of the definition of a method that returns a value: static double salary(double hoursWorked, double hourlyRate) { double grossPay; grossPay = hoursWorked * hourlyRate; return grossPay; }
A call to this method could be like the following: double myPay = salary(40, 35.95);
This call would transfer the values 40 and 35.95 to stack memory where the instructions of the method would take these values into the body of the method. The instructions of the method would be carried out and the return value would be transferred from the variable grossPay on the stack of the method to the memory defined for myPay. Since myPay is defined in a block (e.g. in another method) then it would also be on the stack for its block. Note: If the variable passed as an argument is not of the same data type as the argument of the method, then one of two things can happen. If the variable passed was of a data type with less memory requirement than the data type of the argument, then the compiler will do a data type conversion of the variable implicitly. However if the variable being transferred is of a larger data type than the argument, the program will not compile. The way around this problem would be to require an explicit type conversion. For example notice in the above example that the first argument was to be a double, yet 40 (an int) was passed as the argument. In this case the compiler performed an implicit type conversion.
The const Modifier and Methods In C++ the modifier const could be used to either modify the input or to modify the output of a function. However in C# the const modifier may not be used with methods either with the arguments or with the output.
Main() and Its Roll in the Program In the examples so far the function Main() has played a major role in the program in addition to it being the entry point of the program. In the previous examples, variables were defined and functions called within Main(). However the role of Main() may be to just call another method which then does all of the "work". For an example of this change in the role of Main() see function4.cs
Methods and the Visual Studio .NET IDE When viewing a method call, it is sometimes desirable to know how the method is defined. Rather than scanning the entire program, you can block the name of the method in the call (do not include the parenthesis or the arguments). Once you have blocked the method name, do a right mouse click. For example suppose that you want
file:///D|/1/final/BBL0026.html (4 von 6) [01.12.2007 04:48:04]
Lecture 3: Methods in C#, Text File I/O and Structures
to know the definition of the function: calculatePayroll();
When the name of the function: calculatePayroll is blocked and the right mouse button is clicked, the following pop up menu will appear:
Next click the option: Go To Definition. When you do, the IDE will jump to the method's definition permitting the viewing of the definition. Another option that might be found useful would be to block some code that you want to be a method and then click the Refactor option on the pop up menu above. When you do, the following would appear:
Next click the Extract Method… option. When this choice is made, the following would pop up:
file:///D|/1/final/BBL0026.html (5 von 6) [01.12.2007 04:48:04]
Lecture 3: Methods in C#, Text File I/O and Structures
After selecting a name, the blocked code would be replaced by a call to the method and the IDE would insert the method's definition into the code.
file:///D|/1/final/BBL0026.html (6 von 6) [01.12.2007 04:48:04]
Structures
Structures Definition of a Structure As in C++, C# structures are a programmer data type. They are derived from the class: System.ValueType. The C# structures have several similarities as well as several differences with the C++ structures. The general construct of a C# structure is the following: [access-modifiers] struct TheStructureName { [access-modifiers] struct-members }
Notice that there is no semicolon following the ending brace as in C++. In general the access-modifiers of the structure definition are usually public. The struct-members can be data members (also called fields) or member functions (also called methods). The access-modifiers of the fields or the methods are usually public as well. However they may also be private, protected and static. When defining structures, the definition should be placed outside of all classes but inside of a namespace.
Definition of a Structure Instance When defining an instance of a structure, the definition may look like the following: TheStructureName theInstance;
See struct1.cs. Note: It is recommended that the name of the structure begin with a capital letter and then capitalize the first letter of each additional word in the name of the structure. Instances of a structure are value types like the built-in data types and the enumerated data types. Notice in this example that the definition of the instance of the structure looks exactly like a definition of an instance of a built-in data type. (In fact all of the built-in data types are structures.) In addition note that both the structure and its data members have public access modifiers. When an instance of a structure is defined in this manner, the data members must be initialized or the program will not compile.
Defining a Structure Instance with a Constructor While it is possible to define an instance of a structure as in the above example, it is also possible to define an instance like the following: TheStructure theInstance = new TheStructure();
Notice that this looks like the structure is using a constructor which in fact it is. However, the definition of the structure does not require the definition of an explicit constructor in order to define instances of the structure using code like the statement above.
Structure's Default Constructor The structure Customer in the example struct1.cs above does not show the use of a constructor. However the compiler implicitly defines a default constructor. Look at struct5.cs where the default constructor is used but there
file:///D|/1/final/BBL0027.html (1 von 10) [01.12.2007 04:48:05]
Structures
is no explicit definition of the default constructor in the definition of the structure. When the default constructor is used, each of the data members is initialized to the zero for the respective data types. See struct0.cs. While the previous examples used the default constructor created by the compiler, it is not possible for the programmer to define a default constructor. See struct6.cs and notice that this program will not compile because the program contains the definition of the default constructor. Notice the use of the new operator in the definition of an instance of the structure in struct5.cs. This would normally imply that the definition of the instance would therefore be a reference type and therefore stored on the heap. However, in this case, it is the definition of a value type and the instance is stored on the stack.
Structure's Non-Default Constructors Although the compiler must create the default constructor, it is possible for the programmer to define a structure instance using a non default explicit constructor like the following: TheStructure theInstance = new TheStructure(signature);
What is required of any programmer defined constructor is that the data members of the instance of a structure must be initialized. See struct4.cs.
Structures with Methods Structures may use explicit access modifiers. See struct10.cs which has private data members and public methods. This structure has field access and initialization methods. In addition to constructors, access and initialization methods, structures may also have additional methods. See struct3.cs, See the UML chart for the structure: Circle:
UML Charts for Structures As part of the Design Phase used in programming, the programmer should create a UML chart for the structures. For example suppose the following structure: Customer was to be used in a program: public struct Customer { private string name; private decimal owes; public void setName(string aName) { name = aName;
file:///D|/1/final/BBL0027.html (2 von 10) [01.12.2007 04:48:05]
Structures
} public void setOwes(decimal customerOwes) { owes = customerOwes; } public string getName() { return name; } public decimal getOwes() { return owes; } }
In the Design Phase it would therefore be necessary to create a UML chart for this structure. Open Visio to create a UML chart for this structure. When Visio has opened, it should appear as in the following graphic:
Notice in the Category column the option: Software. Click this option. On the right in the Template region will be the option: UML Model Diagram (US units). Click this option. A new screen will appear. On the left in the Shapes column, click on the Class icon and drag a copy onto the graph on the right. It will appear as in the following graphic (It helps viewing, if you change the graph size to 100%):
file:///D|/1/final/BBL0027.html (3 von 10) [01.12.2007 04:48:05]
Structures
Double click on the Class1 rectangle on the graphic. This will open a dialog box like the following:
Change the Name to Customer and then click on the Stereotype list box. The options of Stereotype should appear as the following:
file:///D|/1/final/BBL0027.html (4 von 10) [01.12.2007 04:48:05]
Structures
Select the option: struct and click the OK button. Next should appear the following:
Double click on the graphic one more time. This time selection the Attribute option (this word is used in Visio rather than Field.) When the window for Attributes appears enter the fields, their data type and that they are private. This should appear like the following:
file:///D|/1/final/BBL0027.html (5 von 10) [01.12.2007 04:48:05]
Structures
What needs to be done next is to enter the methods. Click the OK button to return to the main Class screen. To enter the methods select the Operations option (there is no methods option listed) in the Categories window. In the Operation column enter the name of each method. Each of the methods is public. The Return Type of the first two methods is void, the third has a Return Type of string and the last one has a Return Type of decimal. Making these entries should then appear like the following:
The next step is to enter the signatures. This only needs to be done for the first two methods because the second two have a void signature so for these methods nothing needs to be done. To enter the signatures, click the individual methods one at a time and then click the Properties button. This should open a window like the following:
file:///D|/1/final/BBL0027.html (6 von 10) [01.12.2007 04:48:05]
Structures
In the Categories window click the Parameters option. When the new window opens enter the Parameter: aName of Type: string. Click the OK button. Next using the same steps, enter the Parameter: customerOwes of Type: decimal and again click OK. Return to the original graphic and the UML chart for the structure: Customer should appear like the following:
Structures with Properties Instead of using field access and initialization methods structures may use properties for its fields. For example in struct10.cs the definition of the structure Customer is defined as the following: public struct Customer { private string name; private decimal owes; public void setName(string name) { name = aName; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public string getName()
file:///D|/1/final/BBL0027.html (7 von 10) [01.12.2007 04:48:05]
Structures
{ return name; } public decimal getOwes() { return owes; } }
Notice that the fields: name and owes were private to implement OOP. But to give access to the values of these fields, the field access methods were defined. C# introduces an additional way to approach this topic, i.e. the introduction of properties. For example instead of the field access methods for the field name the following property Name may be used: public string Name { get { return name; } set { name = value; } }
and for the field owes the following property Owes may be used: public decimal Owes { get { return owes; } set { owes = value; } }
See structureProperties.cs. In this example, notice that the properties are then used as if they are the fields and that the fields are public. These is how OOP principles may be supported by defining the fields as private, yet still make it easier to access the data stored in the private fields by using properties which are public.
Structures with static Fields or Methods Structures may have static fields or static methods. If the fields are static, then they are not contained in the structure instances. To be called, they must be dotted with the name of the structure. Similarly a static structure method must also be called by the structure's name using the dot operator.
Structures and Destructors While structures like the one in struct4.cs may have an explicit constructor, structures may not have an explicit destructor since structure instances are value types and in C#, destructors are only required for reference types. file:///D|/1/final/BBL0027.html (8 von 10) [01.12.2007 04:48:05]
Structures
Assignment Operator and Structures As with C++, the C# assignment operator is implicitly defined between instances of structures. The assignment operator is defined on structures as the following example shows: struct11.cs. What happens is that the value for each data member of the structure is transferred from one instance to the other through assignment.
Structures with Non-System Data Types as Data Members In the examples above, system data types were used for the data type of the fields. In addition, it is also possible to have the data type of a structure's fields to be not only system data types but also programmer data types like an enumerated data type or even another structure. For example see struct2.cs. This structure is an example of the composition of structures and an enumerated data type. See the following UML chart for the structure: Employee which demonstrates how composition is depicted:
Structures Are Derived from Object As mentioned previously, structures are derived from the System class Object. One of the methods of Object is ToString(). Structures are able to override this function. That is they may define a member function ToString() that could for example provide a more appropriate output for the fields of the structure. This could be achieved like the following: public override string ToString() { return "\nCustomer: " + name+ "\nOwes: $" +owes.ToString(); }
In this case the term override tells the compiler that this definition is to be used when the method: ToString() is called by an object of the structure rather than the Object method ToString(). For example see structToString.cs
Structures and Inheritance While all structures are derived from Object, structures do not in general support inheritance. That is, other than file:///D|/1/final/BBL0027.html (9 von 10) [01.12.2007 04:48:05]
Structures
the class Object, a structure may not be derived from any other structure or class. Further it is not possible to derive a structure or class from a structure. In general structures should only be used for data types that are small, simple and are similar to the built in data types. Because of their simplicity, some authors recommend that structures be used rather than classes while other authors completely ignore structures.
file:///D|/1/final/BBL0027.html (10 von 10) [01.12.2007 04:48:05]
Recursive Methods
Recursive Methods Recursive methods may be used in C#. This type of method can be used with fractals and in artificial intelligence. A method is recursive if it calls itself directly or indirectly through another method. Each time the recursive method is called, it begins over again. Each time it starts again, a new set of arguments, local variables and instructions are created on the stack. There will be one set of variables on the stack for each call. Because there is a new set of memory locations for variables for each call, the programmer must guard against permitting too deep a call for the available memory. In particular, care must be taken not to have an infinite call. For example: static int newGCD(int numb1, int numb2) { return (numb1 < 0)? (newGCD(-numb1,numb2)): ((numb2 == 0) ? numb1: newGCD(numb2 , numb1 % numb2)); }
This method returns the greatest common divisor of the two ints: numb1 and numb2. See newgcd.cs Another example of recursive methods is the following method: static unsigned long factorial(int numb) { return (numb==0) ? (1) :(numb * factorial(numb-1)); }
This method will return the factorial of the int: numb. In mathematics we would represent this function call by numb! A call to this method could be: int value = factorial(5);
in which case value would receive 120 from the function: factorial(). That is 5! = 120. In order to execute this call, there would need to be 6 copies of numb (and other controlling commands) created on the stack, one for each number from 0 up to 5. However, there will be only one copy of the method in memory. See newfact.cs
file:///D|/1/final/BBL0028.html [01.12.2007 04:48:05]
Method Name Overloading
Method Name Overloading In the C libraries can be found the following functions: iabs() labs() fabs() dabs()
These functions return the absolute value of an int, a long, a float, and a double respectively. You may ask yourself: "Why do we need four function names to accomplish what appears to be the same objective?" To use these functions requires a lot of additional code. For example: if (float_flag) fabs(x); else if (long_flag) labs(x); else if (int_flag) iabs(x); else dabs(x);
is required in order to use the correct function which would depend upon the data type of the argument. The programmer should not have to work this hard. In C#, one way that can be used to overcome this problem is to use OVERLOADED method names. Method name overloading permits the programmer to use the same method name when the methods have a different signature and are methods for the same class. This is most useful when the different methods have the same or similar objectives. Overloading was done when the same operator symbols: +, -, / and * were used on shorts, ints, longs, floats or doubles. These are different data types and therefore the method arguments would have to be different, yet the objectives are the same and therefore the operator names are the same. In C#, two or more methods within the same scope may have the same name provided they have different signatures. Two methods have the same signatures, if their signatures have all of the following: ●
the same number of arguments
●
the data types of the arguments are the same
●
the data types and the arguments are in the same order
So to have overloaded methods one of the above conditions must be false. The output data type in no way effects the overloading of method names. Several of the examples viewed previously use overloaded methods. The Console static methods: ReadLine() and WriteLine() are both overloaded. For example, there are 19 different Console methods with the name: WriteLine() For example:
file:///D|/1/final/BBL0029.html (1 von 2) [01.12.2007 04:48:06]
Method Name Overloading
static int MAX(int a, int b) { return (a>b?a:b); } static long MAX(long a, long b) { return (a>b?a:b); } static float MAX(float a, float b) { return (a>b?a:b); } static double MAX(double a, double b) { return (a>b?a:b); }
are methods that overload the name MAX. See overload.cs The C# compiler will not return a compiler error when the definitions for the above methods MAX are compiled in the same program since the signatures are all different. Overloading may help the programmer who wants a method to operate on new arguments. Rather than rewriting all previous code to include the new argument, the programmer only needs to overload the name with a new definition. The compiler will then determine from context which name to use. What overloading has done is to reduce the complexity of programming by reducing the number of different method names for the programmer has to remember. Q: When should methods be overloaded? A: When there exists a group of methods with similar results but different signatures. However, the real answer to this question will only come with experience. There will be times in which another technique may be a better choice.
file:///D|/1/final/BBL0029.html (2 von 2) [01.12.2007 04:48:06]
Text File Output
Text File Output Now that the lectures have considered keyboard input and screen output, it is time to consider text file input and output. This can be done using the console or using the Windows GUI environment. Only the console approach will be considered in this part of the lecture. Suppose that a program was to store the customer ID, the name of a customer and the balance due. Suppose that some of the data was to include: 1, George Washington, $1.25. Each of the symbols in this data would be a character. Each of the items: customer ID, first name, last name and balance due would be what are called a field. All of the information about each customer would be called a record. Lastly the data would all be stored into a file in persistent storage. For example the data to be stored could be that which is included in the following table:
Open table as spreadsheet Field 1 Customer ID
Field 2 First Name
Field 3 Last Name
Field 4 Balance Due $1.25
Record 1
1
George
Washington
Record 2
93
Thomas
Doolittle
$32.33
Record 3
134
Jon
Le Moire
$421.33
Record 4
245
Juan
Sanchez
$532.64
Record 5
356
Heinrich
Schmitz
$1,343.23
Record 6
567
Wen
Wu
$4,632.33
Text File Output Classes The classes needed for file I/O are in the namespace: System.IO and therefore each program that will handle file I/ O must contain the following: using System.IO;
Inside of the program's class definition, the text file could be named with a statement like the following: static string fileName = @"C:\temp\datafile.txt";
Note: The @ reduces the need for special characters in strings. The file may be located in any storage location including the temp folder on the C: drive as indicated in the above statement. The text file: datafile.txt is the storage file that will contain the data (there is nothing about this particular name or extension that is required).
file:///D|/1/final/BBL0030.html (1 von 5) [01.12.2007 04:48:07]
Text File Output
Another statement that is needed is one like the following: static FileStream writeFileStream;
This statement defines a reference writeFileStream (this could be any name) to an object of the class FileStream that permits output of data. The class FileStream deals with the access to the environment outside of the program. A statement like the following should also be included in the code: static StreamWriter fileWriter;
The statement above defines a reference fileWriter (this could be any name) to an object of the class StreamWriter that is required for file output of text data. The class StreamWriter handles the data within the program before sending it out. The conditionals below are required to close the objects if they are already open to avoid an exception and thereby a crashing of the program. if( fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close();
These objects for the classes FileStream and StreamWriter will need to be instantiated with statements similar to the following: writeFileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream);
These two statements instantiate the objects referred to by writeFileSream and fileWriter respectively. They are calling constructors for these respective classes. These objects will now provide for the connecting of the program to the data file represented by fileName.
FileMode and FileAccess The FileStream() constructor has several forms with different options to regulate how the file is accessed. FileMode is an enumerated data type whose enumerators regulate how the file will access the data. The FileMode enumerators are: Append, CreateNew, Create, Open, OpenCreate and Truncate
Be careful about using OpenCreate because if the file already exists, the data that is to be written to the file will be placed at the start of the current file data and the data that is there will be ignored and overwritten. FileAccess is also an enumerated data type whose enumerators are:
file:///D|/1/final/BBL0030.html (2 von 5) [01.12.2007 04:48:07]
Text File Output
Read, Write and ReadWrite
WriteLine() for File Output In the code where theData is used for output, there should be a line like the following: fileWriter.WriteLine(theData);
This line of code will send what ever is stored in theData variable to the file buffer associated with fileWriter and from there to the file. Notice the use of the method WriteLine() above. This is similar to the WriteLine() used with the class: Console. The major difference is that the WriteLine() for Console is a static method while the method WriteLine() for StreamWriter is a non-static method and it must therefore be dotted with an object like fileWriter.
Clearing Output Buffers After all of the data for a record has been written to the output buffer fileWriter, the buffer should be cleared to ensure that the data has all been written to the data file. This can be done by using the StreamWriter method Flush () as in the following statement: fileWriter.Flush();
But if the program is no longer going to use fileWriter and the associated file, then the following statement would achieve this same goal: fileWriter.Close();
For an example of output to a text file, view the following: writeToTextFiles.cs. The program: writeToTextFiles.cs implements the customer data specifications listed in the table above. Create a C# Console project. Paste this sample program file into this Visual Studio .NET 2005 project, compile and run the program. After you have stored the records to the disk, open the file: datafile.txt in NotePad and examine its contents. Note: The C: drive was not used in this program. The program will store the data to the drive and folder where the project is located. Open up Windows Explorer and view the location of the data file.) In what folder is the data file located? In C++ it would be in the folder where the source file is located. In the C# program, the data file is located in the folder where the executable file is located, i.e. in the bin\Debug subfolder of the program's folder.
Appending Data to the End of the File If you ran this program more than once, each time the program was run the previous data would be overwritten. To avoid this, the program could have the FileMode enumerator be Append rather than OpenCreate. Modify this program by changing the FileMode to Append. Compile and run it several times. After you have run the program several times, examine the contents of the text file to notice that the data was appended one record after another for each of the program runs.
Checking File Existence The program above provided the name of the file to be processed in the code. However, suppose that the name of the file needs to come from the keyboard or somewhere else in the code. The question would then arise as to
file:///D|/1/final/BBL0030.html (3 von 5) [01.12.2007 04:48:07]
Text File Output
whether the file existed. If the file's name was stored into the string variable: fileName from the keyboard or somewhere else in the program, then the following would test whether the file existed or not by using the static method Exists() of the class: File. This method returns true if the file argument is accessible and false otherwise. For example the keyboard entry into the string fileName could be tested with this method as in the following: if(File.Exists(fileName)) { /// processes this code if the file exists. }
Note: The class File as well as other classes used for working with file I/O will be discussed in more detail in a later lecture.
Keyboard Enter of Output File Name The following code modifies the program above to permit the user to enter the file name. Notice that the user would enter the name and then the program would add the extension: ".txt" so that the user would not need to know the extension and therefore would not need to type it in. static string fileName; // additional code goes here //...... // char response; bool toProcess; do { Console.Write("\nWhat is the name of the file? "); fileName = Console.ReadLine(); fileName += ".txt"; if(File.Exists(fileName)) { Console.WriteLine("\nThat file already exists."); Console.Write("\nReenter the file name? (Y/N) "); response = Char.Parse(Console.ReadLine()); toProcess = false; } else { response = 'N'; toProcess = true; } }while(response=='Y'||response=='y'); if(!toProcess) { Console.WriteLine("\nThe program will now " + "end. \n\nContinue? "); Console.ReadLine(); } else { ..... }
file:///D|/1/final/BBL0030.html (4 von 5) [01.12.2007 04:48:07]
Text File Output
Notice that if the file already exists then the program will either end or permit the user to enter in a name that does not already exist. See testingwriteToTextfiles.cs
file:///D|/1/final/BBL0030.html (5 von 5) [01.12.2007 04:48:07]
Text File Input
Text File Input File Input Classes To read the text data in from storage, the code of the program is similar to that used for writing to the data file. The major difference is that instead of using an object of the class StreamWriter, an object of the class StreamReader is used instead. The following three sections of code for reading data are similar to the three sections of code in the previous part of the lecture where output was discussed. For example the following would define the objects needed for input in this program: static string fileName = @"c:\temp\datafile.txt"; static FileStream readFileStream; static StreamReader fileReader;
and in addition the following statements are needed to check to see if the objects have been instantiated: if(readFileStream!=null) readFileStream.Close(); if( fileReader!=null) fileReader.Close();
The objects for the classes FileStream and StreamReader need to be instantiated with statements similar to the following: readFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream);
ReadLine() for File Input To bring the text data in from the file, a statement like the following method call is needed. fileReader.ReadLine(theData);
Notice the use of method: ReadLine() above. As with WriteLine(), this ReadLine() is a non-static method of the class StreamReader and therefore it must be dotted with the object: fileReader.
Loop to Input Data The program must determine whether all of the data in the text file has been read. To do this a while() loop could be coded to determine whether there is more data to read or not. A statement like the following could be used to determine when the end of the data is reached. The ..... below indicates that there is additional code. while(theData != null) { ..... } file:///D|/1/final/BBL0031.html (1 von 3) [01.12.2007 04:48:08]
Text File Input
For an example of input of the same text file: datafile.txt, view the following: readFromTextFiles.cs. Open this file and paste it into the same console project that was used with writeToTextFiles.cs and then compile and run the program as you did in that example. Notice how the program reads in the data that was stored into the file: datafile. txt on the drive where the program writeToTextFiles.cs stored it as discussed above. (An alternate approach would be to use an entirely new console project and to copy the datafile.txt to the folder for the new project.)
Variable File Names The program above provided the name of the file to be processed in the code. However, suppose that the name of the file needs to come from the keyboard or somewhere else in the code. The question would then arise as to whether the file existed. If the file's name was stored into the string variable: fileName from the keyboard or somewhere else in the program, then the following would test whether the file existed or not by using the static method Exists() of the class: File. This method returns true if the file argument is accessible and false otherwise. For example the keyboard entry into the string fileName could be tested with this method as in the following: if(File.Exists(fileName)) { /// processes this code if the file exists. }
Note: The class File as well as other classes used for working with file I/O will be discussed in more detail in a later lecture. The following code modifies the program above to permit the user to enter the file name. Notice that the user would enter the name and then the program would add the extension: ".txt" so that the user would not need to know the extension and therefore would not need to type it in. static string fileName; // additional code goes here //...... // char response; bool toProcess; do { Console.Write("\nWhat is the name of the file? "); fileName = Console.ReadLine(); fileName += ".txt"; if(!File.Exists(fileName)) { Console.WriteLine("\nThat file does not exist."); Console.Write("\nReenter the file name? (Y/N) "); response = Char.Parse(Console.ReadLine()); toProcess = false; } else { response = 'N'; toProcess = true; } }while(response=='Y'||response=='y'); if(!toProcess) {
file:///D|/1/final/BBL0031.html (2 von 3) [01.12.2007 04:48:08]
Text File Input
Console.WriteLine( "\nThe program will now end. \n\nContinue? "); Console.ReadLine(); } else { // // continue with the file processing. // }
Observe the above code at the top of the program: testingInFileName.cs. Copy this file to the same project that you did for the program: readFromTextFiles.cs that you used above. When the program: testingInFilename.exe begins, enter different file names. For example use: testing and datafile. Notice that when testing is entered, the program catches the problem and permits reenter of the correct name: datafile. When datafile is entered, the program operates correctly. In addition if the user wished to terminate the program, this is also permitted.
file:///D|/1/final/BBL0031.html (3 von 3) [01.12.2007 04:48:08]
Windows Forms and Text File I/O
Windows Forms and Text File I/O Windows Forms and Text File Output Specifications: Suppose that you were requested to write an accounts payable program that would receive data entered from the keyboard and store it to a text file using the C# GUI interface. Suppose further that the data to be entered is: company name and amount due. The GUI should include a button labeled: Post that would append the data to the file: accountsPayable.txt. The form should look like the following:
where the top two blanks are the text boxes and the bottom one is a button. The following is some sample data (however the dollar signs and the commas should not be entered into the program since this would be character data rather than numeric data):
Company Name Amount Due
The Big One
Another One
Again One
Still More
$10,000.00
$1,422.33
$23,320.21
$235.34
Design: Form1 Set companyName = "" Set amountDue = "0.00" Open for writing to the data file End Posting Open file accountsPayable.txt Write companyName to file Write amountDue to file Set companyName = ""; Set amountDue = "0.00"; End
Coding: To begin, create a Windows form using the project name: accountsPayable. Click on the form and using the Properties change the Text of the form to Accounts Payable. From the Toolbox drag two labels, two textboxes and a button to the form. ●
properties of the labels
file:///D|/1/final/BBL0032.html (1 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
●
●
❍
label 1 properties: Font: Bold, Text: Company Name Location: 12, 43, Size: 120, 17
❍
label 2 properties: font: Bold, text: Amount Due, location: 12, 96, size: 96, 17
properties of the textboxes ❍
textbox 1 properties: font: Bold, name: companyName, location: 138, 43, size: 142, 22, TabIndex: 1
❍
textbox 2 properties: font: Bold, name: amountDue, location: 138, 96, size: 142, 22 , TabIndex: 2
properties of button ❍
button 1 properties: font: Bold, text: Post, name: postPayables, location: 12, 171, size: 75, 23, TabIndex: 3 When you have made the above modifications, the form should look like the following:
To complete the coding, click on the form and select: View Code. Place the following at the top of Form1.cs with the other using statements: using System.IO;
In the class: Form1 define the following data members: static string fileName = @"accountsPayable.txt"; static FileStream writeFileStream; static StreamWriter fileWriter;
By making the above as static data members, they will be accessible inside of any of the Form1 methods without the need to define an object of the class Form1 nor will it be necessary to dot it with the name of the class when they are used. In the Form1() constructor do the following:
file:///D|/1/final/BBL0032.html (2 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = "0.00"; writeFileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); }
Next double click the Post button and change its event handler to the following: private void thePosting_Click(object sender, EventArgs e) { fileWriter.WriteLine(companyName.Text); fileWriter.WriteLine(amountDue.Text); fileWriter.Flush(); companyName.Text = ""; amountDue.Text = "0.00"; companyName.Focus(); }
As indicated previously when text file I/O was discussed, the first two statements would write out the data from the textboxes to the text file: accountsPayable.txt. The third statement would flush out the output buffer to send the data to the file. The fourth and fifth statement would clear the data in the textboxes and the sixth statement would return the cursor to the text box: companyName. Note: While the program is running, use a mouse to attempt to change the size of the form. Was it possible? Would this be a good idea to have the form resizable? In this particular program, allowing the user to resize the form is not a good idea. To prevent this from happening, set the Maximum Size and the Minimum Size to the same values as the Size for Form1. To see the program link to: Form1.cs, Form1.Designer.cs and its corresponding Program.cs. To use these three files, create a Windows project: accountsPayable. Copy each of these three files into their corresponding files in the project. Compile and run the program. After you have run the program on several records, observe the data file and its contents. Close and run the program again. Open the data file once again and notice that the data from the second run is appended to the data in the file.
Programming C# Windows Program to Output Data for Excel If the fields had commas between them and the output data file had an extension of .csv, then the file could be imported into Excel. To see how this could be done, modify the Form1.cs above to contain the following: public partial class Form1 : Form { static string fileName = @"accountsPayable.csv"; static FileStream writeFileStream; static StreamWriter fileWriter; public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = "0.00"; writeFileStream = new FileStream(fileName,
file:///D|/1/final/BBL0032.html (3 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } private void thePosting_Click(object sender, EventArgs e) { fileWriter.Write(companyName.Text); fileWriter.Write(","); fileWriter.WriteLine(amountDue.Text); fileWriter.Flush(); companyName.Text = ""; amountDue.Text = "0.00"; companyName.Focus(); } }
Run at least ten companies through the program modification above. Then download APTotals.xls and open it into Excel. When the file is opened, it should appear similar to the following:
Notice that in the file APtotals.xls, there is text: Total AP in A20 and in B20 is the Sum of B1–B19. Further the cells B1–B20 are formatted into US currency. Click on the cell: A1. Next, click on Data on the menu bar. Follow this by clicking on: Import External Data and then on Import Data. Making these selections, Excel should appear as in the following graphic:
file:///D|/1/final/BBL0032.html (4 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
Using these selections, open the file: accountsPayable.csv. The following dialog should then appear:
Click on the Next button and the following dialog should appear:
file:///D|/1/final/BBL0032.html (5 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
In the Delimiters uncheck Tab and check Comma. Next click the Finish button at the bottom. A dialog like the following should appear (Notice that the data will be placed beginning at A1):
Now click the OK button and in the spreadsheet should appear data like the following:
file:///D|/1/final/BBL0032.html (6 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
Notice how the data appears formatted as would be needed. A C# student: Geoff asked how a C# Windows program could be used to interact with Excel. The example above illustrates his request. Note: It is also possible to create an Excel spreadsheet populated with data and to import the data into a C# program. This topic will be discussed later in the lectures.
Windows Forms and Text File Input Specifications: Suppose that you were requested to create a Windows GUI program that can read the data created by the program above one record at a time and display the data read into textboxes. In addition the program should total the account payable amount as it is read. The total accounts payable amounts should then be posted to the Total AP Due text box. The form should look like the following where the top three are text boxes and the bottom is a button:
file:///D|/1/final/BBL0032.html (7 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
Design: The following is the pseudo code for the program Form Set companyName = "" Set amountDue = "0.00" Set totalAPDue = "0.00" Open File Set totalDue = 0.00 End Next IF(file not at end of file)THEN { Read from file into companyName; Read from file into theAmount totalDue += theAmount; Set amountDue = String.Format(theAmount); Set totalAPDue = String.Format(totalDue); } ELSE Display "There is no more data to read." ENDIF End
Coding: To begin, create a Window's project using the project name: viewAccountsPayable. Click on the form and using the Properties change the Text of the form to View Accounts Payable. Set the Maximum Size and the Minimum Size to the same values as the Size. From the Toolbox drag three labels, three textboxes and a button to the form. Change their properties to the following: ●
●
properties of the labels ❍
label 1 properties: Font: Bold, Text: Company Name Location: 40, 27, Size: 120, 17
❍
label 2 properties: font: Bold, text: Amount Due, location: 43, 70 ,size: 96, 17
❍
label3 properties font: Bold, text: Total Amount Due: location: 43, 120, size: 104, 17
properties of the textboxes
file:///D|/1/final/BBL0032.html (8 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O ❍
textbox 1 properties: font: Bold, name: companyName, location: 174, 27, size: 100, 22, ReadOnly: True
❍
textbox 2 properties: font: Bold, name: amountDue, location: 174, 70, size: 100, 22, ReadOnly: True
❍
●
textbox 3 properties: font: Bold, name: totalAmountDue, location: 174, 120, size: 100, 22, ReadOnly: True
properties of button ❍
button 1 properties: font: Bold, text: Next, name: viewPayables, location: 12, 171, size: 75, 23, TabIndex: 1
After completing the above steps, the form should look like the following:
Add the following to the top of Form1.cs: using System.IO;
Add the following definitions to the class: Form1: static string fileName = @"accountsPayable.txt"; static FileStream readFileStream; static StreamReader fileReader; static double totalDue;
Modify the Form1 constructor to the following: public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = String.Format("{0:c}", 0.00); totalAPDue.Text = String.Format("{0:c}", 0.00); readFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream); file:///D|/1/final/BBL0032.html (9 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
totalDue = 0.00; }
The purpose of the second, third and fourth statements above are to initialize the three textboxes. The next two lines make a connection to the file for the purpose of reading in the data. The last line sets the variable: totalDue to 0.00 for the purpose of adding the values as they are read in. Next double click on the button: Next and change its event handler to the following: private void nextAP_Click(object sender, EventArgs e) { if (fileReader.EndOfStream == false) { companyName.Text = fileReader.ReadLine(); double theAmount = double.Parse(fileReader.ReadLine()); totalDue += theAmount; amountDue.Text = String.Format("{0:c}", theAmount); totalAPDue.Text = String.Format("{0:c}", totalDue); } else MessageBox.Show("There is no more data to read."); }
Notice the use of the StreamReader data member: EndOfStream to control access to fileReader.ReadLine(). The Console program viewed above used a while() loop and theData != Null to stop data entry. However that approach would not work here. Notice that a selection is set up to determine if all of the data in the file has been read. Inside of the then part of the selection are five statements to implement the reading of the data, the adding up of the amounts due and the displaying the dollar amounts of the amount due the current record and the total amount due. The else part of the selection contains a call to a MessageBox to inform the user when all of the data has been read. (More will be discussed about the MessageBox later in the lectures.) To complete the implementation and to test the program the data file: accountsPayable.txt that was created in the program: accountsPayable.cs needs to be copied to the bin\Debug folder of the current project. To View the code see: Form1.cs, Form1.Designer.cs and Program.cs. Comment: Above it was discussed how to output to a file that could then be used by Excel. It is also possible to create a file in Excel, save it as comma separated data: i.e. a .csv file and then using a C# Windows program input the data into a program like the one above. To do this would require the separation of the data into two strings: one for the company name and one for the amount owed. This would require the use of a string method to find the comma and then to separate the data into the company name up to the comma and the amount owed after the comma. This topic will be discussed later when strings and string builders are discussed. Note: One of the important issues that has not been considered in the discussion of Windows programs so far has been what happens if the user does not enter a value in a field. Or what if the value to be entered into a textbox is to be a numeric value and the user enters characters instead. This topic will be discussed later in a lecture on data validation.
file:///D|/1/final/BBL0032.html (10 von 10) [01.12.2007 04:48:09]
UML Charts and Class Diagram for Structures
UML Charts and Class Diagram for Structures Example 1: In a previous lecture it was demonstrated how to use Visio to create a UML chart of an enumerated data type and how to use the Visual Studio .NET 2005 IDE to not only create an enumerated data type in the program but to also create a graphic that would depict the enumerated data type. In this example it will be demonstrated how to use Visio and the Visual Studio .NET 2005 IDE to create the code for the structure Customer and how to create a graphic of the structure as well. The structure Customer is defined in the following code: public struct Customer { private string name; private decimal owes; public void setName(string aName) { name = aName; } public string getName() { return name; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public decimal getOwes() { return owes; } }
Open Visio to create UML charts. Select the Class icon and drag it onto the graphic. Double click the Class icon. Change the Name: to Customer and change and the Stereotype: option to struct which should appear as in the following:
file:///D|/1/final/BBL0033.html (1 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Next click the OK button and the UML chart should now appear like the following:
The next step is to add the fields and the methods to the UML chart. Begin by double clicking the graphic and the following appears:
Notice that in Visio the fields are called: Attributes and the methods are called: Operations. First click on the Attributes from the Categories options. What should appear should be like the following:
file:///D|/1/final/BBL0033.html (2 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Click in the Attribute column and add each of the field names, their data type and their visibility as private (i.e. a will appear in the UML chart) as indicated in the example code above. After making these changes, click the OK button. What should appear would be like the following:
The next step is to enter the structure's methods. Again double click the structure icon and then select Operations from the Categories: options. What you should see will be like the following:
file:///D|/1/final/BBL0033.html (3 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Clicking in the Operation column, enter the name of each method and in the Return Type column enter the method's return type. What you should see is something like the following:
The next step is to enter the signature of setName(). To do this, click on the Properties button on the right side. Something like the following will appear:
Clicking in the Parameter column enter aName and click into the Type column and enter C#::string. After the signature for setName() is entered, do the same for setOwes(). Clicking the OK button the UML chart should look like the following:
file:///D|/1/final/BBL0033.html (4 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Begin by creating a console project called: AccountsReceivable. As soon as the project opens, click on Project on the menu bar. When you do, what appears should be like the following:
Next click on the option: Add New Item. When the Add New Item options appear, select Class Diagram.
file:///D|/1/final/BBL0033.html (5 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Next should appear the following and when it does select Struct by draging the icon onto the Class Diagram form:
When the New Struct form appears enter Customer as the name. Rather than creating an new file, the structure will be placed into the file: Program.cs by clicking the Add to existing file option and then typing in the name of file:///D|/1/final/BBL0033.html (6 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
the file: Program.cs.(In a Windows program you might place the structure's code into Form1.cs) Follow this by clicking the OK button.
An icon like the following should now appear on the screen:
The structure is to have the following fields: private string name; private decimal owes;
and the following methods: public void setName(string aName) { name = aName; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public string getName() {
file:///D|/1/final/BBL0033.html (7 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
return name; } public decimal getOwes() { return owes; }
To include these features, right click on the Customer icon to make the following options appear:
First select the Field option and type in the word: name for the field. After this, click the right mouse button to display the following options and then select Properties:
file:///D|/1/final/BBL0033.html (8 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
The Properties menu will appear like the following:
In the Type property, change from the default int to string. Leave the Access as private. Following these same steps, create the field: owes and make its Type: decimal and Access as private. After completing the fields, the next step is to add the methods. Right click on the name of the structure and select Add and then Method.
file:///D|/1/final/BBL0033.html (9 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Enter the name of the first method: setName. After typing in the name, right click on the name of the method and select Properties and the following should appear:
file:///D|/1/final/BBL0033.html (10 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Notice that it is possible to change the output type from the default void to any option needed. In addition one of the Properties options is Method Signature. In addition the Access is by default public. The Properties options do not seem to permit the entry of the signature so this will be handled later when viewing the code. Next follow the steps used for the method setName() and add the public methods: ●
void setOwes()
●
string getName()
●
decimal getOwes()
After making these additions to the structure: Customer, the icon should appear as the following:
file:///D|/1/final/BBL0033.html (11 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
To complete the next step, do a right mouse button and select View Code. When you do, the following code should appear in Program.cs: public struct Customer { private string name; private decimal owes; public void setName() { throw new System.NotImplementedException(); } public string getName() { throw new System.NotImplementedException(); } public void setOwes() { throw new System.NotImplementedException(); } public decimal getOwes() { throw new System.NotImplementedException(); } }
Next the signatures of setName() and setOwes() have to be completed and the body of each method needs to be
file:///D|/1/final/BBL0033.html (12 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
rewritten removing the throw statements. When this is completed, the code should now appear like the following: public struct Customer { private string name; private decimal owes; public void setName(string aName) { name = aName; } public string getName() { return name; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public decimal getOwes() { return owes; } }
For the program documentation, the graphic should also be saved. Example 2: In the example above, the access member methods were used. In addtion to access member methods, C# can also implement properties for the fields of a structure as was discussed in a previous example in this section. In that discussion the structure Customer was this time written with properties as in the following: public struct Customer { private string name; private decimal owes; public string Name { get { return name; } set { name = value; } } public decimal Owes { get { return owes; } set { owes = value; } }
file:///D|/1/final/BBL0033.html (13 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
The next step will be to create a UML chart that implements structure properties. Using the same technique as in the above example, the fields are entered in as before. The problem with Visio is that it does not appear that there are any features to implement, properties. Therefore what I did was to create methods whose names were the following: Name get{} set{}
and Owes get{} set{}
When the UML chart was completed, it appeared as in the following:
Notice that the parenthesis appears above even though they should not. I was unable to find a way to eliminate them. Create a console project called: NEWAR. Once it appears, click on Project on the Menu Bar. From the choices, again select, Add New Item. The item to be added is again, Class Diagram. This again will create a Class Diagram document on to which drag a structure. Name the structure Customer. Recall that this structure may be placed into any file. To simulate a case where the structure may be placed into the component library, this time permit the structure to be placed into the default file which is Customer.cs. As before, create the two fields: name and owes. Instead of creating the methods as in the previous example, select Property from the menu selection as in the following:
file:///D|/1/final/BBL0033.html (14 von 17) [01.12.2007 04:48:11]
UML Charts and Class Diagram for Structures
When creating the Property Name change its data type to string and when creating Owes change its data type to decimal. This should create a graphic like the following:
Do a right click on the graphic and select View Code. The structure's definition should appear like the following: public struct Customer { private string name; private decimal owes;
file:///D|/1/final/BBL0033.html (15 von 17) [01.12.2007 04:48:11]
UML Charts and Class Diagram for Structures
public string Name { get { throw new System.NotImplementedException(); } set { } } public decimal Owes { get { throw new System.NotImplementedException(); } set { } } }
What now needs to be done is to remove the throw statements from each get{} and to enter the correct code into each get{} and each set{} as in the following: public struct Customer { private string name; private decimal owes; public string Name { get { return name; } set { name = value; } } public decimal Owes { get { return owes; } set { owes = value; } } }
file:///D|/1/final/BBL0033.html (16 von 17) [01.12.2007 04:48:11]
UML Charts and Class Diagram for Structures
This would complete the coding of the structure Customer. What should of course be done now would be to save the graphics for each of these two charts.
file:///D|/1/final/BBL0033.html (17 von 17) [01.12.2007 04:48:11]
Lecture 3 Examples
Lecture 3 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
Accounts Payable (output)
Demonstrates a Windows program which outputs data to a text file.
●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Accounts Payable (input) ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Demonstrates a Windows program which inputs data from a text file.
APTotals.xls
An Excel spreadsheet that demonstrates inputting data into the spreadsheet which would output into a text file.
function1.cs
Demonstrates how to use functions in C#.
function2.cs
Demonstrates how to use functions with arguments. One of the arguments is passed by value and the other is passed by reference ref.
function3.cs
Demonstrates how to use functions with arguments. One of the arguments is passed by value and the other is passed by the reference out.
function4.cs
Demonstrates how it is possible that the function: Main() calls another function that does all of the work.
newfact.cs
demonstrates how to use recursive functions in C#
newgcd.cs
Demonstrates how to use recursive functions in C#.
overload.cs
Demonstrates how to overload functions in C#.
readFromTextFiles.cs
Demonstrates text file input.
struct0.cs
Illustrates a struct where the definition of an instance initializes the data members.
struct1.cs
Illustrates a struct definition, struct variable definition, struct assignment, and the manipulation of struct members‥
struct2.cs
Illustrates a struct definition, struct variable definition, struct assignment, and the manipulation of struct members.
struct3.cs
Illustrates a struct with methods including a constructor.
struct4.cs
Illustrates a struct where the definition of a non-default constructor is included.
struct5.cs
Illustrates a struct where the definition of an instance uses the new operator and the definition of the structure does not have a constructor.
struct6.cs
Illustrates a struct where the definition of default constructor is included. However it will not compile.
struct10.cs
Illustrates a struct with private data members and public methods.
struct11.cs
Illustrates that the assignment operator is overloading on structures.
structToString.cs
Illustrates how a struct can override the ToString() method.
structureProperties.cs
Illustrates a structure with public properties of the data members instead of using public methods.
testingInFileName.cs
Demonstrates the testing of the name of the text file to see if it exits before input.
testingwriteToTextfiles.cs
Demonstrates how to test to determine if a text file exists before output. It only permits continuation if the file did not exist.
writeToTextfiles.cs
Demonstrates text file output.
// program_id Form1.Designer.cs // written_by don voils // date_written 6/28/2006 // description This program provides for the output of data from a Windows form // to a text file. // namespace accountsPayable { partial class Form1
file:///D|/1/final/BBL0034.html (1 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
{ /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.companyName = new System.Windows.Forms.TextBox(); this.amountDue = new System.Windows.Forms.TextBox(); this.thePosting = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(12, 43); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(120, 17); this.label1.TabIndex = 0; this.label1.Text = "Company Name"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(12, 96); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 17); this.label2.TabIndex = 1; this.label2.Text = "Amount Due"; // // companyName // this.companyName.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.companyName.Location = new System.Drawing.Point(138, 43); this.companyName.Name = "companyName"; this.companyName.Size = new System.Drawing.Size(142, 22); this.companyName.TabIndex = 1; // // amountDue // this.amountDue.Location = new System.Drawing.Point(138, 96); this.amountDue.Name = "amountDue"; this.amountDue.Size = new System.Drawing.Size(142, 22); this.amountDue.TabIndex = 2; // // thePosting // this.thePosting.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0)));
file:///D|/1/final/BBL0034.html (2 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
this.thePosting.Location = new System.Drawing.Point(12, 171); this.thePosting.Name = "thePosting"; this.thePosting.Size = new System.Drawing.Size(75, 23); this.thePosting.TabIndex = 3; this.thePosting.Text = "Post"; this.thePosting.UseVisualStyleBackColor = true; this.thePosting.Click += new System.EventHandler(this.thePosting_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 267); this.Controls.Add(this.thePosting); this.Controls.Add(this.amountDue); this.Controls.Add(this.companyName); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.MaximumSize = new System.Drawing.Size(300, 300); this.MinimumSize = new System.Drawing.Size(300, 300); this.Name = "Form1"; this.Text = "Accounts Payable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox companyName; private System.Windows.Forms.TextBox amountDue; private System.Windows.Forms.Button thePosting; } }
// program_id Form1.cs // written_by don voils // date_written 6/28/2006 // description This program provides for the output of data from a Windows form // to a text file. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace accountsPayable { public partial class Form1 : Form { static string fileName = @"accountsPayable.txt"; static FileStream writeFileStream; static StreamWriter fileWriter; public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = "0.00"; writeFileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } private void thePosting_Click(object sender, EventArgs e) { fileWriter.WriteLine(companyName.Text); fileWriter.WriteLine(amountDue.Text);
file:///D|/1/final/BBL0034.html (3 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
fileWriter.Flush(); companyName.Text = ""; amountDue.Text = "0.00"; companyName.Focus(); } } }
// program_id Program.cs // written_by don voils // date_written 6/28/2006 // description This program provides for the output of data from a Windows form // to a text file. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace accountsPayable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id function1.cs // written?_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use functions in C# // using System;
class theProgram { static void Main() { // Receives and adds the value of each emplyee's payroll // until the user requests to stop. // calculatePayroll(); // Causes the running of the program to stop // and waits for the pressing of the enter key. // This is needed most when executing the program // using Debug. // Console.ReadKey(); } static void calculatePayroll() { // This char used to control the loop // char toContinue = 'y'; // this int keeps track of the number of employees //
file:///D|/1/final/BBL0034.html (4 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
int numberEmployees = 0; // The doubles required for the calculations // double totalPayroll = 0; do { ++numberEmployees; // Clears the screen. // Console.Clear();
// Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); totalPayroll += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); }while((toContinue == 'y') || (toContinue == 'Y')); do { // Clears the screen. // Console.Clear(); // Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",totalPayroll); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Request and receive whether to continue. // Console.Write("\n\nDo you want to end program? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Clears the screen. //
Console.Clear(); }while((toContinue != 'y') && (toContinue != 'Y')); } }
// program_id function2.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use functions with arguments. // One of the arguments is passed by // value and the other is passed by // reference ref. // using System;
class theProgram { static void Main() {
file:///D|/1/final/BBL0034.html (5 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
// The doubles required for the calculations // double totalPayroll = 0.00; // Receives and adds the value of each emplyee's payroll // until the user requests to stop. // calculatePayroll(ref totalPayroll); showTotalPayroll(totalPayroll); Console.ReadKey(); } // Notice the use of the keyword ref both in the call above // and in the definition below. // static void calculatePayroll(ref double theTotal) { // This char used to control the loop // char toContinue = 'y'; // this int keeps track of the number of employees // int numberEmployees = 0;
do { ++numberEmployees; // Clears the screen. // Console.Clear(); // Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); theTotal += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); }while((toContinue == 'y') || (toContinue == 'Y')); } // Notice that the argument theTotal does not need to be passed by reference // so the modifier ref is no included in the definition below or the call above. // static void showTotalPayroll(double theTotal) { char toContinue; do { // Clears the screen. // Console.Clear(); // Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",theTotal); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Request and receive whether to continue. // Console.Write("\n\nDo you want to end program? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Clears the screen. // Console.Clear(); }while((toContinue != 'y') && (toContinue != 'Y'));
file:///D|/1/final/BBL0034.html (6 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
} }
// program_id function3.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use functions with arguments. // One of the arguments is passed by // value and the other is passed by // the reference out. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double totalPayroll; // Receives and adds the value of each emplyee's payroll // until the user requests the process to stop. // calculatePayroll(out totalPayroll); showTotalPayroll(totalPayroll); Console.ReadKey(); } static void calculatePayroll(out double theTotal) { // This char used to control the loop // char toContinue = 'y'; // Since the variable theTotal is passed in with no value // using the modifier out, it must be initialized. // theTotal = 0.00; // this int keeps track of the number of employees // int numberEmployees = 0; do { ++numberEmployees; // Clears the screen. // Console.Clear(); // Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); theTotal += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); }while((toContinue == 'y') || (toContinue == 'Y')); } // Even though the argument theTotal was passed into the method // calculatePayroll() by reference, this feature is not needed // in the following method so it is passed in by value. //
file:///D|/1/final/BBL0034.html (7 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
static void showTotalPayroll(double theTotal) { char toContinue; do { // Clears the screen. // Console.Clear(); // Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",theTotal); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Request and receive whether to continue. // Console.Write("\n\nDo you want to end program? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Clears the screen. // Console.Clear(); }while((toContinue != 'y') && (toContinue != 'Y')); } }
// program_id function4.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how it // is possible that the function: Main() // calls another function that does all // of the work. // using System;
class theProgram { static void Main() { StaringProgram(); } static void StaringProgram() { // The doubles required for the calculations // double totalPayroll; // Receives and adds the value of each emplyee's payroll // until the user requests to stop. // calculatePayroll(out totalPayroll); showTotalPayroll(totalPayroll); Console.ReadKey(); } static void calculatePayroll(out double theTotal) { // This char used to control the loop // char toContinue = 'y'; // Since the variable theTotal comes in with no value // using the modifier out, it must be initialized. //
file:///D|/1/final/BBL0034.html (8 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
theTotal = 0; // this int keeps track of the number of employees // int numberEmployees = 0; do { ++numberEmployees; // Clears the screen. // Console.Clear(); // Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ", numberEmployees); theTotal += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); } while ((toContinue == 'y') || (toContinue == 'Y')); } static void showTotalPayroll(double theTotal) { char toContinue; do { // Clears the screen. // Console.Clear(); // Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}", theTotal); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Request and receive whether to continue. // Console.Write("\n\nDo you want to end program? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Clears the screen. // Console.Clear(); } while ((toContinue != 'y') && (toContinue != 'Y')); } }
// program_id newfact.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use recursive functions in C# // using System;
class theProgram { static void Main() { int number1; Console.Write("What is the number? "); number1 = Int32.Parse(Console.ReadLine());
file:///D|/1/final/BBL0034.html (9 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
Console.WriteLine("\n{0} factorial is {1}\n\n",number1,factorial(number1)); Console.ReadKey(); } static long factorial(int numb) { return (numb==0)?(1):(numb * factorial(numb-1)); } }
// program_id newgcd.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use recursive functions in C# // using System;
class theProgram {
static void Main() { int int1, int2; Console.Write("What is the first number? "); int1 = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the second number? "); int2 = Int32.Parse(Console.ReadLine()); Console.WriteLine("\nThe GCD of {0} and {1} is {2}\n",int1,int2,newGCD(int1,int2)); Console.ReadKey(); } static int newGCD(int numb1, int numb2) { return (numb1<0) ? newGCD(-numb1,numb2):((numb2==0)? numb1:newGCD(numb2,numb1%numb2)); } }
// program_id overload.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // overload functions in C# // using System;
class theProgram {
static void Main() { int int1=5, int2=6; long long1=50000, long2= 60000; float float1=5.0f, float2=6.0f; double double1=500000.00, double2=600000.00; Console.WriteLine("This is a test of overloading the functional name MAX\n\n"); Console.WriteLine("The maximum of the integers {0} and {1} is {2}", int1,int2,MAX(int1,int2));
file:///D|/1/final/BBL0034.html (10 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
Console.WriteLine("The maximum of the longs {0} and {1} is {2}", long1,long2,MAX(long1,long2)); Console.WriteLine("The maximum of the floats {0:n} and {1:n} is {2:n}", float1,float2,MAX(float1,float2)); Console.WriteLine("The maximum of the doubles {0:n} and {1:n} is {2:n}\n\n", double1,double2,MAX(double1,double2)); Console.ReadKey(); } static int MAX(int a, int b) { return (a>b?a:b); } static long MAX(long a, long b) { return (a>b?a:b); } static float MAX(float a, float b) { return (a>b?a:b); } static double MAX (double a, double b) { return (a>b?a:b); } }
// program_id readFromTextFiles.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates text file input. // using System; using System.IO; namespace readFromTextFiles { class InPutData { static string fileName = "datafile.txt"; static FileStream readFileStream; static StreamReader fileReader; static void Main(string[] args) { OpentoReadDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; customerFirstName = fileReader.ReadLine(); while(customerFirstName != null) { customerLastName = fileReader.ReadLine(); Console.WriteLine("\nCustomer's name: "+customerFirstName+" " +customerLastName); customerID = fileReader.ReadLine(); Console.WriteLine("Customer's ID: "+customerID); customerBalanceDue = decimal.Parse(fileReader.ReadLine()); Console.WriteLine(String.Format("Balance due: {0:c}\n",customerBalanceDue)); customerFirstName = fileReader.ReadLine(); } CloseDataFiles(); Console.ReadKey();
file:///D|/1/final/BBL0034.html (11 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
} static void OpentoReadDataFile() { if(readFileStream!=null) readFileStream.Close(); if( fileReader!=null) fileReader.Close(); readFileStream = new FileStream(fileName,FileMode.Open,FileAccess.Read); fileReader = new StreamReader(readFileStream ); } static void CloseDataFiles() { fileReader.Close(); readFileStream.Close(); } } }
// program_id scope1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use local variables in C# functions. // using System;
class theProgram { static void Main() { int x = 5; overThere(x); Console.WriteLine("\nAfter the function, the outside x = {0}\n",x); }
static void overThere(int a) { int x = 7; Console.WriteLine("\nIn the function, the inside x = {0}",x); Console.WriteLine(" & the outside x = {0}",a); } }
// program_id static1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use static variables in C# // using System;
class theProgram { static int x = 7; static void Main() { // Notice there there is no automatic variable x inside of Main() // The static variable will be called in each of the folowing statements. // overThere(x); Console.WriteLine("Static variable from outside of Main() where x = {0}\n", x); overThere(x); Console.WriteLine("Static variable from outside of Main() where x = {0}\n", x);
file:///D|/1/final/BBL0034.html (12 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
} static void overThere(int a) { // Notice there there is no automatic variable x inside of overThere() // The static variable will be called in each of the folowing statements. // Console.WriteLine("Static variable x = {0}" + " inside of overThere()\n & passed by value x = {1}\n",x,a); ++x; Console.WriteLine("Incremented static variable inside of overThere().\n"); } }
//program_id struct0.cs //author don voils //date written 6/10/2006 //Description This program illustrates a struct // where the definition of an instance // initializes the data members. // using System; public struct Customer { public string name; public decimal owes; } class theProgram { static void Main() { Customer theOne = new Customer(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.name, theOne.owes); Console.ReadKey(); } }
//program_id struct1.cs //author don voils //date written 12/22/2006 //Description This program illustrates a struct // definition, struct variable definition, // struc assignment, and the manipulation // of struc members. // using System; public struct Customer { public string name; public decimal owes; } class theProgram { static void Main() { Customer theOne; Console.Write("\nWhat is the customer's name? "); theOne.name = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",theOne.name); theOne.owes = Decimal.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n",theOne.name,theOne.owes); Console.ReadKey(); }
file:///D|/1/final/BBL0034.html (13 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
}
//program_id struct2.cs // //author don voils //date written 12/22/2006 // //Description This program illustrates a struc // definition, struc variable definition, // struc assignment, and the manipulation // of struc members. // using System; public enum WorkType {SALARIED, HOURLY}; public struct Date { public int theMonth, theDay, theYear; } public struct Employee { public Date hireDate; public WorkType salaryType; public string employeeLastName, employeeFirstName; public decimal unitPay; }
class theProgram { static void Main() { Employee newStaff; Console.Write("\nWhat is the new employee's first name? "); newStaff.employeeFirstName = Console.ReadLine(); Console.Write("\nWhat is the new employee's last name? "); newStaff.employeeLastName = Console.ReadLine(); Console.Write("\nWhat is {0} {1}'s pay per unit of work? ", newStaff.employeeFirstName,newStaff.employeeLastName); newStaff.unitPay = Decimal.Parse(Console.ReadLine()); Console.Write("\nWhat month was {0} {1} hired? ", newStaff.employeeFirstName,newStaff.employeeLastName); newStaff.hireDate.theMonth = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat day was {0} {1} hired? ", newStaff.employeeFirstName,newStaff.employeeLastName); newStaff.hireDate.theDay = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat year was {0} {1} hired? ", newStaff.employeeFirstName,newStaff.employeeLastName); newStaff.hireDate.theYear = Int32.Parse(Console.ReadLine()); int salaryType; Console.Write("\nIs the employee salaried (0) or hourly {1)? "); salaryType = Int32.Parse(Console.ReadLine()); newStaff.salaryType= (WorkType)salaryType; Console.Clear(); Console.WriteLine("\n\nDid you say that the name of the new employee is {0} {1}", newStaff.employeeFirstName,newStaff.employeeLastName); Console.WriteLine("who was hired on {0}/{1}/{2}" ,newStaff.hireDate.theMonth ,newStaff.hireDate.theDay ,newStaff.hireDate.theYear);
file:///D|/1/final/BBL0034.html (14 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
if (newStaff.salaryType==WorkType.SALARIED) Console.WriteLine("and is salaried at {0:c}?" ,newStaff.unitPay); else Console.WriteLine("and is hourly at {0:c}?" ,newStaff.unitPay); Console.ReadKey(); } }
//program_id struct3.cs //author don voils //date written 12/22/2006 //Description This program illustrates a struc // with methods including a constructor. // using System;
public struct Circle { private double theRadius; public Circle(double Radius) { theRadius = Radius; } public void setRadius(double Radius) { theRadius = Radius; } public double getRadius() { return theRadius; } public double getArea() { double PI = 3.14159; return (theRadius * theRadius * PI); } public double getCircumference() { double PI = 3.14159; return (2 * theRadius * PI); } } class theProgram { static void Main() { Circle theCircle = new Circle(); Console.Write("What is the radius of the circle? "); theCircle.setRadius(Double.Parse(Console.ReadLine())); Console.Clear(); Console.WriteLine("\n\nThe area of the circle is {0}",theCircle.getArea()); Console.WriteLine("\nThe circumference of the circle is {0}\n\n",theCircle.getCircumference()); Console.ReadKey(); } }
//program_id struct4.cs //author don voils //date written 12/22/2006 //Description This program illustrates a struc // where the definition of a non-default
file:///D|/1/final/BBL0034.html (15 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
// constructor is included. // using System; public struct Customer { public string name; public decimal owes; public Customer(string aName,decimal TheyOwe) { name = aName; owes = TheyOwe; } } class theProgram { static void Main() { Console.Write("\nWhat is the customer's name? "); string aName = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",aName); decimal TheyOwe = Decimal.Parse(Console.ReadLine()); Customer theOne = new Customer(aName,TheyOwe); Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.name,theOne.owes); Console.ReadKey(); } }
//program_id struct5.cs //author don voils //date written 12/22/2006 //Description This program illustrates a struct // where the definition of an instance // uses the new operator and the // definition of the structure // does not have a constructor. // using System; public struct Customer { public string name; public decimal owes; } class theProgram { static void Main() { Customer theOne = new Customer(); Console.Write("\nWhat is the customer's name? "); theOne.name = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",theOne.name); theOne.owes = Decimal.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n",theOne.name,theOne.owes); Console.ReadKey(); } }
//program_id struct6.cs //author don voils
file:///D|/1/final/BBL0034.html (16 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
//date written 12/22/2006 //Description This program illustrates a struc // where the definition of default // constructor is included. However // it will not ocmpile. // using System; public struct Customer { public string name; public decimal owes; public Customer() { name = ""; owes = 0.0; } } class theProgram { static void Main() { Customer theOne = new Customer(); Console.Write("\nWhat is the customer's name? "); theOne.name = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",theOne.name); theOne.owes = Decimal.Parse(Console.ReadLine()); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.name,theOne.owes); } }
//program_id struct10.cs //author don voils //date written 6/10/2006 //Description This program illustrates a struct // with private data members and // public methods. // using System; public struct Customer { private string name; private decimal owes; public void setName(string aName) { name = aName; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public string getName() { return name; } public decimal getOwes() { return owes; } } class theProgram { static void Main() { Customer theOne = new Customer(); theOne.setName("George Washington");
file:///D|/1/final/BBL0034.html (17 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
theOne.setOwes(100000.00m); Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.getName(), theOne.getOwes()); Console.ReadKey(); } }
//program_id struct11.cs //author don voils //date written 12/22/2006 // //Description This program illustrates that // the assignment operator is // overloading on structures. // using System; public struct Customer { public string name; public decimal owes; } class theProgram { static void Main() { Customer theOne; Customer theOtherOne; Console.Write("\nWhat is the customer's name? "); theOne.name = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ", theOne.name); theOne.owes = Decimal.Parse(Console.ReadLine()); theOtherOne = theOne; Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOtherOne.name, theOtherOne.owes); Console.ReadKey(); } }
//program_id structToString.cs // //author don voils //date written 12/22/2006 // //Description This program illustrates how a struc // can override the ToString() method // using System; public struct Customer { public string name; public decimal owes; public Customer(string aName,decimal theyOwe) { name = aName; owes = theyOwe; } public override string ToString() { string output = String.Format("\nCustomer: {0}\nOwes: {1:c}",name,owes); return output; } }
file:///D|/1/final/BBL0034.html (18 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
class theProgram { static void Main() { Console.Write("\nWhat is the customer's name? "); string aName = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",aName); decimal theyOwe = Decimal.Parse(Console.ReadLine()); Customer theOne = new Customer(aName,theyOwe); Console.Clear(); Console.WriteLine(theOne.ToString()); Console.ReadKey(); } }
//program_id structureProperties.cs //author don voils //date written 8/28/2006 //Description This program illustrates a struct // with public properties of the data members // instead of using public methods. using System; public struct Customer { private string name; private decimal owes; public string Name { get { return name; } set { name = value; } } public decimal Owes { get { return owes; } set { owes = value; } } } class theProgram { static void Main() { Customer theOne = new Customer(); theOne.Name = "George Washington"; theOne.Owes = 100000.00m; Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.Name, theOne.Owes); Console.ReadKey(); } }
file:///D|/1/final/BBL0034.html (19 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
// program_id testingInFileName.cs // written_by don voils // date_written 1/9/2006 // description This program demonstrates the testing of the name // of the text file to see if it exits before input. // using System; using System.IO; namespace readFromTextFiles { class InPutData { static string fileName; static FileStream readFileStream; static StreamReader fileReader; static void Main(string[] args) { char response; bool toProcess; do { Console.Write("\nWhat is the name of the file? "); fileName = Console.ReadLine(); fileName += ".txt"; if(!File.Exists(fileName)) { Console.WriteLine("\nThat file does not exist."); Console.Write("\nReenter the file name? (Y/N) "); response = Char.Parse(Console.ReadLine()); toProcess = false; } else { response = 'N'; toProcess = true; } }while(response=='Y'||response=='y'); if(!toProcess) { Console.WriteLine("\nThe program will now end. \n\nContinue? "); Console.ReadLine(); } else { OpentoReadDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; customerFirstName = fileReader.ReadLine(); while(customerFirstName != null) { customerLastName = fileReader.ReadLine(); Console.WriteLine("\nCustomer's name: "+customerFirstName+" " +customerLastName); customerID = fileReader.ReadLine(); Console.WriteLine("Customer's ID: "+customerID); customerBalanceDue = decimal.Parse(fileReader.ReadLine()); Console.WriteLine(String.Format("Balance due: {0:c}\n",customerBalanceDue)); customerFirstName = fileReader.ReadLine(); } CloseDataFiles(); Console.ReadKey(); } } static void OpentoReadDataFile() { if(readFileStream!=null) readFileStream.Close();
file:///D|/1/final/BBL0034.html (20 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
if( fileReader!=null) fileReader.Close(); readFileStream = new FileStream(fileName,FileMode.Open,FileAccess.Read); fileReader = new StreamReader(readFileStream ); } static void CloseDataFiles() { fileReader.Close(); readFileStream.Close(); } } }
// program_id testingwriteToTextfiles.cs // written_by don voils // date_written 2/10/2006 // description This program demonstrates how to test to // determine if a text file exists before // output. It only permits continuation if // the file did not exist. // using System; using System.IO; namespace writeToTextfiles { class OutPutData { static string fileName; static FileStream writeFileStream; static StreamWriter fileWriter; static void Main(string[] args) { char response; bool toProcess; do { Console.Write("\nWhat is the name of the file? "); fileName = Console.ReadLine(); fileName += ".txt"; if(File.Exists(fileName)) { Console.WriteLine("\nThat file already exists."); Console.Write("\nReenter the file name? (Y/N) "); response = Char.Parse(Console.ReadLine()); toProcess = false; } else { response = 'N'; toProcess = true; } }while(response=='Y'||response=='y'); if(!toProcess) { Console.WriteLine("\nThe program will now end. \n\nContinue? "); Console.ReadLine(); } else { OpentoWritetoDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; int moreData = 1; while(moreData == 1) { Console.Clear();
file:///D|/1/final/BBL0034.html (21 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
Console.Write("\n\nWhat is the customer's first name? "); customerFirstName = Console.ReadLine(); fileWriter.WriteLine(customerFirstName); Console.Write("\n\nWhat is the customer's last name? "); customerLastName = Console.ReadLine(); fileWriter.WriteLine(customerLastName); Console.Write("\n\nWhat is the customer's ID? "); customerID = Console.ReadLine(); fileWriter.WriteLine(customerID); Console.Write("\n\nHow much does the customer owe? "); customerBalanceDue = decimal.Parse(Console.ReadLine()); fileWriter.WriteLine(customerBalanceDue); fileWriter.Flush(); Console.Write("\n\n\nTo Continue enter 1 and 0 to end. "); moreData = int.Parse(Console.ReadLine()); Console.Clear(); } CloseDataFile(); } Console.ReadKey(); } static void OpentoWritetoDataFile() { if( fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close(); // The enumerator FileMode.Create should be // Append if the file already exists and the // program should add to existing data. // writeFileStream = new FileStream(fileName,FileMode.Create, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } static void CloseDataFile() { Console.WriteLine("\n"); fileWriter.Close(); writeFileStream.Close(); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 4/3/2006 // description This Windows program demonstrates input // from a text file. // namespace viewAccountPayable { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); }
file:///D|/1/final/BBL0034.html (22 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
#region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.nextAP = new System.Windows.Forms.Button(); this.companyName = new System.Windows.Forms.TextBox(); this.amountDue = new System.Windows.Forms.TextBox(); this.totalAPDue = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(45, 27); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(120, 17); this.label1.TabIndex = 0; this.label1.Text = "Company Name"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(48, 70); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 17); this.label2.TabIndex = 1; this.label2.Text = "Amount Due"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(48, 120); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(104, 17); this.label3.TabIndex = 2; this.label3.Text = "Total AP Due"; // // nextAP // this.nextAP.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.nextAP.Location = new System.Drawing.Point(48, 178); this.nextAP.Name = "nextAP"; this.nextAP.Size = new System.Drawing.Size(84, 23); this.nextAP.TabIndex = 3; this.nextAP.Text = "Next"; this.nextAP.UseVisualStyleBackColor = true; this.nextAP.Click += new System.EventHandler(this.nextAP_Click); // // companyName // this.companyName.Location = new System.Drawing.Point(196, 27); this.companyName.Name = "companyName"; this.companyName.ReadOnly = true; this.companyName.Size = new System.Drawing.Size(112, 22); this.companyName.TabIndex = 4; // // amountDue // this.amountDue.Location = new System.Drawing.Point(196, 70); this.amountDue.Name = "amountDue";
file:///D|/1/final/BBL0034.html (23 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
this.amountDue.ReadOnly = true; this.amountDue.Size = new System.Drawing.Size(112, 22); this.amountDue.TabIndex = 5; // // totalAPDue // this.totalAPDue.Location = new System.Drawing.Point(196, 120); this.totalAPDue.Name = "totalAPDue"; this.totalAPDue.ReadOnly = true; this.totalAPDue.Size = new System.Drawing.Size(112, 22); this.totalAPDue.TabIndex = 6; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(328, 267); this.Controls.Add(this.totalAPDue); this.Controls.Add(this.amountDue); this.Controls.Add(this.companyName); this.Controls.Add(this.nextAP); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.Name = "Form1"; this.Text = "View Account Payable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button nextAP; private System.Windows.Forms.TextBox companyName; private System.Windows.Forms.TextBox amountDue; private System.Windows.Forms.TextBox totalAPDue; } }
// program_id Form1.cs // written_by don voils // date_written 4/3/2006 // description This Windows program demonstrates input // from a text file. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace viewAccountPayable { public partial class Form1 : Form { static string fileName = @"accountsPayable.txt"; static FileStream readFileStream; static StreamReader fileReader; static double totalDue; public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = String.Format("{0:c}", 0.00); totalAPDue.Text = String.Format("{0:c}", 0.00); readFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream);
file:///D|/1/final/BBL0034.html (24 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
totalDue = 0.00; } private void nextAP_Click(object sender, EventArgs e) { if (fileReader.EndOfStream == false) { companyName.Text = fileReader.ReadLine(); double theAmount = double.Parse(fileReader.ReadLine()); totalDue += theAmount; amountDue.Text = String.Format("{0:c}", theAmount); totalAPDue.Text = String.Format("{0:c}", totalDue); } else MessageBox.Show("There is no more data to read."); } } }
// program_id Program.cs // written_by don voils // date_written 4/3/2006 // description This Windows program demonstrates input // from a text file. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace viewAccountPayable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id writeToTextfiles.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates text file output. // using System; using System.IO; namespace writeToTextfiles { class OutPutData { // Notice that the following variables are static fields // of the class OutPutData. Therefore they are accessible // withing the following methods without the need to be // dotted with an object or the class. In a way they are // acting like "global" variables being used with the // "global" functions/methods. // static string fileName = "datafile.txt"; static FileStream writeFileStream; static StreamWriter fileWriter; static void Main(string[] args) {
file:///D|/1/final/BBL0034.html (25 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
OpentoWritetoDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; int moreData = 1; while(moreData == 1) { Console.Clear(); Console.Write("\n\nWhat is the customer's first name? "); customerFirstName = Console.ReadLine(); fileWriter.WriteLine(customerFirstName); Console.Write("\n\nWhat is the customer's last name? "); customerLastName = Console.ReadLine(); fileWriter.WriteLine(customerLastName); Console.Write("\n\nWhat is the customer's ID? "); customerID = Console.ReadLine(); fileWriter.WriteLine(customerID); Console.Write("\n\nHow much does the customer owe? "); customerBalanceDue = decimal.Parse(Console.ReadLine()); fileWriter.WriteLine(customerBalanceDue); fileWriter.Flush(); Console.Write("\n\n\nTo Continue enter 1 and 0 to end. "); moreData = int.Parse(Console.ReadLine()); Console.Clear(); } CloseDataFile(); Console.ReadKey(); } static void OpentoWritetoDataFile() { if( fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close(); // The enumerator FileMode.Create should be // Append if the file already exists and the // program should add to existing data. // writeFileStream = new FileStream(fileName,FileMode.Create, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream ); } static void CloseDataFile() { Console.WriteLine("\n"); fileWriter.Close(); writeFileStream.Close(); } } }
file:///D|/1/final/BBL0034.html (26 von 26) [01.12.2007 04:48:14]
Lecture 4: Classes in C#
Lecture 4: Classes in C# An Introduction to C# Classes The language C is based upon the concepts of structured programming. By this is meant that C is based upon the three structures: ●
sequence,
●
selection and
●
recursion
with the added feature of program modularization with functions. C++ extended C and added object oriented programming (OOP). To achieve this, C++ added the concept of classes to C. OOP is based upon the concepts of ●
encapsulation,
●
polymorphism and
●
inheritance.
By encapsulation is meant that parts of the code are hidden either fully or partially from access by other parts of the program. Polymorphism means that some parts of the code look like or act like other parts of the code. This feature saves a programmer time and work when these polymorphic relationships are used. By inheritance is meant that previously written code (i.e. classes) may be used in new and previously unconnected ways. These three concepts are achieved in C++ through the use of classes. C# being an extension of these two languages has both the structured programming features as well as the OOP features of the C/C++ family of languages. This lecture introduces the encapsulation part of C# i.e. it introduces C# classes.
Definition of a Class Object In C# the system data types are: boolean, int, float, double etc. These system data types are used to create blocks of memory with a specific size and with specific properties. These data types are used by defining and then using instances that possess these properties. In addition to the system data types, the programmer may add instances of enumerated data types and structures. The system types, the enumerated types and the structures in C# are referred to as value types. As discussed previously, value types are stored on the stack.
file:///D|/1/final/BBL0035.html (1 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
One of the major features of C# is the class. A class is treated similar to how you have been working with the system data types, enumerated data types and structures. However, when classes are used, the instances are referred to as objects of the class. The objects (instances of programmer defined class data types) are handled differently than the instances of the system data types, enumerated data types and structures. Programmer defined objects are reference variable types in that they contain the address of the class object's memory units. These variables are referred to as reference types. The reference variables reside on the stack but the actual objects of the class reside on the heap. Note: References are similar to the pointers in C++. However they are not as dangerous as pointers. Suppose that the program was to contain a reference: theReference to an object of the TheClass. The definition could be handled in one of the following two ways: ●
First the code may define theReference and its object using the following two statements:
TheClass theReference; theReference = new TheClass();
The first statement defines theReference and the second statement creates an object of TheClass and assigns the address of TheClass object to theReference. If theReference is used before the second statement, an error will occur. ●
Second the two statements above could also be written as one statement like the following:
TheClass theReference = new TheClass();
Note: Each of the above statements uses a class constructor as in TheClass(). As will be seen later in this lecture, a class may have additional constructors some of which may have arguments. Note: It is possible to define a class as static. In this case it is not possible to define a reference because there is no new operator for a static class. Further a static class may only have static fields and static methods.
file:///D|/1/final/BBL0035.html (2 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
Note: It is recommended that the name of each class begin with a capital letter and that each additional word of the name should also begin with a capital letter. The reference and the object to which it refers to are stored as in the following graphic:
Note: The new operator is being used above when the object is defined. This operator is similar to the new operator in C++ that creates the object on the heap and returns the address of this object to theReference. What is different from C++ is that this memory does not need to be deallocated. The programs listed below will use the new operator to create the objects but they will not use the delete operator to deallocate the memory as was necessary in C++. When theReference moves out of scope, then the stack memory used by the variable theReference is returned to the system automatically as was done with variables in C++. However the memory on the heap to which it refers is reclaimed later by the Garbage Collector (GC). When the GC executes, it locates the objects that have no reference and automatically returns their memory to the system. While this is true for objects being handled by system objects, those objects that are involved with network connections, database connections and files must be handled by the programmer as will be discussed later in this lecture. Be careful when using references and one reference is set equal to another. What happens is that both references contain the address of the same object. Therefore if the contents of the class object are changed, then these new values will appear for both references.
Class Definition and Member Access By the definition of a class is meant a construct that contains the description of member data (also called fields) that are declared (non-static fields) or defined (static fields) within the definition of the class construct. The nonstatic fields describe the internal construction of each object of the class that is stored on the heap. In addition to the fields, there are member functions (also called methods or operations) defined in the class' definition. The member functions describe how the objects (variables) of the class may interact with the fields of the object and with the remainder of the program. Note: A difference with C++ is that the classes as well as each of its methods and its fields have their own individual access modifier. But similar to C++, the access modifiers are: static, private, public and protected are among the modifiers used. Note: As with the system data types, each class is derived from the System class Object. However this derivation is implicit and requires no explicit coding by the programmer. This therefore implies that methods of Object may be overloaded, overridden and used by programmer defined classes. The class definition construct has the following properties: ●
a header that includes an access modifier, the keyword class and the tag or name of the class.
●
the body of the class that is enclosed by braces: { } (Notice that there is no semicolon after the closing brace.)
●
a collection of zero or more fields declared or defined within the body (Note: Each object contains copies of the
file:///D|/1/final/BBL0035.html (3 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
non-static fields.) ●
a collection of zero or more methods defined within the body. (Note: The objects do not contain the methods but they may use the non-static methods in ways that are consistent with the access modifier of each method.)
●
a collection of zero or more events defined or declared within the body. (Note: More will be discussed about events in later lectures.)
●
the declarations or definitions of each member is preceded and thereby controlled by its own personal access modifier
The construct for a class definition is: access_modifier class Classname { private memberdatatype datamemberlist; private output_datatype memberfunction(signature) { ..... } protected memberdatatype datamemberlist; protected output_datatype memberfunctions(signature) {....} public memberdatatype datamemberlist; public memberfunctions(argument list) {....} ..... }
The access_modifiers for a class is either public or internal. When the definition of a class has an access modifier of public, then that definition may be accessed in any program that includes the file that contains the definition of the class and the program uses the namespace in which the class is defined. The class access modifier internal restricts access to the class by that code which is in the same assembly (i.e. in the same .exe or . dll file.) If the class' definition does not include an explicit access modifier, then the default is internal. The fields and the methods of a class have the following access modifiers:
Open table as spreadsheet Access Modifier
Restrictions
private
those class members that are either defined or declared as private:
protected
●
are accessible only within the class (they are similar to local variables of a function in that they are only visible within the class.)
●
are not accessible anywhere else other than within the class not even by the instance/object of the class in which they are contained not even using the access operator (i.e. the dot operator)
●
or do not have an explicit access modifier are then implicitly private by default.
those class members that are either defined or declared as protected: ●
internal
have the same accessibility and properties as those members defined as private except as they will relate to derived classes (as will be discussed later).
those class members that are either defined or declared as internal: ●
are accessible only within the same assembly (i.e. in the same .exe or .ddl file) in which their class is defined.
file:///D|/1/final/BBL0035.html (4 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
public
those class members that are either declared or defined as public: ●
static
protected internal
have the same accessibility as structure members do in C++ and therefore may be accessed anywhere.
those class members that are either declared or defined as static: ●
are not accessible by objects and are only accessible by the class using the dot operator.
●
may also be either public or private
●
are loaded into memory when the class becomes available
●
exist during the duration of the program that contains the class' definition even when no objects exist.
those class members that are either declared or defined as protected internal have access limited: ●
to the containing class
●
to the derived classes
●
to those classes within the same assembly as the containing class.
Objects get access to the available members using the access member operator (also called the dot operator). That is if anObject is a reference to an object of some class and aMember is some non-static member of that class, then the anObject gets access to aMember through the access member operator as in the following statement (depending on the access specifier of aMember and where the access is being attempted): anObject.aMember;
If the member is static, then instead of anObject, theClass is used to get access as in the following: TheClass.aStaticMember
(Note: When a class accesses a static member, then the dot operator is used rather than the scope specifier operator (::) as is done in C++.) Note: When or where an object of a class may access its members depends on which access modifier precedes the member when it is defined or declared. For example an int field numberCustomers could have private access if it was declared as follows: private int numberCustomers;
A member function countInvoices() could be defined as public as follows: public int countInvoices() { ...... }
file:///D|/1/final/BBL0035.html (5 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
Note: It is recommended that each field and method begin with a lower case letter and that each word beyond the first word should have its first letter a capital letter. In addition, it is recommend that each method begin with a verb as in countInvoices(). At the top of each of the program files should be the following statement: using System;
because these files contain references to that namespace. Further, notice that each of the class definitions may be enclosed in a namespace. This must either be the same namespace that the program is in or a using statement with the class' namespace must be placed at the top of the program code with the other using statements. In the examples below notice that the fields of most classes are private and that the methods are usually public. The members' declarations/definitions may appear in any order within the class' definition. The recommendation is that the fields be listed first and then the methods. Then within these two groups, they should be ordered in terms of their respective access modifier with the recommended order being: private, protected, internal, public, static and finally protected internal. If a member should be declared/defined with no explicit access modifier, then the member will implicitly default to private but the access modifiers should always be present to ensure that the member is following the software specification requirements. Usually the methods are public but they may also be private. For example see the following class: theDate. Notice that some of the methods are private and therefore can be accessed only within the class by other members of the class. As part of the Design Phase, the UML chart for each class should be defined. For example the class: Date in the example above would have the following UML chart:
References to a Class Object When two value types are defined, separate places in stack memory are created. For example: // As a result of the following a and b // refer to two different place in stack // memory. // int a = 5; int b = a; Console.WriteLine("a stored {0} and b stored {1}", a, b); file:///D|/1/final/BBL0035.html (6 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
b = 15; Console.WriteLine("b was changed."); Console.WriteLine("a stored {0} and b stored {1}\n", a, b);
The output of the first statement would show that both a and b contained the value of 5. However once 15 is placed in b, the value in a is still 5 and the value in b is now 15. When two references to class objects are defined, they may point to the same places on the heap. For example in the following code, the class references A and B are different references but they are accessing the same place on the heap. As a result, to begin with both A and B reference memory that contains the value 15. However when B has its object's field changed to 24, the object that A and B refer to is the same place on the heap and therefore the output for both A and B is 24. See references1.cs // As a result of the following both A and B // refer to the same place in heap memory // TheFirst A = new TheFirst(); A.settheFirstone(15); theFirst B = A; Console.WriteLine("A stored {0} and B stored {1}", A.getTheFirstOne(), B.getTheFirstOne()); Console.WriteLine("B was changed."); B.setTheFirstone(24); Console.WriteLine("A stored {0} and B stored {1}\n", A.getTheFirstOne(), B.getTheFirstOne());
Passing Objects to Functions When an object is passed to a function, it is automatically passed by reference with no special notation required as in the following function: static void modifyCustomerBalance(TheCustomer theOne) { Console.Write("What is {0}'s new balance? ",theOne.getTheName()); double theAmount = Double.Parse(Console.ReadLine()); theOne.setTheBalance(theAmount); Console.WriteLine("\n\n"); }
For example see class4.cs.
Classes in Multiple Files In .NET 1.0, the C# methods had to be defined within the class definition and can not be placed into separate files from the class' definition as in C++. If the class was placed into a separate file from the program, then the entire definition including the methods' definitions must be placed into that file and within the definition of the class. .NET 2.0 has added a variation that makes it more like C++ in this respect. This variation requires that each part of the
file:///D|/1/final/BBL0035.html (7 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
class (and there can be several) can be in a different file. However in order for this to work, the keyword: partial must be used with the class' definition block for each part of the class. The keyword partial must appear immediately before the keyword class. For example the following code could be in one file of the project: public partial class TheAccount { private decimal theBalance; }
while the following code could be in another file of the project.: public partial class TheAccount { public settheBalance(decimal startBalance) { theBalance = startBalance; } }
Note: When the definition of a class is placed in a separate file, the file that contains the class' definition should be enclosed within a namespace. If the file only contained the class' definition, then it is recommended that the namespace be similar to the name of the class. Note: Look at the windows program examples that were considered in previous lectures. Notice that the definition of the class Form1 appeared in two different files: Form1.cs and Form1.Designer.cs and that each class contained part of the class' definition using the word: partial. In Visual Studio .NET 2003 all of this code was in the same file. Create the project processCustomers.cs using the following three files: class5.cs, theCustomer.cs and theCustomer2.cs. Compile and run the program. Notice that the class: Customer was defined in the last two of these files and that each part of the class' definition used the key word: partial. Note: If two classes have the same name and are in different namespaces then the namespace should precede the name of the class when calling the class. In this way the compiler will know which class is being called.
file:///D|/1/final/BBL0035.html (8 von 8) [01.12.2007 04:48:16]
Class Fields
Class Fields Field Initialization If the program does not explicitly initialize the data members (also called fields) of an object, they are initialized automatically to the default for the data type. For example if the field is one of the system numeric values, it will be initialized to 0, if it is a string, it will be initialized to an empty string and if it is a Boolean, then it would be initialized to false. The Visual Studio .NET IDE should produce a warning if the program does not explicitly initialize the fields of an object used in a program. See class1.cs (Note: When this program is compiled, observe all of the warning errors indicating that the class fields have not been initialized, however the program does compile and the default values are automatically assigned to the fields.) As discussed previously, built into C# is the class System.DateTime. If the fields of an object to this class are not initialized, then they will be initialized to 0 automatically. However if you use the property: Now, then the calling object will have its fields initialized to the current time and date. See class2.cs. In C# it is possible to initialize a field to a non-default value within the class' definition. That is in the class' definition a field could be initialized as in the following statement: private double theBalance = 500.00;
Notice how this is done in the following class definition: public class TheClass { private double theBalance = 500.00; private string theName; public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } }
Therefore each object when defined will have the value of its field theBalance set to 500.00. For example see class3.cs. The following is a UML chart for TheClass in this example:
file:///D|/1/final/BBL0036.html (1 von 2) [01.12.2007 04:48:16]
Class Fields
Constant, Readonly and Static Fields A static field is a field that is declared with the keyword static before its definition. It is not a member of any object. It can only be called by using the name of the class as in the following: TheClass.theStaticField;
A field may be declared as a constant meaning therefore that the program may not change its value during program execution. Making a field a constant can be done by preceding the fields declaration with either the keywords const or readonly. The const fields are static by default and must be initialized when the variable is defined and therefore are not fields of an object. Using the keyword static along with the keyword const will cause a compiler error. Fields that are defined as readonly can be initialized when defined or in a constructor. The const fields are compile time constants and the readonly fields are run time constants. This initialization may be done in any one of several constructors however only one will be called at runtime. The readonly may be preceded with the static modifier. When a field is static and readonly, then the constructor must be static. An int field could be defined as static as follows: static int startYear;
To better understand these concepts, view the definitions of the following classes: Circle and Clock1. A UML chart for the class Circle in the example above is:
file:///D|/1/final/BBL0036.html (2 von 2) [01.12.2007 04:48:16]
Class Methods and Field Properties
Class Methods and Field Properties Initializing Field Methods Generally fields are declared as private. Therefore they can not be accessed except by class members. The question is then how are values placed in fields of the object's memory. One way to do this is with Initializing member methods. These methods require no special code. They usually are defined with public access. They must just permit the data to be loaded into the fields. For example in the class: TheDate defined below, the method: setDate() initializes the fields theMonth, theDay and theYear of an object by assigning the values to the respective field through keyboard input when the method setDate() is called as in the following definition: public class TheDate { private long theMonth, theDay, theYear; public void setDate() { Console.Write("What is the month? "); theMonth = Int32.Parse(Console.ReadLine()); Console.Write("What is the day? "); theDay = Int32.Parse(Console.ReadLine()); Console.Write("What is the year? "); theYear = Int32.Parse(Console.ReadLine()); } // additional code is missing }
For an example of a class that uses the above initialization method see the following program and class pair: viewDateClass.cs and dateClass.cs. This example permitted the initialization of the fields within the body of a class method. However, it is also possible to pass these values in through arguments to initialize the fields. View the following program and class pair: viewBankAccount.cs and bankAccount.cs. Notice how the argument of the method: startAccount() initializes the field: balanceAmount. Note: Initializing field methods usually begin with the word set as in setMonth() Accessor and Mutator Methods The class TheDate just considered in the example dateClass.cs contains the methods getMonth(), getDay(), and getYear(). These methods are called accessor methods because through them it is possible to access the data stored in the fields: theMonth, theDay and theYear. That is the value stored in the field theMonth may be accessed through getMonth() in the following manner: TheDate dob = new TheDate(); dob.setDate(): Console.WriteLine(String.format("The month is {0}", dob.getMonth()));
In addition to accessor methods, the class needs what are called mutator methods. For example, see viewCircleClass.cs and CircleClass.cs. In this example, the field: theRadius is initialized by the mutator method:
file:///D|/1/final/BBL0037.html (1 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
setRadius() and accessed through the access method: getRadius(). Note: In general, each field needs an accessor and a mutator method so that the data within an object's fields may be accessed and changed. These methods should be defined with public access so that the field may be accessed and changed anywhere. Access methods usually begin with the word get as in getRadius() and mutator methods usually begin with the word set as in setRadius(). Field Properties and the get and set Accessors Object oriented programming is based upon the concept of encapsulation. By this is meant that the member data is hidden from accidental modification. This is done by defining the fields with private access. However while this provides the programmer with control, this approach also hinders access and initialization of the fields. The creators of C# came up with what are called the properties of a field. These properties use the keywords: get and set. In the following example Month is a property for the field: theMonth: class TheDate { private int theMonth; private int theDay; private int theYear; int public Month { get { return theMonth; } set { theMonth = (value <1 || value >12 ? (1):(value); } } ...... // Additional code goes here. }
Notice how the get returns the value of theMonth while set initializes the value of theMonth. As a result of these definitions, the field: theMonth could be modified in the program using its property Month where an object theObject is defined as in the following code: Warning: A property may have only one get or one set. ..... theObject.Month = 3; Console.WriteLine("The month of the day is {0}",theObject.Month); ......
Note: Having properties for a class permits the class to conform to the OOP without breaking the program. Warning: Notice in the definition of the set accessor that the word value was used without an explicit definition. (The variable: value is not a keyword.) This variable is defined by the compiler and may not be used except in a set definition as in the above example. For a complete example look at the following pair of files: ViewNewDate.cs and theNewDate.cs. The UML chart for the class: theDate
file:///D|/1/final/BBL0037.html (2 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
Look at this UML chart very closely. Notice how the fields: theMonth, theDay and theYear of the TheDate class are declared and then how their properties: Month, Day and Year are implemented. Notice the use of <<property>> in the UML chart before each of these properties. Observe that there are + signs prior to each property because each is public. However their access modifier could be different. The get and the set do not have an access modifier indicated in the UML chart and therefore they are assumed to be public. However their access modifier may be more restrictive than the property and each could be different from the other. Notice further how in the program ViewNewDate that these properties are used to initialize the fields. Notice also in the class theClass how these properties are used in the method: viewDate(). This example may appear to be destroying encapsulation but it is controlling the fields while restricting how they may be accessed. In a sense you are not destroying encapsulation because the program does not have "direct" access to the fields. When a field's property is defined, it does not require that both the get and the set accessor for that field to be defined. If only the get accessor was defined, then the property would be read only. If only the set accessor was defined, then the property would be write only. The access modifier for the property is usually public and both the get and the set are usually public as well. However the access modifiers for the get or the set may be private as well and thereby further restricting the access to the property of a field. Static fields may be defined to be private. In this case, properties may be defined for the static fields as well as non-static fields. Note: Properties are like the accessor and mutator functions in disguise. It is recommended that the field properties be used rather than the accessor and the mutator methods discussed above. Warning: If properties are defined for a particular field, then the compiler will not permit the definition of accessor or mutator methods. Warning: Fields may be used with ref or out but properties may not be used with ref or out as arguments for a method. Constructor Methods When a class object is defined, memory is set aside, the memory is labeled and restrictions are placed on that memory. This is done by a method called a constructor method. If the programmer does not create one explicitly, the compiler will define a constructor implicitly. Constructors have special characteristic that distinguish them from other methods. While the compiler will create an implicit constructor if one is not explicitly defined, the programmer should always define one explicitly so that it will have the characteristics desired. A constructor is called with the new operator as in the following: theBank theAccount = new theBank(); // the method call on the right of the // assignment is a call to the class // constructor theBank(); file:///D|/1/final/BBL0037.html (3 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
The characteristics of a constructor: ●
has the same name as the class.
●
has no return data type not even void.
●
may have a non-void signature.
●
is created by compiler if none is defined (called the default constructor)
●
may be more than one such method (i.e they may be overloaded.)
●
are usually defined with public access but can also be static if it initializes the static fields or private if the desire is to prevent the creation of objects.
●
will initialize the fields to their default value if not explicitly initialized.
In the statement above, theAccount is a reference to the object that is created by the constructor. The reference resides in the stack and the object to which it refers resides in the heap. These variables are called reference types. Remember that this is different from the variables defined for the system data types which are value types and are stored on the stack. If a constructor has a void signature, then it is called a default constructor. When the compiler creates a constructor, it creates an implicit default constructor. (Note: It is recommended that the programmer always create the default constructor if any other constructors are defined. This will be helpful when defining arrays.) If a constructor has a non-void signature, then it is called an explicit constructor. For an example of a class with explicitly defined constructors, see the file pair: viewBank2.cs and theBank2.cs. A class may have static fields. To initialize these static fields, a static constructor may be defined. These constructors obviously may only initialize the static fields. A class may have only one static constructor. Static constructors may not be assigned an access specifier like public. These constructors are called before any objects of the class are defined. See staticConstructor.cs A constructor in addition to being static or public may also have private access. It may be desirable to have a class be a utility class and to have non-static fields. In this case the constructor could be private to prevent the definition of any objects. See privateConstructor.cs When a class has several constructors, it is possible to define one or more of the constructors in terms of one constructor. For example suppose that a class: theEmployee is to have four different constructors all based upon the following constructor: theEmployee(string anID, string aName, decimal theGross) { theID = anID; theName = aName; grossYTD = theGross; }
The remaining constructors may therefore be defined in the following manner: theEmployee() : this("", "", 0.00) { } theEmployee(string anID) : this(anID, "", 0.00) { } theEmployee(string anID, string aName) : this(anID, aName, 0.00) { }
file:///D|/1/final/BBL0037.html (4 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
For an example of this type of constructors see constructor1.cs. Destructor Methods In addition to constructing the object when it is defined, it is necessary to destroy or reclaim the memory of an object after it is no longer needed. In C# this is achieved by the Garbage Collector (GC). When the reference to the object goes out of scope, its memory on the stack is reclaimed by the system immediately. However the memory on the heap that is held by the object remains assigned until the GC claims it. This memory is reclaimed when the GC periodically reclaims memory on the heap that has no reference. In some cases this may not be immediate and in fact the GC may reclaim some unreferenced memory and not other unreferenced memory. Many times the GC is only activated when the amount of unassigned heap memory is below a certain amount. To assist the GC in the process of reclaiming unreferenced heap memory, the class Object has a method called Finalize(). It is also possible for the programmer to define either an overloaded Finalize() method or the destructor method. The destructor performs its tasks and then calls the Object's Finalize() method that in turn calls the GC to return the heap memory used by the object. A programmer defined Finalize() method is mainly used for unmanaged code. Since there will be no further discussion of unmanaged code in this course, the properties of the Finalize() method will not be discussed in these notes. It is recommended that the student read about this method in case its use is required in a program being written once in the work place. As with constructors, the compiler will define a destructor implicitly if the programmer does not define one explicitly in the class definition. The Finalize() method and the GC provide many of the features of a destructor in C++ and therefore in C#, a destructor is notrequired as much as it is in C++. In C# the destructor may provide for services that the garbage collector does not, e.g., the closing of files or the closing of network connections. If a program is working over a network, a destructor is recommended because the GC will not handle all of the system's needs in this case. In general, it is recommended for most programs that the programmer not define a destructor. The characteristics of a destructor are that: ●
it has the same name as class preceded with ~
●
it has no return data type not even void
●
it has only a void signature
●
it has no access specifier and is public by default.
●
there is only one per class
●
it is created implicitly by the compiler if one is not defined explicitly in the code
●
it should never be called explicitly and is called automatically when the reference to an object leaves scope and then calls the Object's Finalize() method which in turn calls the GC to reclaim the heap memory
For example see the file pair: viewDestructor.cs and ConstructorDestructor.cs. In this example notice when the constructor and the destructor are called with relationship to the starting and the ending of the program. Using the following statements in a program can help to force the GC to reclaim the heap memory for objects that have been dereferenced: // force grabage collection System.GC.Collect(); // wait until garbage collection completes System.GC.WaitForPendingFinalizers();
For example see the following pair that use the statements above:
file:///D|/1/final/BBL0037.html (5 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties ●
Employee.cs
●
StaticTest.cs
Overloaded Methods In the discussion above, overloaded functions were defined as functions within the same scope that have the same name but have different argument data types or a different order of the arguments. Methods are within the same scope namely the class' scope. Therefore if two different methods have the same name but have different signatures then they are called overloaded methods. For example in file: theBANK4.cs, the class BankAccount is defined with both of the following constructors: BankAccount() { theAmount = 0.00; } BankAccount(float startingAmount) { theAmount = startingAmount; }
When objects are defined, their definitions can use either one of these constructors. For example when the objects checkingAccount and savingsAccount were created in viewBANK4.cs, it was done like the following: BankAccount checkingAccount = new BankAccount(); BankAccount savingsAccount = new BankAccount(5000);
In the first case the default constructor initialized checkingAccount to $0.00 while the second definition used the constructor with an argument to initialize savingsAccount to $5000.00. theBANK4.cs is an example of using overloading because the constructor methods both have the same name yet they have different arguments. The arguments are different because the first constructor has a void argument and the second has an argument list consisting of one argument of type float. Static Methods These methods can access only the static fields. They can only be called by the class as in the following: TheClass.theStaticMethod();
A static method has no this reference since they are independent of any class object. They are defined as in the following: static theStaticMethod(signature) { ..... }
Static methods are usually used to manipulate the static fields although the static fields may also be manipulated by non-static methods as well. As seen above, static constructors may be used to initialize static fields. See staticConstructor.cs.
file:///D|/1/final/BBL0037.html (6 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
The UML chart for the class TheAccount used in this example:
Copy Constructors A copy constructor is a method that copies the values of the fields of one class object into the fields of another object of the class. In C++ the compiler provides each class with a copy constructor. However in C++ there are times in which defining a copy constructor was necessary. In C# each class needs a copy constructor and it must be explicitly defined by the programmer if one is needed. In fact, it is a good idea to always define one for each class. For example suppose TheClass had a copy constructor. Its general form would be like the following: public TheClass(TheClass anObject) { ..... }
Then if firstObject is an object of TheClass, the secondObject could be defined and initialized by the following statement: TheClass secondObject = new TheClass(firstObject);
or TheClass secondObject = new TheClass(); secondObject = firstObject;
For an example see copy.cs Overriding the ToString() Method for a Class As mentioned previously, every class in C# is derived from the System class Object. One of the methods in the class: Object is ToString(). This converts the objects of the class Object or objects of other classes to strings. It is therefore possible and recommended to override this method for each class you define to help formatting the output of a class' objects. For example the following method achieves this objective for the class bankAcount: public override string ToString() file:///D|/1/final/BBL0037.html (7 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
{ return("Account ID: " + accountID.ToString() + "\nAccount Name: " + accountName.ToString() + "\nAccount Balance: $" + balanceAmount.ToString()); }
Notice the use of the keyword: override in the definition above. For a full implementation of this concept, see: classToString.cs. A UML chart for this class is the following:
The this Reference In C++ each non-static method had a this pointer which would contain the address of the calling object. C# has something similar. In C# each non-static method contains a this reference that contains the address of the calling object. There are four major uses of the this reference. They are: ●
to enable easier access within the method to storing values into the fields of the calling object. For example
this.amount = amount;
could be used in a method definition when both the field and the argument have the name: amount. Notice that the dot operator is used with this above rather than the arrow operator as was done in C++ with its this operator. For an example see this1.cs ●
to enable output of the calling object from within the method as in
return this;
For an example see this2.cs ●
to enable the calling object to be an argument of a method being called within the body of a method as in.
theMethod(this);
For an example see this3.cs ●
to enable the definition of overloaded constructors as in the following:
public theCustomer():this("","",0.00)
file:///D|/1/final/BBL0037.html (8 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
{} public theCustomer(double theAmount):this("","",theAmount) {} public theCustomer(string Name,string ID, double Balance) { this.Name = Name; this.ID = ID; this.Balance = Balance; }
For an example see this4.cs.
file:///D|/1/final/BBL0037.html (9 von 9) [01.12.2007 04:48:18]
Using Classes in C# Programs
Using Classes in C# Programs There are three main approaches to including classes into a C# program. They include the following: ●
define the class within the namespace of the main project but outside of the class' definition of the program that contains Main().
●
define the class within a separate file attached to the program's project either using the same namespace as the program or having its own namespace which is therefore used in the program.
●
define the class within a .dll library and then attach the .dll to the program's project.
Any of these approaches could use the partial class modifier. Using Separate Files for the Class Definition and the Program The first approach was used in the examples earlier in the lecture. The following examples show the second approach. Download each of the following pairs of files (be careful to add the .cs extension to each file): ●
viewClock.cs and Clock1.cs
●
viewCircles.cs and Circle.cs
●
viewPrivateFunctions.cs and theDate.cs
Create a project for each of these pairs of files. Once the project is created, redefined the default .cs file and add each of the files in the pair. The class file should be added as a class. After each pair has been added to its respective solution, compile and run the programs. Next look at each program and observe how the classes are defined, how the objects are defined, what type of methods each uses and how the programs work in general. Notice in the first example that the two files used the same namespace. However in the second example, each file had a different namespace so the program viewCircles.cs had to add an additional using statement. Notice that the classes in the examples above are defined as public. Recall that if a class has no access modifier then it is therefore internal by default. After you have experimented with the above examples, remove the public access specifier for one of the classes and see if the program still compiles. Using Dynamic Linked Libraries (DLL) in a Program When writing programs with classes, the class definition file may be compiled into a .dll (dynamic linked library) file. The dynamic linked library is created at the beginning when the solution is compiled. When defining a .dll, instead of selecting either Windows Application or Console Application, select Class Library. Once the classes have been added to the library, compile the file into a .dll. Then when the program is created that will use the library class, add the .dll by using the Reference Add feature. One last step is to include a using with the class' namespaces (used in the .dll) at the top of the program if the program's namespace is different. Note: When doing this on the job, you should create a dll library folder and after compiling each dll, copy it to the company's component library folder. Using one of the example pairs above, turn the class file into a .dll and add it to the program to see how this feature works. To create .dll file use the following steps: 1. If a dll is used, do the following: i. Create a project using either the same namespace as the program's or a different namespace from the program. (Use the latter approach if the class is to be used for other programs.)
file:///D|/1/final/BBL0038.html (1 von 2) [01.12.2007 04:48:19]
Using Classes in C# Programs
ii. To create the project select C# Program and Class Library. iii. After the class has been defined, build it. Be sure to use the Release version of the build. This creates a file with a dll extension. (Be sure to include the following highlighted code: [Serializable] before the class' definition in the project which may be needed if the classes are going to be used with binary file I/O to be discussed later.) iv. If the class project had a different namespace than the program, create a using statement at the top of the program's code and include the class' namespace name. v. In the program's project select the Solution Explorer and right click on the References' option. vi. Select Add References. vii. When the Add References dialog box appears, select the Browse button and find the class's dll file. viii. Once the class dll has been selected, its name should appear in the Add Reference's dialog box. When this happens, double click on the dll's name and then click the OK button to add the dll to the project's references. ix. The dll has now been added to the program and its contents are now ready to be used by the program. x. If the + sign on the References option of the Solution Explorer is clicked, the name of the dll should appear with the other dlls. 2. If the class is to be part of the program's project as a secondary file, do the following: i. In the Solution Explorer right click on the name of the project. ii. Click on the Add option of the popup menu. iii. If the class's file has already been created, select Add Existing Item and add the file. iv. If the class's file has not been created, select Add New Item and then create the class' definition. After the definition has been created, return to the project file to continue coding. Now create some examples using the partial class modifier. Separate the class definition from the method definitions in different files. Using these separate files, create a .dll file. Using this .dll recompile the program and compare this implementation with the ones above. It is recommended that all of the .dll files be placed into a company component library folder e.g. on a computer that all company programmers would have access to anywhere in the world e.g. on a secure internal network server or accessible through a secure link to an Internet server.
file:///D|/1/final/BBL0038.html (2 von 2) [01.12.2007 04:48:19]
Accessing Class Objects in a Windows Program
Accessing Class Objects in a Windows Program Specifications: Boynton Hauling Lines of Boynton Beach, Florida needs a program that will prepare a shipping manifest which is to be stored to disk. When the program begins, it should seek the truck number and the maximum weight limit of the truck and then store this information in memory to be used as the program progresses. The truck number is to be used to name the file into which the shipping information for each item will be stored. The maximum weight limit of the truck is to be used to limit the items to be shipped. This information is stored in memory by using a button. After the truck items have been entered, the user is provided the opportunity to enter the shipping information for each item that is to be shipped on this truck. The shipping information is to include: the weight of the item, the customer's name, the customer's address, the customer's city, the customer's state and the customer' zip code. As each item to be shipped by the truck is entered, the program should first determine whether the weight of the item added to the weight of each previous entered items does not exceed the maximum weight limit of the truck. This is accomplished by pressing a button. If the weight of the item plus the weight of the items previously entered exceeds the maximum weight limit, the user is provided with a warning and the data is not saved. In this case the user is given the opportunity to try another item or to end the program. If the weight of the item plus the weight of the items previously entered items does not exceed the maximum weight limit of the truck, then the shipping information may be entered. Once the shipping information is entered, the user clicks a button and it is stored to a text file whose name shall be the truck number. The program shall continue until the user decides to exit. Note: The printing of the shipping manifest will be provided by a different program later in the lectures. The screen should look like the following:
The BHL business analyst has decided that the program should be a Windows GUI program written in C#. The file:///D|/1/final/BBL0039.html (1 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
form should have text boxes and labels for each of the following items: ●
truck number
●
truck weight limit
●
sum of weight of previously entered items
●
item weight
●
customer name
●
customer address
●
customer city
●
customer state
●
customer zip
The form should have three buttons for the following purposes: ●
Store Truck Information
●
Check Item Weight
●
Store Item Information
The program should begin by having all of the text boxes cleared except for the sum of weight list box which should begin with the value: 0.00. The text boxes for the truck number and the truck weight limit should be available for data entry when the program begins. All of the other list boxes should be read only at the beginning. In addition the Store Truck Information button should be available for clicking but the other two buttons should not be available at this point. The truck number is to be used to name the text file where the data is to be stored. Once the above conditions are met, the cursor should move to the truck number list box for data entry so that the user may enter the two truck information values. Once the truck information has been entered, the user should click the Store Truck Information button. The clicking of this button stores the truck information into memory. The two text boxes for the truck information entry are then changed to read only. The cursor is to then move to the item weight list box to become available for data entry. When the truck values have been entered, the user is to enter the item weight and then click the Check Item Weight button to determine the sum of the weight of the items entered previously plus the weight of the new item. If the sum of the items previously entered added to the item weight of the new item is over the truck limit, a MessageBox with a warning message should appear. After the warning message disappears, the item weight list box is cleared and the cursor moves back to that list box. In this case the user may again enter a different item or end the program. If the sum of the items previously entered added to the item weight of the new item is below the truck limit, the item weight list box becomes read only and the item weight is added to the sum of weight. The new value of the sum of the weight is then displayed in its list box. The remaining list boxes for the customer information become available for new data entry, After the customer information has been entered, the user may click the Store Item Information button. When this button is clicked, the customer information values are stored in the text file. This is then followed by clearing the customer information list boxes and changing them to read only. After this has been accomplished, the cursor is moved to the item weight text box. Next this list box is changed to become available for entry of another item. At this point the user may again enter another item or end the program. The printing of the shipping manifest will be provided by another program.
file:///D|/1/final/BBL0039.html (2 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
Design: The program is to be based upon the class: Shipments. The following is the UML chart for the class:
This following is the pseudo code to describe the program's actions: TruckInfo Set Shipments.TruckNumber = truckNumber Set Shipments.TruckWeight = weightLimit Set Shipments.WeightEntered = 0.00; Set truckNumber and weightLimit so that the tab does not stop there Set truckNumber and weightLimit so that no data will apear there SetTruckInfo to be invisible and not to be a tab stop Set itemWeight to be read only, the focus and not to be a tab stop Set checkWeight to permit the tab to stop, to be visible and to accept data End
and checkWeight IF (itemWeight + Shipments.WeightEntered <= (Shipments.TruckWeight))THEN Set checkWeight not to permit a TabStop, not to be visible and to to be enabled Set storeItem to permit a.TabStop and to be visible Set theItem to define a new Shipments using itemWeight;
file:///D|/1/final/BBL0039.html (3 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
Set weightEntered = Shipments.WeightEntered Set itemWeight not to be a.TabStop and to be ReadOnly Set customerName, customerAddress, customerCity, customerState and customerZip not to be ReadOnly Set customerName to be the Focus ELSE Display "That item weight will exceed the weight limit" Set itemWeight = "" and to be the Focus Set checkWeight to be Visible, to be Enabled and to be a TabStop ENDIF End
and storeItem Set theItem.Name = customerName Set theItem.Address = customerAddress Set theItem.City = customerCity Set theItem.State = customerState Set theItem.Zip = customerZip Set itemWeight, customerName, customerAddress, customerCity customerState and customerZip to "" Set storeItem to be.visible and aTabStop Display the contenst of theItem IF(Shipments.WeightEntered == Shipments.TruckWeight)THEN Display "The load has reached the truck load limit." and "Start another truck manifest or exit program." Set truckNumber, weightLimit and weightEntered.not to be ReadOnly Set truckNumber, weightLimit and weightEntered to "" Set TruckInfo to be visible and a TabStop ELSE Set checkWeight to be visible, enabled and to be TabStop Set itemWeight to be ReadOnly and the.Focus ENDIF Set customerName, customerAddress, customerCity, customerState and customerZip to be ReadOnly Set storeItem not to be visible or a TabStop End
Coding: The program is to be called: BHLshipments. The class Shipments is to be contained in the namespace theShipments. As indicated by the UML chart above, the values of the Truck Number, the Weight Limit and the Weight Entered should be static fields of the class Shipments. The Truck Number and the Weight Limit are to be entered from the keyboard. These fields should be initialized when the Store Truck Information button is clicked. The Weight Entered should be initialized to 0.00. Once they are stored, their text boxes become ReadOnly. When the Store Truck Information button is clicked, it should initialize the static fields of the class: Shipments. In addition the code should deactivate the truck information text boxes and the Store Truck Information button. Next it should then activate the Item Weight text box and the Check Weight button. file:///D|/1/final/BBL0039.html (4 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
The code for the button: Store Truck Information should look like the following: private void storeTruckInfo_Click(object sender, EventArgs e) { Shipments.TruckNumber = truckNumber.Text; Shipments.TruckWeight = double.Parse(weightLimit.Text); Shipments.WeightEntered = 0.00; truckNumber.TabStop = false; weightLimit.TabStop = false; truckNumber.ReadOnly = true; weightLimit.ReadOnly = true; storeTruckInfo.Visible = false; storeTruckInfo.TabStop = false; itemWeight.TabStop = true; itemWeight.ReadOnly = false; itemWeight.Focus(); checkWeight.TabStop = true; checkWeight.Visible = true; checkWeight.Enabled = true; }
The Check Item Weight button's code should determine if the Item Weight entered does not exceed the available amount for the Truck Weight Limit. If the amount does not exceed the limit, the Item Weight text box and the Check Item Weight button should be deactivated and the Store Item button is activated. Next an object of the class Shipments should be created to store the item information. When the object is defined, the Item Weight is transferred to the object and this value is added to the Weight Entered. The Weight Entered text box should next show the new amount with the Item Weight is added to it. This is followed by activating all of the text boxes needed to receive the customer information. Once this code has executed, the user may begin to enter the remaining data for the customer. If the item amount exceeds the limit, then an error message should appear using a MessageBox. In this case the user is given the opportunity to enter a new item or to end the program. The code for the Check Item Weight button should look like the following: private void checkWeight_Click(object sender, EventArgs e) { if ((double.Parse(itemWeight.Text) + Shipments.WeightEntered) <= (Shipments.TruckWeight)) { checkWeight.TabStop = false; checkWeight.Visible = false; checkWeight.Enabled = false; storeItem.TabStop = true; storeItem.Visible = true; theItem = new Shipments(Convert.ToDouble(itemWeight.Text)); weightEntered.Text = Convert.ToString(Shipments.WeightEntered); itemWeight.TabStop = false; itemWeight.ReadOnly = true; customerName.ReadOnly = false; customerAddress.ReadOnly = false; customerCity.ReadOnly = false;
file:///D|/1/final/BBL0039.html (5 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
customerState.ReadOnly = false; customerZip.ReadOnly = false; customerName.Focus(); } else { MessageBox.Show("That item weight will exceed the weight limit"); itemWeight.Text = ""; itemWeight.Focus(); checkWeight.TabStop = true; checkWeight.Visible = true; checkWeight.Enabled = true; } }
When the Store Item Information button is clicked, the customer information should be stored into the Shipments object previously defined. Next the customer data that was just entered should be cleared and the Store Item Information button should be deactivated. If the Truck Weight limit has been reached, a message should inform the user to either start processing another truck or to end the program. In addition the previously entered truck information should be reset. If the Truck Weight limit has not been reached, the item data text boxes should be reactivated for the next item to be entered. The code for the Store Item Information button should look like the following: private void storeItem_Click(object sender, EventArgs e) { theItem.Name = customerName.Text; theItem.Address = customerAddress.Text; theItem.City = customerCity.Text; theItem.State = customerState.Text; theItem.Zip = customerZip.Text; itemWeight.Text = ""; customerName.Text = ""; customerAddress.Text = ""; customerCity.Text = ""; customerState.Text = ""; customerZip.Text = ""; storeItem.Visible = false; storeItem.TabStop = false; MessageBox.Show(theItem.ToString()); if (Shipments.WeightEntered == Shipments.TruckWeight) { MessageBox.Show("The load has reached the truck load limit."); MessageBox.Show("Start another truck manifest or exit program."); truckNumber.ReadOnly=false; weightLimit.ReadOnly=false; weightEntered.ReadOnly=false; truckNumber.Text = ""; weightLimit.Text = ""; weightEntered.Text = "";
file:///D|/1/final/BBL0039.html (6 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
storeTruckInfo.Visible=true; storeTruckInfo.TabStop=true; } else { checkWeight.Enabled = true; checkWeight.Visible = true; checkWeight.TabStop = true; itemWeight.Focus(); itemWeight.ReadOnly = false; } customerName.ReadOnly = true; customerAddress.ReadOnly = true; customerCity.ReadOnly = true; customerState.ReadOnly = true; customerZip.ReadOnly = true; storeItem.Visible = false; storeItem.TabStop = false; // At this point the object theItem would be stored // to a binary file. This will be discussed later // in the course. // }
Set the Maximum Size and the Minimum Size of Form1 to the same values as the Size. The Windows form looks like the following:
The definition of the class is stored in the file: Shipments.cs The remaining files of the program are: Form1.cs, Form1.Designer.cs and Program.cs. These files are left as a class exercise to load and to view how the program runs. file:///D|/1/final/BBL0039.html (7 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
Note: The code for storing the data from this program is not included and will be discussed later when the file storage of class objects is discussed.
file:///D|/1/final/BBL0039.html (8 von 8) [01.12.2007 04:48:20]
Using the IDE Class Diagram to Code Classes
Using the IDE Class Diagram to Code Classes Suppose that a program Banking.exe was to be created and it was to be based upon the class: Accounts which was to be stored in the component library in the file: Accounts.cs. While the program could be coded one line at a time, it is possible to use the Class Diagram from the IDE to assist in the programming. To begin this exercise, create the project: Banking in Visual Studio .NET 2005. On the menu bar select: Project and the following menu will appear:
Select the Add New Item option and the following will appear:
file:///D|/1/final/BBL0040.html (1 von 7) [01.12.2007 04:48:21]
Using the IDE Class Diagram to Code Classes
Next select the Class Diagram option using the default Name: ClassDiagram1.cd. When this option is selected a box will appear listing links one of which is: Toolbox. Click this link and the Toolbox should appear like the following
Click on the Class option and drag it to the center of the window. This will activate the following:
file:///D|/1/final/BBL0040.html (2 von 7) [01.12.2007 04:48:21]
Using the IDE Class Diagram to Code Classes
Change the Class name to Accounts. When this is done there will be an option to create a new file called: Accouunt.cs. For this exercise, leave this default option. What could be done would be to select: Add to existing file and then type in Program.cs to add the class to the current file rather than create a new file. However in this example a new file will be created. Next click the OK button. When this button is clicked, the following diagram will appear that looks like a UML diagram of the class: Accounts:
The next step will be to add the field: Balance, the property: theBalance, a constructor and the methods: Deposit() and Withdrawal(). To achieve this object right click on the class diagram. When this is done, the following should appear:
file:///D|/1/final/BBL0040.html (3 von 7) [01.12.2007 04:48:21]
Using the IDE Class Diagram to Code Classes
Notice that the menu on the right has options to create a Method, a Property, a Field, an Event, a Constructor, a Destructor and a Constant. First select the Field option entering Balance as in the following:
Next select the Property option for theBalance followed by the Constructor option and the Method option for both Deposit() and Withdrawal(). After making these changes, the class diagram should appear like the following:
file:///D|/1/final/BBL0040.html (4 von 7) [01.12.2007 04:48:21]
Using the IDE Class Diagram to Code Classes
By default the data type of Balance was made int. However, the data type should be double. To make this change, right click on Balance. When this is done, the following menu options should appear:
Click on the Properties option at the bottom. This will make the Properties menu appear as in the following:
file:///D|/1/final/BBL0040.html (5 von 7) [01.12.2007 04:48:21]
Using the IDE Class Diagram to Code Classes
Under the Type option, remove the int and replace it with double. After this has been changed, do the same for the property: theBalance. If Type option is checked for each method, it would be noticed that they are void by default which is what is wanted. The remaining changes need to be made by directly coding the class' definition. Click on the file tab for Accounts. cs. Modify the class definition to the following: public class Accounts { private double Balance; public Accounts() { Balance = 0.00; } public double theBalance { get
file:///D|/1/final/BBL0040.html (6 von 7) [01.12.2007 04:48:21]
Using the IDE Class Diagram to Code Classes
{ return Balance; } set { Balance = value; } } public void Deposit(double theAmount) { Balance += theAmount; } public void Withdrawal(double theAmount) { Balance -= theAmount; } }
Now that the class has been defined the remainder of the program may be coded. The purpose of this exercise was to show how the IDE's Class Diagram may be used to define a class. The process in addition created a graphic that looks like the UML that can be created by Visio.
file:///D|/1/final/BBL0040.html (7 von 7) [01.12.2007 04:48:21]
Lecture 4 Examples
Lecture 4 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
bankAccount.cs
Contains the definition of the C# class bankAccount.
Circle.cs
Contains the definition of the class circle. It is using one of the Math methods Pow().
CircleClass.cs
Contains a definition of the class Circle.
class1.cs
Demonstrates that the attributes of an object will contain the data type defaults if the program does not initialize them. Notice the warning about the lack of initialization.
class2.cs
Demonstrates that the attributes of an object will contain the data type defaults if the program does not initialize them. Notice the warning about the lack of initialization. This example also shows some of the features of the System class DateTime.
class3.cs
Demonstrates that the attributes of an object may be initialized in the class definition with what is called an initializer statement. Notice that the attribute theBalance has an initializer statement.
class4.cs
Demonstrates that objects are passed to functions by reference.
Class5.cs
Demonstrates that may be separated into multiple files using the partial keyword.
classToString.cs
Demonstrates that a class may override the Object method: ToString().
Clock1.cs
Contains the definition of the class classTime.
ConstructorDestructor. cs
Contains the definition of the class theDestructor. The class has a constructor and a destructor.
constructor1.cs
Demonstrates how several constructors for a class may be defined in terms of one of the other constructors.
copy.cs
Demonstrates that classes with a copy constructor.
dateClass.cs
Contains the definition of the class theDate.
Employee.cs
Employee class contains static data and a static method.
privateConstructor.cs
Demonstrates a class with a private constructor. This prevents defining any objects of the class.
references1.cs
Demonstrates how value variables refer to different places in stack member but references that are equal refer to the same place in the heap memory.
staticConstructor.cs
Demonstrates a class with a static attribute, a static constructor and a static method.
StaticTest.cs
Tests the class Employee.
theBank2.cs
Contains the definition of the class bankAccount.
theBank4
Contains the definition of the class bankAccount.
theCustomer.cs
Contains part of the definition of the class TheCustomer.
theCustomer2.cs
Contains the definition of the class TheCustomer.
theDate.cs
Contains the definition of the class Date.
theNewDate.cs
Contains the definition of the class theNewDate. It implements the accessors set and get.
this1.cs
Contains the definition of the class Account. In the method setBalance() the this reference is used.
this2.cs
Demonstrates that objects can be returned from functions using the this reference.
this3.cs
Demonstrates that objects can be passed to functions using the this reference.
this4.cs
Demonstrates how to use the this reference to define overloaded constructors.
viewBank2.cs
Contains the program that utilizes the class bankAccount.
viewBank4.cs
Contains the program viewBank4 that utlizes the class bankAccount.
viewBankAccount.cs
Contains the program viewBankAccount that uses the class bankAccount.
viewCircleClass.cs
Demonstration of a class Circle with initialization and access member function.
viewCircles.cs
Contains a program that utilizes the class theCircle.
viewClock.cs
Demonstrates using C# classes It must be compiled with the file: Clock1.cs.
viewDateclass.cs
Uses TheDate class with member functions defined inside of the class.
viewDestructor.cs
Uses the class theDate.
ViewNewDate.cs
Uses the class aDate.
viewPrivateFunctions.cs
Shows an example where functions can be private as well as data.
// program_id bankAccount.cs // written_by don voils // date_written 12/16/2006
file:///D|/1/final/BBL0041.html (1 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
// description This file contains the definition // of the C# class bankAccount // using System; namespace viewBankAccount { public class BankAccount { private double balanceAmount; public void startAccount(double startAmount) { balanceAmount = startAmount; } public void depositSlip(double depositAmount) { balanceAmount += depositAmount; } public void withdrawalSlip(double checkAmount) { balanceAmount -= checkAmount; } public double showBalance() { return balanceAmount; } } }
// program_id Form1.cs // written_by don voils // date_written 7/13/2006 // description This file along with Form1.Designer.cs is used // to create the program BHLShipments.exe // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using theShipments; namespace BHLshipments { public partial class Form1 : Form { private Shipments theItem; public Form1() { InitializeComponent(); weightEntered.Text = "0.00"; } private void storeTruckInfo_Click(object sender, EventArgs e) { Shipments.TruckNumber = truckNumber.Text; Shipments.TruckWeight = double.Parse(weightLimit.Text); Shipments.WeightEntered = 0.00; truckNumber.TabStop = false; weightLimit.TabStop = false; truckNumber.ReadOnly = true; weightLimit.ReadOnly = true; storeTruckInfo.Visible = false; storeTruckInfo.TabStop = false; itemWeight.TabStop = true;
file:///D|/1/final/BBL0041.html (2 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
itemWeight.ReadOnly = false; itemWeight.Focus(); checkWeight.TabStop = true; checkWeight.Visible = true; checkWeight.Enabled = true; } private void checkWeight_Click(object sender, EventArgs e) { if ((double.Parse(itemWeight.Text) + Shipments.WeightEntered) <= (Shipments.TruckWeight)) { checkWeight.TabStop = false; checkWeight.Visible = false; checkWeight.Enabled = false; storeItem.TabStop = true; storeItem.Visible = true; storeItem.TabStop = true; theItem = new Shipments(Convert.ToDouble(itemWeight.Text)); weightEntered.Text = Convert.ToString(Shipments.WeightEntered); itemWeight.TabStop = false; itemWeight.ReadOnly = true; customerName.ReadOnly = false; customerAddress.ReadOnly = false; customerCity.ReadOnly = false; customerState.ReadOnly = false; customerZip.ReadOnly = false; customerName.Focus(); } else { MessageBox.Show("That item weight will exceed the weight limit"); itemWeight.Text = ""; itemWeight.Focus(); checkWeight.TabStop = true; checkWeight.Visible = true; checkWeight.Enabled = true; } } private void storeItem_Click(object sender, EventArgs e) { theItem.Name = customerName.Text; theItem.Address = customerAddress.Text; theItem.City = customerCity.Text; theItem.State = customerState.Text; theItem.Zip = customerZip.Text; itemWeight.Text = ""; customerName.Text = ""; customerAddress.Text = ""; customerCity.Text = ""; customerState.Text = ""; customerZip.Text = ""; storeItem.Visible = false; storeItem.TabStop = false; MessageBox.Show(theItem.ToString()); if (Shipments.WeightEntered == Shipments.TruckWeight) { MessageBox.Show("The load has reached the truck load limit."); MessageBox.Show("Start another truck manifest or exit program."); truckNumber.ReadOnly=false; weightLimit.ReadOnly=false; weightEntered.ReadOnly=false; truckNumber.Text = ""; weightLimit.Text = ""; weightEntered.Text = "";
file:///D|/1/final/BBL0041.html (3 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
storeTruckInfo.Visible=true; storeTruckInfo.TabStop=true; } else { checkWeight.Enabled = true; checkWeight.Visible = true; checkWeight.TabStop = true; itemWeight.Focus(); itemWeight.ReadOnly = false; } customerName.ReadOnly = true; customerAddress.ReadOnly = true; customerCity.ReadOnly = true; customerState.ReadOnly = true; customerZip.ReadOnly = true; storeItem.Visible = false; storeItem.TabStop = false; // At this point the object theItem would be stored // to a binary file. This will be discussed later // in the course. // } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 7/13/2006 // description This file along with Form1.cs is used // to create the program BHLShipments.exe // namespace BHLshipments { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.truckNumber = new System.Windows.Forms.TextBox(); this.weightLimit = new System.Windows.Forms.TextBox(); this.weightEntered = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label();
file:///D|/1/final/BBL0041.html (4 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.storeTruckInfo = new System.Windows.Forms.Button(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.itemWeight = new System.Windows.Forms.TextBox(); this.customerName = new System.Windows.Forms.TextBox(); this.customerAddress = new System.Windows.Forms.TextBox(); this.customerCity = new System.Windows.Forms.TextBox(); this.customerState = new System.Windows.Forms.TextBox(); this.customerZip = new System.Windows.Forms.TextBox(); this.checkWeight = new System.Windows.Forms.Button(); this.storeItem = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(151, 11); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(135, 17); this.label1.TabIndex = 0; this.label1.Text = "Truck Information"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(61, 50); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(110, 17); this.label2.TabIndex = 1; this.label2.Text = "Truck Number"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(61, 80); this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(97, 17); this.label3.TabIndex = 2; this.label3.Text = "Weight Limit"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(61, 110); this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(120, 17); this.label4.TabIndex = 3; this.label4.Text = "Weight Entered"; // // truckNumber // this.truckNumber.Location = new System.Drawing.Point(252, 50); this.truckNumber.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.truckNumber.Name = "truckNumber"; this.truckNumber.Size = new System.Drawing.Size(132, 22); this.truckNumber.TabIndex = 1; // // weightLimit // this.weightLimit.Location = new System.Drawing.Point(252, 80); this.weightLimit.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
file:///D|/1/final/BBL0041.html (5 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
this.weightLimit.Name = "weightLimit"; this.weightLimit.Size = new System.Drawing.Size(132, 22); this.weightLimit.TabIndex = 2; // // weightEntered // this.weightEntered.Location = new System.Drawing.Point(252, 110); this.weightEntered.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.weightEntered.Name = "weightEntered"; this.weightEntered.ReadOnly = true; this.weightEntered.Size = new System.Drawing.Size(132, 22); this.weightEntered.TabIndex = 6; this.weightEntered.TabStop = false; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(77, 194); this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(124, 17); this.label5.TabIndex = 7; this.label5.Text = "Item Information"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(25, 230); this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(93, 17); this.label6.TabIndex = 8; this.label6.Text = "Item Weight"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.Location = new System.Drawing.Point(25, 260); this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(122, 17); this.label7.TabIndex = 9; this.label7.Text = "Customer Name"; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.Location = new System.Drawing.Point(25, 290); this.label8.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(67, 17); this.label8.TabIndex = 10; this.label8.Text = "Address"; // // storeTruckInfo // this.storeTruckInfo.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing. GraphicsUnit.Point, ((byte)(0))); this.storeTruckInfo.Location = new System.Drawing.Point(285, 162); this.storeTruckInfo.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.storeTruckInfo.Name = "storeTruckInfo"; this.storeTruckInfo.Size = new System.Drawing.Size(213, 28); this.storeTruckInfo.TabIndex = 3; this.storeTruckInfo.Text = "Store Truck Information"; this.storeTruckInfo.UseVisualStyleBackColor = true; this.storeTruckInfo.Click += new System.EventHandler(this.storeTruckInfo_Click); //
file:///D|/1/final/BBL0041.html (6 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
// label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.Location = new System.Drawing.Point(25, 320); this.label9.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(35, 17); this.label9.TabIndex = 12; this.label9.Text = "City"; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.Location = new System.Drawing.Point(25, 350); this.label10.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(46, 17); this.label10.TabIndex = 13; this.label10.Text = "State"; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.Location = new System.Drawing.Point(25, 380); this.label11.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(73, 17); this.label11.TabIndex = 14; this.label11.Text = "Zip Code"; // // itemWeight // this.itemWeight.Location = new System.Drawing.Point(160, 230); this.itemWeight.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.itemWeight.Name = "itemWeight"; this.itemWeight.ReadOnly = true; this.itemWeight.Size = new System.Drawing.Size(132, 22); this.itemWeight.TabIndex = 4; // // customerName // this.customerName.Location = new System.Drawing.Point(160, 260); this.customerName.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.customerName.Name = "customerName"; this.customerName.ReadOnly = true; this.customerName.Size = new System.Drawing.Size(132, 22); this.customerName.TabIndex = 6; // // customerAddress // this.customerAddress.Location = new System.Drawing.Point(160, 290); this.customerAddress.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.customerAddress.Name = "customerAddress"; this.customerAddress.ReadOnly = true; this.customerAddress.Size = new System.Drawing.Size(132, 22); this.customerAddress.TabIndex = 7; // // customerCity // this.customerCity.Location = new System.Drawing.Point(160, 320); this.customerCity.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.customerCity.Name = "customerCity"; this.customerCity.ReadOnly = true; this.customerCity.Size = new System.Drawing.Size(132, 22); this.customerCity.TabIndex = 8; // // customerState // this.customerState.Location = new System.Drawing.Point(160, 350); this.customerState.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
file:///D|/1/final/BBL0041.html (7 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
this.customerState.Name = "customerState"; this.customerState.ReadOnly = true; this.customerState.Size = new System.Drawing.Size(132, 22); this.customerState.TabIndex = 9; // // customerZip // this.customerZip.Location = new System.Drawing.Point(160, 380); this.customerZip.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.customerZip.Name = "customerZip"; this.customerZip.ReadOnly = true; this.customerZip.Size = new System.Drawing.Size(132, 22); this.customerZip.TabIndex = 10; // // checkWeight // this.checkWeight.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.checkWeight.Location = new System.Drawing.Point(340, 230); this.checkWeight.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkWeight.Name = "checkWeight"; this.checkWeight.Size = new System.Drawing.Size(177, 28); this.checkWeight.TabIndex = 5; this.checkWeight.TabStop = false; this.checkWeight.Text = "Check Item Weight"; this.checkWeight.UseVisualStyleBackColor = true; this.checkWeight.Visible = false; this.checkWeight.Click += new System.EventHandler(this.checkWeight_Click); // // storeItem // this.storeItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.storeItem.Location = new System.Drawing.Point(340, 360); this.storeItem.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.storeItem.Name = "storeItem"; this.storeItem.Size = new System.Drawing.Size(197, 28); this.storeItem.TabIndex = 11; this.storeItem.Text = "Store Item Information"; this.storeItem.UseVisualStyleBackColor = true; this.storeItem.Visible = false; this.storeItem.Click += new System.EventHandler(this.storeItem_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(557, 427); this.Controls.Add(this.storeItem); this.Controls.Add(this.checkWeight); this.Controls.Add(this.customerZip); this.Controls.Add(this.customerState); this.Controls.Add(this.customerCity); this.Controls.Add(this.customerAddress); this.Controls.Add(this.customerName); this.Controls.Add(this.itemWeight); this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.storeTruckInfo); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.weightEntered); this.Controls.Add(this.weightLimit); this.Controls.Add(this.truckNumber); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.MaximumSize = new System.Drawing.Size(565, 460); this.MinimumSize = new System.Drawing.Size(565, 460); this.Name = "Form1";
file:///D|/1/final/BBL0041.html (8 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
this.Text = "BHL Shipping Information"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox truckNumber; private System.Windows.Forms.TextBox weightLimit; private System.Windows.Forms.TextBox weightEntered; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Button storeTruckInfo; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox itemWeight; private System.Windows.Forms.TextBox customerName; private System.Windows.Forms.TextBox customerAddress; private System.Windows.Forms.TextBox customerCity; private System.Windows.Forms.TextBox customerState; private System.Windows.Forms.TextBox customerZip; private System.Windows.Forms.Button checkWeight; private System.Windows.Forms.Button storeItem; } }
// program_id Program.cs // written_by don voils // date_written 7/13/2006 // description This file along with Form1.cs and Form1.Designer.cs // is used to create the program BHLShipments. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace BHLshipments { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Circle.cs // written_by don voils // date_written 12/04/06 // description This file contains the definition of // the class circle. It is using one of the // Math methods Pow()to initialize the field: // PI. // using System; namespace theCircle
file:///D|/1/final/BBL0041.html (9 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
{ public class Circle { const double PI = Math.PI; private double radius; public void setRadius(double r) { radius = r; } public double getArea() { return (Math.Pow(radius,2) * PI); } public double getCircumference() { return (2 * radius * PI); } } }
// program_id CircleClass.cs // written_by don voils // date_written 12/10/06 // description This file contains a definition of the // class Circle. // using System; namespace CircleClass { public class Circle { const double PI = Math.PI; private double theRadius; public void setRadius(double radius) { theRadius = radius; } public double getRadius() { return theRadius; } public double getArea() { return (Math.Pow(theRadius,2) * PI); } public double getCircumference() { return (2 * theRadius * PI); } } }
// program_id class1.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates that the attributes // of an object will contain the data type defaults // if the program does not initialize them. Notice // the warning about the lack of initialization. // using System;
class theProgram
file:///D|/1/final/BBL0041.html (10 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
{ public class TheClass { private int theInt; private double theDouble; private string theString; private bool theBoolean; public int getInt() { return theInt; } public double getDouble() { return theDouble; } public string getString() { return theString; } public bool getBoolean() { return theBoolean; } } static void Main() { TheClass theObject = new TheClass(); Console.WriteLine("int is {0}",theObject.getInt()); Console.WriteLine("double is {0}",theObject.getDouble()); Console.WriteLine("string is**{0}***",theObject.getString()); Console.WriteLine("bool is {0}",theObject.getBoolean()); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id class2.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates that the attributes // of an object will contain the data type defaults // if the program does not initialize them. Notice // the warning about the lack of initialization. // // This example also shows some of the features of // the System class DateTime. // // using System;
class theProgram { static void Main() { System.DateTime theObject = new System.DateTime(); Console.WriteLine("The date is {0}/{1}/{2}",theObject.Month,theObject.Day,theObject.Year); Console.WriteLine("The time is {0}:{1}:{2}",theObject.Hour,theObject.Minute,theObject.Second); Console.WriteLine("\n\n"); theObject = System.DateTime.Now; Console.WriteLine("The date is {0}/{1}/{2}",theObject.Month,theObject.Day,theObject.Year); Console.WriteLine("The time is {0}:{1}:{2}",theObject.Hour,theObject.Minute,theObject.Second); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id class3.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates that the attributes // of an object may be initialized in the class
file:///D|/1/final/BBL0041.html (11 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
// definition with what is called an // initializer statement. Notice that // the attribute theBalance has an initializer // statement. // using System; class theProgram { public class TheClass { private double theBalance = 500.00; private string theName; public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } } static void Main() { TheClass theObject = new TheClass(); Console.Write("What is the customers name? "); string aName = Console.ReadLine(); theObject.setTheName(aName); Console.WriteLine("\n\n"); Console.WriteLine("The customer's name is {0}",theObject.getTheName()); Console.WriteLine("{0}'s balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n"); Console.Write("What is {0}'s new balance? ",theObject.getTheName()); double theAmount = Double.Parse(Console.ReadLine()); theObject.setTheBalance(theAmount); Console.WriteLine("\n\n"); Console.WriteLine("{0}'s new balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id class4.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates that objects are passed // to functions by reference. // using System; class theProgram { public class TheCustomer { private double theBalance = 500.00; private string theName; public void setTheBalance(double theAmount)
file:///D|/1/final/BBL0041.html (12 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
{ theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } } static void Main() { TheCustomer theObject = new TheCustomer(); Console.Write("What is the customers name? "); string aName = Console.ReadLine(); theObject.setTheName(aName); Console.WriteLine("\n\n"); Console.WriteLine("The customer's name is {0}",theObject.getTheName()); Console.WriteLine("{0}'s balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n"); modifyCustomerBalance(theObject); Console.WriteLine("{0}'s new balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n"); Console.ReadKey(); } static void modifyCustomerBalance(TheCustomer theOne) { Console.Write("What is {0}'s new balance? ",theOne.getTheName()); double theAmount = Double.Parse(Console.ReadLine()); theOne.setTheBalance(theAmount); Console.WriteLine("\n\n"); } }
// program_id class5.cs // written_by don voils // date_written 6/10/2006 // description This program demonstrates that may be separted into // multiple files using the partial keyword. // using System; using Customer; class theProgram { static void Main() { TheCustomer theObject = new TheCustomer(); Console.Write("What is the customers name? "); string aName = Console.ReadLine(); theObject.setTheName(aName); Console.WriteLine("\n\n"); Console.WriteLine("The customer's name is {0}",theObject.getTheName()); Console.WriteLine("{0}'s balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n"); modifyCustomerBalance(theObject);
file:///D|/1/final/BBL0041.html (13 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
Console.WriteLine("{0}'s new balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n"); Console.ReadKey(); } static void modifyCustomerBalance(TheCustomer theOne) { Console.Write("What is {0}'s new balance? ",theOne.getTheName()); double theAmount = Double.Parse(Console.ReadLine()); theOne.setTheBalance(theAmount); Console.WriteLine("\n\n"); } }
// program_id classToString.cs // written_by don voils // date_written 12/28/2006 // description This program demonstractes that a class may override // the Object method: ToString(). // using System; namespace viewBankAccount { public class BankAccount { private string accountID; private string accountName; private double balanceAmount; public BankAccount(string ID, string Name, double startAmount) { accountID = ID; accountName = Name; balanceAmount = startAmount; } public void depositSlip(double depositAmount) { balanceAmount += depositAmount; } public void withdrawalSlip(double checkAmount) { balanceAmount -= checkAmount; } public double showBalance() { return balanceAmount; } public override string ToString() { return("Account ID: " + accountID.ToString() + "\nAccount Name: " + accountName.ToString() + "\nAccount Balance: $" + balanceAmount.ToString()); } }
class TheProgram { static void Main(string[] args) { string ID; string Name; double startingAmount; Console.Write("What is the account ID? "); ID = Console.ReadLine();
file:///D|/1/final/BBL0041.html (14 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
Console.Write("What is the account name? "); Name = Console.ReadLine(); Console.Write("What is the starting balance? "); startingAmount = Double.Parse(Console.ReadLine()); BankAccount myAccount = new BankAccount(ID,Name,startingAmount); Console.Write("\n\nHow much was deposited to the account? "); myAccount.depositSlip(Double.Parse(Console.ReadLine())); Console.Write("\n\nHow much was the withdrawal from the account? "); myAccount.withdrawalSlip(Double.Parse(Console.ReadLine())); Console.WriteLine("\n\nThe account currently is:\n{0}\n\n",myAccount);
Console.ReadKey(); } } }
// program_id Clock1.cs // written_by don voils // date_written 12/15/2006 // description This file contains the definition of the class ClassTime. // Notice that the class has two static fields that are // initialized in the class' definition.
using System; namespace Clock1 { public class ClassTime { static string spacer_zero= "0", spacer_blank=""; static char backspace = '\b'; int
hours, minutes, seconds;
public void startClock() { Console.WriteLine("Using a 24 hour clock (Example: hh:mm:ss)\n"); Console.Write("What is the time in hours? "); hours = int.Parse(Console.ReadLine()); Console.Write("What is the time in minutes? "); minutes = int.Parse(Console.ReadLine()); Console.Write("What is the time in seconds?"); seconds= int.Parse(Console.ReadLine()); } public void tickClock() { ++seconds; if (seconds >=60) { seconds -= 60; ++minutes; } if (minutes >=60) { minutes -= 60; ++hours; } if (hours >=24) {
file:///D|/1/final/BBL0041.html (15 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
hours = 0; } } public void displayClock() { int counter; string hours_zero, minutes_zero, seconds_zero; if (hours<=9) hours_zero=spacer_zero; else hours_zero=spacer_blank; if (minutes<=9) minutes_zero=spacer_zero; else minutes_zero=spacer_blank; if (seconds<=9) seconds_zero=spacer_zero; else seconds_zero=spacer_blank; for (counter=1;counter<=8;++counter) Console.Write(backspace); for (counter=1;counter<=8;++counter) Console.Write(' '); for (counter=1;counter<=8;++counter) Console.Write(backspace); Console.Write(hours_zero + hours + ':' + minutes_zero + minutes + ':' + seconds_zero + seconds); } } }
// program_id constructor1.cs // written_by don voils // date_written 8/13/2006 // description This program demonstrates how several constructors // for a class may be defined in terms of one of the // other constructors. // using System; class theProgram { class theEmployee { private string theID; private string theName; private decimal grossYTD; public theEmployee() : this("", "", 0.00m) { } public theEmployee(string anID) : this(anID, "", 0.00m) { } public theEmployee(string anID, string aName) : this(anID, aName, 0.00m) { } public theEmployee(string anID, string aName, decimal theGross) { theID = anID; theName = aName; grossYTD = theGross; } public string ID { get { return theID;
file:///D|/1/final/BBL0041.html (16 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
} set { theID = value; } } public string Name { get { return theName; } set { theName = value; } } public decimal Gross { get { return grossYTD; } set { grossYTD = value; } } public override string ToString() { string theInfo = " Employee ID: " + ID + " \n Employee Name: " + Name + string.Format(" \n YTD Gross Pay: {0:c}\n",Gross); return theInfo; } } static void Main() { theEmployee firstOne = new theEmployee(); string Name = "Someone"; string ID = "12334"; decimal Gross = 2424.34m; theEmployee secondOne = new theEmployee(ID); theEmployee thirdOne = new theEmployee(ID, Name); theEmployee fourthOne = new theEmployee(ID, Name, Gross); Console.WriteLine("fistOne is:\n" + firstOne.ToString()); Console.WriteLine("secondOne is:\n" + secondOne.ToString()); Console.WriteLine("thirdOne is:\n" + thirdOne.ToString()); Console.WriteLine("fourth One is:\n" + fourthOne.ToString()); } }
// program_id ConstructorDestructor.cs // written_by don voils // date_written 12/20/2006 // description This file contains the definition of // the class theDate. The class // has a constructor and a destructor. // using System; namespace theDestructor { class TheDate { private int theMonth; private int theDay; private int theYear; public TheDate(int Month,int Day,int Year)
file:///D|/1/final/BBL0041.html (17 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
{ theMonth = Month; theDay = Day; theYear = Year; Console.WriteLine("Creating {0}/{1}/{2}\n\n",theMonth,theDay,theYear); } ~TheDate() { Console.WriteLine("Destroying {0}/{1}/{2}\n\n",theMonth,theDay,theYear); } } }
// program_id copy.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates that classes with // a copy constructor. // using System;
class theProgram { public class TheCustomer { private double theBalance; private string theName; public TheCustomer() { theBalance = 0.00; theName = ""; } public TheCustomer(TheCustomer theOne) { theBalance = theOne.theBalance; theName = theOne.theName; } public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } } static void Main() { TheCustomer theObject = new TheCustomer(); Console.Write("What is the customers name? "); string aName = Console.ReadLine(); theObject.setTheName(aName); Console.Write("What is {0}'s balance? ", theObject.getTheName()); double theAmount = Double.Parse(Console.ReadLine()); theObject.setTheBalance(theAmount);
file:///D|/1/final/BBL0041.html (18 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
Console.WriteLine("\n\n"); TheCustomer theNewObject = new TheCustomer(theObject); Console.WriteLine("{0}'s balance is {1:c}", theNewObject.getTheName(), theNewObject.getTheBalance()); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id dateClass.cs // written_by don voils // date_Written 12/27/2006 // description This file contains the definition of the class theDate. // using System; namespace ViewDateClass { public class TheDate { private long theMonth, theDay, theYear; public void setDate() { Console.Write("What is the month? "); theMonth = int.Parse(Console.ReadLine()); Console.Write("What is the day? "); theDay = int.Parse(Console.ReadLine()); Console.Write("What is the year? "); theYear = int.Parse(Console.ReadLine()); } public long getMonth() { return theMonth; } public long getDay() { return theDay; } public long getYear() { return theYear; } public void viewDate() { string[]monthName = {"","JANUARY","FEBRUARY","MARCH", "APRIL", "MAY","JUNE","JULY","AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER","DECEMBER"}; if(theYear<100) { theYear += 1900; } Console.WriteLine("\n\n"+monthName[theMonth] + " " + theDay + ", " + theYear+"\n\n"); } } }
// program_id Employee.cs // written_by don voils
file:///D|/1/final/BBL0041.html (19 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
// date_written 12/28/2006 // description Employee class contains static data and a static methods. // using System; namespace StaticExample { // Employee calss definition public class Employee { private string firstName; private string lastName; private static int count; // number of objects in memory
// constructor increments static employee count public Employee(string fName, string lName) { firstName = fName; lastName = lName; ++count; Console.WriteLine("Employee object constructor: " + firstName + " " + lastName + "; count = " + count); }
// destructor decrements static count ~Employee() { --count; Console.WriteLine("Employee object destructor: " + firstName + " " + lastName + "; count = " + count); }
// FirstName property public string FirstName { get { return firstName; } } // LastName property public string LastName { get { return lastName; } } //static Count property public static int Count { get { return count; } } } }
// program_id privateConstructor.cs // written_by don voils // date_written 1/27/2006 // description This program demonstrates a class with a private // constructor. This prevents defining any objects of the class. //
file:///D|/1/final/BBL0041.html (20 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
using System; namespace theBank { public class TheInterest { static double theInterestRate = 0.0125; private TheInterest() { } static public void setTheInterest(double theAmount) { theInterestRate = theAmount; } static public double getTheInterest() { return theInterestRate; } } public class TheAccount { private double theBalance = 1000.00; private string theName; public TheAccount(string aName) { theName = aName; } public void addInterest() { theBalance *= 1 + TheInterest.getTheInterest(); }
public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } } class theProgram { static void Main() { Console.WriteLine("The interest rate is {0:n3}%\n",TheInterest.getTheInterest()*100);
//
// The statement below is not allowed because the class constructor // is private which prevents defining an object of the class // TheInterest theNewRate = new TheInterest(); Console.Write("\nWhat is the customers name? "); string aName = Console.ReadLine(); TheAccount theObject = new TheAccount(aName); Console.WriteLine("\nThe customer's name is {0}\n",theObject.getTheName()); Console.WriteLine("{0}'s balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n"); Console.Write("What is {0}'s new balance? ",theObject.getTheName()); double theAmount = Double.Parse(Console.ReadLine());
file:///D|/1/final/BBL0041.html (21 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
theObject.setTheBalance(theAmount); Console.WriteLine("\n{0}'s new balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\nThe monthly interest is being added to the account."); theObject.addInterest(); Console.WriteLine("\n{0}'s new balance after the interest is added is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.Write("\nWhat is the new monthly interest rate? "); TheInterest.setTheInterest(Double.Parse(Console.ReadLine())/100); Console.WriteLine("\nThe new monthly interest rate is {0:n3}%",TheInterest.getTheInterest()*100); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id references1.cs // written?_by don voils // date_written 6/9/2006 // description This program demonstrates how // value variables refer to different // places in stack member but references // that are equal refer to the same place // in the heap memory. // using System;
class theProgram { public class TheFirst { private int theFirstOne; public void setTheFirstOne(int theFirst) { theFirstOne = theFirst; } public int getTheFirstOne() { return theFirstOne; } } static void Main() { // As a result of the following a and b // refer to two different place in stack // memory. // int a = 5; int b = a; Console.WriteLine("a stored {0} and b stored {1}", a, b); b = 15; Console.WriteLine("b was changed."); Console.WriteLine("a stored {0} and b stored {1}\n", a, b); // As a result of the following both A and B // refer to the same place in heap memory // TheFirst A = new TheFirst(); A.setTheFirstOne(15); TheFirst B = A;
file:///D|/1/final/BBL0041.html (22 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
Console.WriteLine("A stored {0} and B stored {1}", A.getTheFirstOne(), B.getTheFirstOne()); Console.WriteLine("B was changed."); B.setTheFirstOne(24); Console.WriteLine("A stored {0} and B stored {1}\n", A.getTheFirstOne(), B.getTheFirstOne()); Console.ReadKey(); } }
// program_id Shipments.cs // written_by Don Voils // date_written 7/10/2006 // description This file contains the definition of the // class Shipments. // namespace theShipments { class Shipments { private static string truckNumber; private static double truckWeight; private static double weightEntered; private double itemWeight; private string customerName; private string customerAddress; private string customerCity; private string customerState; private string customerZip; public Shipments(double theWeight) { Weight = theWeight; WeightEntered += theWeight; } public static string TruckNumber { get { return truckNumber; } set { truckNumber = value; } } public static double TruckWeight { get { return truckWeight; } set { truckWeight = value; } } public static double WeightEntered { get { return weightEntered; } set { weightEntered = value; } } public double Weight { get
file:///D|/1/final/BBL0041.html (23 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
{ return itemWeight; } set { itemWeight = value; } } public string Name { get { return customerName; } set { customerName = value; } } public string Address { get { return customerAddress; } set { customerAddress = value; } } public string City { get { return customerCity; } set { customerCity = value; } } public string State { get { return customerState; } set { customerState = value; } } public string Zip { get { return customerZip; } set { customerZip = value; } } public override string ToString() { string theCustomer = "Customer: " + Name + "\n" + "Address: " + Address + "\n" + "City: " + City + "\n" + "State: " + State + "\n" + "Zip: " + Zip + "\n" + "Weight: " + Weight + "\n"; return theCustomer; } } }
file:///D|/1/final/BBL0041.html (24 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
// program_id staticConstructor.cs // written_by don voils // date_written 1/27/2006 // description This program demonstrates a class with a static // attribute, a static constructor and a static method. // using System; namespace theBank { public class TheAccount { private double theBalance = 1000.00; private string theName; static double theInterest; static TheAccount() { theInterest = 0.0125; } public TheAccount(string aName) { theName = aName; } static public void setTheInterest(double theAmount) { theInterest = theAmount; } public void addInterest() { theBalance *= 1 + theInterest; } static public double getTheInterest() { return theInterest; } public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } } class theProgram { static void Main() { Console.WriteLine("The interest rate is {0:n3}%\n",TheAccount.getTheInterest()*100);
Console.Write("\nWhat is the customers name? "); string aName = Console.ReadLine(); TheAccount theObject = new TheAccount(aName); Console.WriteLine("\nThe customer's name is {0}\n",theObject.getTheName()); Console.WriteLine("{0}'s balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n");
file:///D|/1/final/BBL0041.html (25 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
Console.Write("What is {0}'s new balance? ",theObject.getTheName()); double theAmount = Double.Parse(Console.ReadLine()); theObject.setTheBalance(theAmount); Console.WriteLine("\n{0}'s new balance is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\nThe monthly interest is being added to the account."); theObject.addInterest(); Console.WriteLine("\n{0}'s new balance after the interest is added is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.Write("\nWhat is the new monthly interest rate? "); TheAccount.setTheInterest(Double.Parse(Console.ReadLine())/100); Console.WriteLine("\nThe new monthly interest rate is {0:n3}%",TheAccount.getTheInterest()*100); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id StaticTest.cs // written_by don voils // date_Written 12/28/1006 // description This program tests the class Employee. // using System; namespace StaticExample { // StaticTest class definition class StaticTest { static void Main(string[] args) { Console.WriteLine("Employees before instantiation: " + Employee.Count + "\n"); // create two employees Employee employee1 = new Employee("George", "Washington"); Employee employee2 = new Employee("Thomas", "Jefferson"); Console.WriteLine("\nEmployees after instantiation: " + Employee.Count); // display the employees Console.WriteLine("\nEmployee 1: " + employee1.FirstName + " " + employee1.LastName + "\nEmployee 2: " + employee2.FirstName + " " + employee2.LastName + "\n"); // remove references to the objects so that they // can be grabage collected employee1 = null; employee2 = null; // force grabage collection System.GC.Collect(); // wait until garbage collection completes System.GC.WaitForPendingFinalizers(); Console.WriteLine("\nEmployees after garbage collection: " + Employee.Count + "\n"); } } }
file:///D|/1/final/BBL0041.html (26 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
// program_id theBank2.cs // written_by don voils // date_written 12/20/2006 // descriptioni This file contains the definition of the // class BankAccount. // using System; namespace Account { class BankAccount { private float theAmount; public BankAccount(float startAmount) { theAmount = startAmount; } public void depositSlip(float theDeposit) { theAmount += theDeposit; } public void withdrawalSlip(float checkAmount) { theAmount -= checkAmount; } public float showBalance() { return theAmount; } } }
// program_id theBank4.cs // written_by don voils // date_written 12/20/2006 // description This file contains the definition of // the class BankAccount. // using System; namespace Bank4 { class BankAccount { private float theAmount; public BankAccount() { theAmount = 0.00f; } public BankAccount(float startingAmount) { theAmount = startingAmount; } public void depositSlip(float theDeposit) { theAmount += theDeposit; } public void withdrawalSlip(float checkAmount) { theAmount -= checkAmount; } public float showBalance() {
file:///D|/1/final/BBL0041.html (27 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
return theAmount; } } }
// program_id theCustomer2.cs // written_by don voils // date_written 12/10/2006 // description This file contains the definition of the // class TheCustomer. // namespace Customer { public partial class TheCustomer { public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } } }
// program_id theCustomer.cs // written_by don voils // date_written 12/10/2006 // description This file contains part of the definition of // the class TheCustomer. // namespace Customer { public partial class TheCustomer { private double theBalance = 500.00; private string theName; } }
// program_id theDate.cs // written_by don voils // date_written 12/23/2006 // description This file contains the definition // of the class Date. Notice that the // class has a field that is initialized // in the class' definition. // namespace theDate { public class Date { private int theMonth; private int theDay; private int theYear; const long startYear = 2000; // The following functions are hidden from outside of the class. // Only date class members may access them.
file:///D|/1/final/BBL0041.html (28 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
// private bool testDay(int day) {return ((day>31) || (day < 1))? false:true;} private bool testMonth(int month) {return ((month>12) || (month<1))? false:true;} private bool testYear(int year) {return (year<startYear)? false:true;} public int showMonth() {return (theMonth);} public int showDay() {return (theDay);} public int showYear() {return (theYear);} // This function sets the data elements of the date. public bool setDate(int month,int day,int year) { bool goodDay; if((testMonth(month)) && (testDay(day)) && (testYear(year))) { theDay = day; theMonth = month; theYear = year; goodDay = true; } else goodDay = false; return (goodDay); } } }
// program_id theNewDate.cs // written_by don voils // date_written 6/12/2006 // description This file contains the definition of // the class TheNewDate. It implements // the accessors set and get. // using System; namespace theNewDate { public class TheDate { private int theMonth; private int theDay; private int theYear; public int Month { get { return theMonth; } set { theMonth = (value <1 || value >12)? (1):(value); } } public int Day { get { return theDay; } set { theDay = (value <1 || value >31) ? (1):(value); } }
file:///D|/1/final/BBL0041.html (29 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
public int Year { get { return theYear; } set { theYear = value; } } public void viewDate() { string[]monthName = {"","JANUARY","FEBRUARY","MARCH", "APRIL", "MAY","JUNE","JULY","AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER","DECEMBER"}; if(Year<100) { Year += 1900; } Console.WriteLine("\n\n"+monthName[Month] + " " + Day + ", " + Year+"\n\n"); } } }
// program_id this1.cs // written_by don voils // date_written 12/26/2006 // description This file contains the definition of // the class Account. In the method setBalance() // the this reference is used. // using System; class theProgram { public class Account { private double balance; public void setBalance(double balance) { this.balance = balance; } public double getBalance() { return balance; } public double addDeposit(double deposit) { return balance += deposit; } public double addWithdrawal(double withdrawal) { return balance -= withdrawal; } } static void Main() { Account theAccount = new Account(); Console.Write("What is the starting balance? "); theAccount.setBalance(Double.Parse(Console.ReadLine())); Console.Write("\n\nWhat is the deposit? "); theAccount.addDeposit(Double.Parse(Console.ReadLine())); Console.Write("\n\nWhat is the withdrawal? ");
file:///D|/1/final/BBL0041.html (30 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
theAccount.addWithdrawal(Double.Parse(Console.ReadLine())); Console.WriteLine("\n\nThe current balance is {0:c}\n\n",theAccount.getBalance()); Console.ReadKey(); } }
// program_id this2.cs // written_by don voils // date_written 12/26/2006 // description This program demonstrates that objects can be returned // from functions using the this reference. // using System; class theProgram { public class TheCustomer { private double theBalance = 500.00; private string theName; public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } public TheCustomer interestOnBalance() { return this; } } static void Main() { TheCustomer theObject = new TheCustomer(); Console.Write("What is the customers name? "); string aName = Console.ReadLine(); theObject.setTheName(aName); Console.WriteLine("\n\n"); Console.WriteLine("The customer's name is {0}",theObject.getTheName()); Console.WriteLine("{0}'s starting balance is {1:c}",theObject.getTheName(), theObject.getTheBalance()); TheCustomer anotherObject = new TheCustomer(); anotherObject = theObject.interestOnBalance(); Console.WriteLine("\n\n{0}'s new account after transfer contains {1:c}", anotherObject.getTheName(),anotherObject.getTheBalance()); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id this3.cs // written_by don voils // date_written 12/26/2006 // description This program demonstrates that objects can be passed // to functions using the this reference.
file:///D|/1/final/BBL0041.html (31 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
// using System; class theProgram { public class TheCustomer { private double theBalance = 500.00; private string theName; public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } public void interestOnBalance() { addInteresttoCustomerBalance(this); } } static void Main() { TheCustomer theObject = new TheCustomer(); Console.Write("What is the customers name? "); string aName = Console.ReadLine(); theObject.setTheName(aName); Console.WriteLine("\n\n"); Console.WriteLine("The customer's name is {0}",theObject.getTheName()); Console.WriteLine("{0}'s starting balance is {1:c}",theObject.getTheName(), theObject.getTheBalance()); theObject.interestOnBalance(); Console.WriteLine("{0}'s new balance after interest is {1:c}", theObject.getTheName(),theObject.getTheBalance()); Console.WriteLine("\n\n"); Console.ReadKey(); } static void addInteresttoCustomerBalance(TheCustomer theOne) { double interest = .0575; theOne.setTheBalance(theOne.getTheBalance()*(1+interest)); Console.WriteLine("\n\n"); } }
// program_id this4.cs // written?_by don voils // date_written 7/9/2006 // description This file demonstrates how // to use the this reference to define // overloaded constructors. // using System; class theCustomer { private string theName; private string theID;
file:///D|/1/final/BBL0041.html (32 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
private double theBalance; public theCustomer():this("","",0.00){} public theCustomer(double theAmount):this("","",theAmount){} public theCustomer(string Name,string ID,double Balance) { this.Name = Name; this.ID = ID; this.Balance = Balance; } public string Name { get { return theName; } set { theName = value; } } public string ID { get { return theID; } set { theID = value; } } public double Balance { get { return theBalance; } set { theBalance = value; } } }
// program_id viewBank2.cs // written_by don voils // date_written 12/20/2006 // description This file contains the program // that utilizes the class BankAccount. // using System; namespace Account { class theProgram { static void Main(string[] args) { Console.WriteLine("I started my account with $500.00\n\n"); BankAccount myAccount = new BankAccount(500f); // Notice the use of the constructor. Console.WriteLine("I deposited $2,000.00 in my account"); myAccount.depositSlip(2000.00f); Console.WriteLine("I wrote checks for $700.00 against my account.\n\n"); myAccount.withdrawalSlip(700.00f); Console.WriteLine("My account balance is {0:c}",myAccount.showBalance()); Console.ReadKey();
file:///D|/1/final/BBL0041.html (33 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
} } }
// program_id viewBank4.cs // written_by don voils // date_written 12/20/2006 // description This file contains the program // viewBank4 that utlizes the class // BankAccount. // using System; namespace Bank4 { class theProgram { static void Main() { Console.WriteLine("I started my checking account at the bank.\n\n"); BankAccount checkingAccount = new BankAccount(); Console.WriteLine("I deposited $2,000.00 in my checking account.\n\n"); checkingAccount.depositSlip(2000.00f); Console.WriteLine("I wrote checks for $700.00 against my account.\n\n"); checkingAccount.withdrawalSlip(700.00f); Console.WriteLine("My account balance is {0:c}\n\n",checkingAccount.showBalance()); Console.WriteLine("I started my savings account at the bank with $5,000\n\n"); BankAccount savingsAccount = new BankAccount(5000f); Console.WriteLine("I desposited $3,000.00 in my savings account\n\n"); savingsAccount.depositSlip(3000.00f); Console.WriteLine("I withdrew $1,700.00 from my savings account.\n\n"); savingsAccount.withdrawalSlip(1700.00f); Console.WriteLine("My savings balance is {0:c}\n\n",savingsAccount.showBalance()); Console.ReadKey(); } } }
// program_id viewBankAccount.cs // written_by don voils // date_written 12/20/2006 // description This file contains the program // viewBankAccount that uses the class // bankAccount. // using System; namespace viewBankAccount { class theProgram { static void Main(string[] args) { BankAccount myAccount = new BankAccount(); Console.WriteLine("I started my account with $500.00.\n\n");
file:///D|/1/final/BBL0041.html (34 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
myAccount.startAccount(500); Console.WriteLine("I deposited $2,000.00 in my account.\n\n"); myAccount.depositSlip(2000.00); Console.WriteLine("I wrote checks for $700.00 against my account.\n\n"); myAccount.withdrawalSlip(700.00); Console.WriteLine(String.Format("My account balance is {0:c}\n\n", myAccount.showBalance())); Console.ReadKey(); } } }
// program_id viewCircleClass.cs // written_by Don Voils // date_written 6/15/2006 // description Demonstration of a class Circle // with initialization and access member function. using System; namespace CircleClass { class theProgram { static void Main(string[] args) { Circle theCircle = new Circle(); double theInput; Console.Write("What is the radius of the circle? "); theInput = double.Parse(Console.ReadLine()); theCircle.setRadius(theInput); Console.WriteLine(String.Format("\n\nThe radus is {0}", theCircle.getRadius())); Console.WriteLine(String.Format("\n\nThe area of the circle is {0}", theCircle.getArea())); Console.WriteLine(String.Format("\n\nThe circumference of the circle is {0}\n\n", theCircle.getCircumference())); Console.ReadKey(); } } }
// program_id viewCircles.cs // written_by don voils // date_written 12/20/2006 // description This file contains a program // that utilizes the class theCircle. // using System; using theCircle; namespace ViewCircles { class theProgram { static void Main(string[] args) { Circle theCircle = new Circle(); double theInput;
file:///D|/1/final/BBL0041.html (35 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
Console.Write("What is the radius of the circle? "); theInput = double.Parse(Console.ReadLine()); theCircle.setRadius(theInput); Console.WriteLine("\nThe area of the circle is {0}",theCircle.getArea()); Console.WriteLine("\nThe circumference of the circle is {0}", theCircle.getCircumference()); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id viewClock.cs // written_by don voils // date_written 12/15/2006 // description This program demonstrates using C# classes // It must be compiled with the file: Clock1.cs //
using System; namespace Clock1 { class Class1 { static void Main(string[] args) { ClassTime day1 = new ClassTime(); long counter; for(counter=1L;counter<=25L;++counter) Console.WriteLine(); day1.startClock(); for (counter=1;counter<=25;++counter) Console.WriteLine(); while(true) { day1.tickClock(); day1.displayClock(); for(counter=1L;counter <= 450000000;++counter); } } } }
// program_id viewDateclass.cs // written_by Don Voils // date_written 06/15/2006 // // description: This program uses TheDate class // with member functions // defined inside of the class. // using System; namespace ViewDateClass { class theProgram { static void Main(string[] args) { TheDate aDate = new TheDate();
file:///D|/1/final/BBL0041.html (36 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
aDate.setDate(); aDate.viewDate(); Console.ReadKey(); } } }
// program_id viewDestructor.cs // written_by don voils // date_written 12/20/2006 // description This program uses the class // theDate which has both a // constructor and a destructor. // using System; using theDestructor; namespace theProgram { class theProgram { static void Main(string[] args) { Console.WriteLine("The beginning of main().\n\n"); TheDate startDate = new TheDate(7,4,1776); Console.WriteLine("The end of Main().\n\n"); } } }
// program_id ViewNewDate.cs // written_by don voils // date_written 1/1/2006 // description This program uses the class // TheDate. using System; namespace theNewDate { class theProgram { static void Main(string[] args) { TheDate aDate = new TheDate(); Console.Write("What is the month? "); aDate.Month = int.Parse(Console.ReadLine()); Console.Write("What is the day? "); aDate.Day = int.Parse(Console.ReadLine()); Console.Write("What is the year? "); aDate.Year = int.Parse(Console.ReadLine()); aDate.viewDate(); Console.ReadKey(); } } }
/* program_id viewPrivateFunctions.cs author Don Voils date written 6/15/2006 program description This program shows an example where methods can be private as well as fields. */ using System;
file:///D|/1/final/BBL0041.html (37 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
using theDate; namespace viewPrivateFunctions { class Class1 { static void Main(string[] args) { Date invoiceDate = new Date(); bool notCorrectDate; int theMonth; int theDay; int theYear; do { Console.Write("\nWhat is the invoice month? "); theMonth = int.Parse(Console.ReadLine()); Console.Write("\nWhat is the invoice day? "); theDay = int.Parse(Console.ReadLine()); Console.Write("\nWhat is the invoice year? "); theYear = int.Parse(Console.ReadLine()); if (invoiceDate.setDate(theMonth,theDay,theYear)) notCorrectDate = false; else { notCorrectDate = true; Console.WriteLine("\nCheck date entered."); } }while(notCorrectDate); Console.WriteLine("\n\nThe invoice date entered is {0}/{1}/{2}\n\n", invoiceDate.showMonth(),invoiceDate.showDay(),invoiceDate.showYear()); Console.ReadKey(); } } }
file:///D|/1/final/BBL0041.html (38 von 38) [01.12.2007 04:48:26]
Lecture 5: Class Extensions and Polymorphism
Lecture 5: Class Extensions and Polymorphism Extensions of Classes One of the major goals of a programmer should be to take the classes already written and extend them to new classes with new capabilities and with less coding. In C# there are three major ways of doing this. They are: ●
composition of classes
●
nesting of classes
●
class inheritance
When using either composition of classes or nesting of classes, the objects of the new class are said to support the concept of "has-a" relationship. This means that these objects "has-a" object of the inner class.
Composition of Classes By composition of classes is meant that some of the fields of one class are variables of an enumerated data type or variables of a structure as well as references of objects of another class. (Recall that earlier when structures were discussed some of the examples had fields that were instances of an enumerated data type or another structure type as well.) For example of references of objects of one class acting as fields of another see composition1.cs The following is a UML chart of these classes:.
For an example where an instance of an enumerated data type is a field of a class see composition2.cs. Note: Pay particular attention to the definition of the enumerated data type in this example. Notice that it has an access modifier public. Without this modifier, the program would not compile.
Nesting of Classes By nesting of classes is meant that the definition of one class is completely within the definition of another. The
file:///D|/1/final/BBL0042.html (1 von 2) [01.12.2007 04:48:26]
Lecture 5: Class Extensions and Polymorphism
class which is defined within the other class is called the "inner class". The class which contains the inner class is called the "outer class". The purpose of the inner class is to only serve the needs of the outer class and therefore there is no need to define it separately from the outer class. Sometimes the inner class is referred to as a "helper class" since it has no other purpose than to help the outer class. For example see nesting1.cs
Class Inheritance In class inheritance the original classes are called the base class and the class that inherits the base class' properties is called the derived class. Inheritance supports the concept of "is-a". By this is meant that an object of the derived class "is-a" object (with some restrictions) of the base class.
file:///D|/1/final/BBL0042.html (2 von 2) [01.12.2007 04:48:26]
Introduction to Inheritance
Introduction to Inheritance Inheritance is one of the major features of object oriented programming and software reusability. With inheritance a programmer can take the classes already written and extend them to new classes with new capabilities and with less coding. The original classes are called the base class and the class that inherits the base class' properties is called the derived class. Inheritance supports the concept of "is-a". By this is meant that an object of the derived class "is-a" object (with some restrictions) of the base class.
C# Inheritance as Compared to C++ Inheritance As with many of the other features of C#, there are differences between C# and C++ with respect to inheritance. For example in the C++ the definition of a derived class: ●
contained an access modifier to control the access of the base class by the derived class.
●
could be derived from multiple base classes.
Both of these features have been removed in C# especially the ability of multiple base classes.
Defining the Inheritance Relationship In C# the definition of the derivedClass from the baseClass has the following construct: access_modifier class derievedClass : baseClass { ........... }
Notice that there is no access specifier in the header of the class' definition after the colon as was true in C++. In C# all inheritance is implicitly public. In addition there can be only one base class. That is C# only supports single inheritance and not multiple inheritance. However as will be discussed later in the notes, C# has a construct call interfaces which permits the good features of multiple inheritance without the bad features. Recall that in C# all classes are derived from System.Object. Therefore every class is a derived class. So if theDerivedClass was a class then by default it has an implicit base class: object supplied by the compiler and therefore any base class which is not derived from any other class explicitly has the following implicit inheritance definition: access_modifier class theDerivedClass: System.Object { .... }
Class Inheritance and Heap Memory When an object of the derived class is defined, the heap memory for the object contains not only memory for the fields of the derived class contained in the object but also heap memory for the base class fields that are contained in the object as well, as the following graphic illustrates:
file:///D|/1/final/BBL0043.html (1 von 4) [01.12.2007 04:48:27]
Introduction to Inheritance
Inheritance and UML Charts UML charts may be used in the Design Phase to represent the relationship between the base class and its derived class(s). For example the following graphic shows the UML charts for several possible inheritances:
file:///D|/1/final/BBL0043.html (2 von 4) [01.12.2007 04:48:27]
Introduction to Inheritance
In viewing the UML charts above, it should be apparent that when referring to inheritance, one might use the term: inheritance tree with the base class acting as the roots and the derived classes acting as the branches. For examples of the above inheritance trees for the classes in the first two UML charts see inheritance1.cs and inheritance2.cs.
Base Class Date Member Access Modifiers One has to be careful of the access modifiers of the base class fields and methods. Inheritance preserves encapsulation because those base fields that are private are not directly accessible by the derived classes. Those that are public may be accessed by the references of any derived classes. Something between private and public is sometimes desirable. For this case, the access modifier: protected may be used. If a base class' fields or methods are protected, then the derived classes may access them as if they are private in the derived class. Further as the derived class also becomes a base class, then these same protected members will become accessible in the same way down the inheritance tree. This access modifier then permits inheritance to "protect" the concept of encapsulation.
The Keyword new and Hiding Methods in the Base Class As stated above, an object of a derived class may have direct access to any fields or any method of the base class other than private fields or methods. One of the challenges is when a derived class has a method with the same name as a method of the base class. If this should happen, then the program will compile but a warning error will occur. See inheritance5.cs. While this is acceptable design, having a warning error appear is not acceptable. The warning error may be eliminated if the definition of the derived class' method contains the keyword: new to proceed the definition to acknowledge that it is a different method. This is how base method hiding is accomplished in C#. See inheritance3.cs. The following is a UML chart for the inheritance between the classes stuff and stuff1 which illustrate the use of the modifier new:
Notice in the UML chart for the derived class stuff1 that the name of the base class stuff appears.
Sealed Classes and Inheritance When creating classes, there are times in which the specifications of the program or the policies of your company require that a particular class not be permitted to be the base class in any inheritance tree. If this should arise, C# has a modifier for class definitions to prevent inheritance from happening. The procedure is to declare the class file:///D|/1/final/BBL0043.html (3 von 4) [01.12.2007 04:48:27]
Introduction to Inheritance
sealed as in the following construct: sealed public class theClass { ..... }
See inheritance4.cs. This program is the same as inheritance1.cs except the class Customer is sealed and therefore the program does not compile even though inheritance1.cs does compile. The following is a UML chart of the sealed class: Customer used in the example: inheritance4.cs
Structures and Inheritance As noted previously, structures are similar to classes but there are several differences. For example, they differ with respect to inheritance. Structures are sealed by default. That is structures may not be the base in any inheritance.
file:///D|/1/final/BBL0043.html (4 von 4) [01.12.2007 04:48:27]
Constructors and Destructors in Inheritance
Constructors and Destructors in Inheritance Format for Defining Constructors of a Derived Class Every time an object is defined, a constructor must be called to create the memory for the object. An object of a derived class contains not only memory for the derived class fields but also for the base class fields. The question arises then what happens when an object of a derived class is defined. Substituting a base class constructor for the derived class is not possible. Therefore each derived class must have its own constructor(s). But how are the base class' fields constructed? The answer is that when a constructor for the derived class is called a constructor for the base class must also be called. Each derived class' constructors is dependent on one of the base class' constructors. Sometimes the base class' constructor is the default constructor and sometimes it is a non default constructor. If a base class has no explicit constructor, then the compiler will supply an implicit default constructor for the base class to be used with the derived class' constructor. For example if theBase is the base class with no explicitly defined constructor and theDerived is a class derived from theBase, then the constructor for theDerived may be written as: access_modifier theDerived(signature) { ..... }
but the compiler will rewrite this definition to be: access_modifier theDerived(signature) : base() { ..... }
where in this case, base() refers to the implicit default constructor of theBase. In particular, since each class is directly or indirectly derived from System.Object. Therefore the constructor of aClass which is not explicitly derived from any other class is the following: access_modifier aClass : base() { ..... }
where in this case, base() refers to the implicit default constructor of Object. A special problem may occur when the base class has an explicit constructor. In this case it will be necessary for the derived class to have an explicit constructor as well. This is especially true when the only constructor the base class has is a non default constructor. The construct of the definition of a derived class constructor whose base class constructors may have a non default constructor is: access_modifier derivedclassname(signature) : base(args) {
file:///D|/1/final/BBL0044.html (1 von 3) [01.12.2007 04:48:28]
Constructors and Destructors in Inheritance
… }
In the construct above, the access_modifier may be any one of the modifiers: public or internal. Note that in the definition of the derived constructor above there appears to be a call to the base class' constructor and after the base class constructor's name there appears an argument list. While the derivedclassname is the name of the derived class (and therefore could be any name), the keyword: base() must be used rather than the actual name of the base class. The compiler knows from the definition of the class what the name of the base class is so that the actual name does not need to be supplied. The definition of the base class' constructor only appears in the base class' definition. In addition each argument that appears in the base constructor's signature must also appear in the signature of the derived constructor's definition. The argument list above of the base class' constructor is the signature of an execution/call of the constructor and not the signature of a definition. Further, any arguments that are listed in the argument list of the base class' constructor, may also be used within the body of the derived class' constructor. While the example above shows arguments, it should be noted that the signature of the derived class' constructor and the listed base class' constructor may be void. If the signature of the base class is void (i.e. it is the default constructor), then the base class' constructor is usually not listed in the definition of the derived class' constructor. Even though the base class is not listed in the derived class' constructor, the default constructor of the base would be called implicitly.
Relationships between Constructors of Base and Derived Classes The relationship between the constructor of the base and the constructor of the derived class is more complex than the general construct discussed above presents. To clarify this relationship you should check out each of the following examples:
Open table as spreadsheet Example
Description
CONSTRUCTOR1. CS
Neither class has an explicit constructor
CONSTRUCTOR2. CS
The derived class has an explicit non default constructor but the base class only has an implicitly default constructor.
CONSTRUCTOR3. CS
The derived class has an explicit non default constructor and the base class has an explicit default constructor.
CONSTRUCTOR4. CS
Both the base class and the derived class have an explicit default constructor and a non default constructor.
CONSTRUCTOR5. CS
The base class had two constructors one of which is the default constructor. The derived class has three constructors: one is the default, one is a non default with one argument and the other is a non default with two arguments.
CONSTRUCTOR6. CS
This example has a series of three classes that are defined in a series of derived classes. It explores having various combinations of constructors.
After viewing each of the examples above, what general conclusions can be reached about the relationships between the constructors of the classes involved in an inheritance? For one thing note that in each of the examples above, when an object of the derived class is defined, a constructor of the base class is called. In addition the base class' constructor acts before the derived class' constructor. As a result, it is very important that a base class have a default constructor to match the need for derived classes which do not explicitly call the base constructor. When considering an object of a derived class, it should be kept in mind that the derived class object has memory associated with it that is required to store values into the base class fields of the object. As a result, the constructor
file:///D|/1/final/BBL0044.html (2 von 3) [01.12.2007 04:48:28]
Constructors and Destructors in Inheritance
of the derived class or some other method must be able to initialize and access that part of the derived object's memory associated with the base class as well as the memory associated with the derived class.
Destructors and Inheritance When an object of a derived class is defined or when the derived object goes out of scope, the question arises as to which constructor and in the second case which destructor is called first. When an object of the derived class is defined, the base class constructor is called first. However, when an object of the derived class goes out of scope, then the destructor of the derived class is called first followed by a call to the destructor of the base class. For an example of the order constructors and destructors are called for derived classes see CONSDEST.CS (Notice in this example that the order in which the individual objects are destroyed does not depend on the order in which they are defined.) A UML chart for the classes in this example is the following:
Notice in the UML chart for the derived class: stuffb that the name of the base class: stuffa appears.
file:///D|/1/final/BBL0044.html (3 von 3) [01.12.2007 04:48:28]
Polymorphism
Polymorphism References to a Base Class Manipulate Objects of the Derived Class Polymorphism in C# is slightly different from that in C++. As you may recall, in C++ part of the polymorphism feature used pointers and part of it used references. Since C# does not use pointers but does use references, only the reference part is used. For example, references to a base class may be used to reference a derived class' object. In this way, an object of a derived class may be treated as an object of the base class. For example suppose a program has two classes: theBase and theDerived where theDerived is derived from theBase. Suppose the following definition of a reference of the derived class: theDerived theDerivedReference = new theDerived();
With the following definition, the reference: theBaseReference references the derived object referenced by theDerivedReference. theBase theBaseReference = theDerivedReference;
This last statement would then permit theBaseReference to manipulate the theBase class' contents of the object to which theDerivedRefence refers to. For excample see theReference1.cs. One of the problems with this relationship is similar to the problem with pointers in C++. That is the reference: theBaseReference may only refer to the base class members of the derived class object. It can not refer to the derived class members of the object. Notice in this program where theBaseReference is trying to access the method: show_theDerived() if the comment symbols are removed, the program will not compile. The reverse relationship is not possible. Meaning, that a reference to a derived class may not be used with an object of the base class. If a program does, then there will be a compiler error. For example if the following code replaced the code in the previous example the program would not compile:t theBase theBaseReference = new theBase(2); theDerived theDerivedReference; theDerivedReference = theBaseReference;
See theReference3.cs. In addition if anotherDerived is a class that is itself derived from theDerived class, then theBaseReference may also be used to access theBase class' part of an object of anotherDerived class' object. For example see theReference2.cs.
Virtual Methods Earlier in the notes, an example: inheritance5.cs was shown where both the base class and the derived class both have methods with the same name and signature. As was seen, this was permitted by the compiler but a warning error was issued. To overcome this warning error, the modifier new was used in the example: inheritance3.cs on
file:///D|/1/final/BBL0045.html (1 von 2) [01.12.2007 04:48:29]
Polymorphism
the derived class' method to inform the compiler that the definition of the derived class' method was hiding the base class' method. This example also compiled and ran but there were no warning errors. Sometimes it is desirable to force the derived class to either use the base class' method or to override the base class' method with an entirely different method but with the same name. In either case the base class' method must have the modifier: virtual. When this modifier is used, then the modifier new may not be used. Instead the modifier override must be used if the derived class is to have a method with the same name as the base class. To see an example where the base class is using the modifier virtual but the derived class does not use these names see: inheritance7.cs. To see an example where the base class uses the modifier virtual and the derived class defines methods with the same name by using the modifier: override see: inheritance6.cs. Recall how when the ToString () method was discussed in a previous section, that the modifier override was used. The reason for this is that the method ToString() is a virtual method of the class: System.Object. See classToString.cs
Abstract Classes and Methods Two additional features of the C# polymorphism are abstract methods and abstract classes. To define an abstract method the keyword: abstract must be placed in front of the method's definition and the abstract method can have no body as in the following code: abstract public void theMethod();
In the case of classes, the keyword: abstract must appear before the word class in the definition of the class as in the following code: abstract public class theClass { .... }
An abstract class must contain one or more abstract methods. Any class that contains an abstract method must be defined as an abstract class. An abstract class may not have any defined objects. In addition to the abstract methods, an abstract class may also have non abstract methods as well. Abstract classes and methods must be defined public. Any derived class of an abstract class must override the inherited abstract methods in order to permit the derived objects to be defined. If the abstract methods are not overridden, then the derived class would be considered abstract and any attempts to define objects for such a derived class would fail. As discussed above, this is done by placing the word override in front of the method's definition. For example see theAbstract1.cs. While a class derived from an abstract class must implement each abstract method of the abstract class by overriding it, this is not true if a class is in turn derived from this derived class. For example see theAbstract2.cs. One of the purposes of abstract classes is to provide a base from which other classes may be derived that in turn override the abstract methods. A second purpose is to permit the references of the abstract class to access the overridden methods as if they were references of the derived classes. For example see theAbstract3.cs.
file:///D|/1/final/BBL0045.html (2 von 2) [01.12.2007 04:48:29]
Class Extensions in a Windows Program
Class Extensions in a Windows Program Specifications: The software company Boca Legal Software has been contracted by the law firm: Sue Em All Today of Boca Raton, Florida. SEAT would like to have a C# Windows program written that permits their office staff to enter data about a client and then to print a billing document that informs the client of their monthly financial obligation. The program is to be called: SEATBilling.exe The BLS business analyst has decided to base the program upon the BLS component file: People.cs which contains the definition for the class: People. Further she has decided to have the program be based upon the class: Billing which is to be derived from People. In addition to being derived from the class: People, the class Billing is a composition of the DateTime class in that it has an object of the class DateTime as a field. The form should be designed so that values for each of the fields of an object of the class: Billing would have a text box so that each field may receive a value from the data entry into the form. In addition there should be a text box to display the total charge after it has been calculated. This text box should not permit data entry. Each of the numeric textboxes should have their text right justified. There should be two buttons: one to check the total charge entered and one to print the data. When the button to check the data total charge is clicked, the total charge should be calculated and appear in its text box, the button to check the total charge is deactivated, the button to print the bill should be activated and the form's values would be stored into an object of Billing. When the print bill button is clicked, the data is printed. In addition after this button is clicked each of the text boxes should be cleared, the print the data button should be deactivated and the check the amount button should again be activated. The form should appear like the following:
Design: The UML chart for the class: Billing is the following and it contains the UML chart for the class: People:
file:///D|/1/final/BBL0046.html (1 von 5) [01.12.2007 04:48:30]
Class Extensions in a Windows Program
The form is to have a label and a text box for each of the fields of an object of Billing as well as one for the month, the day and the year of the transaction. The following is the pseudo code for the program: Form Set theCharge textbox to ReadOnly and not to be a tab stop Seta the checkCharge button to be visible Set the printBill button not to be visible Move the focus to the textbox accountNumber End printBill_Click Print the bill Clear all textboxes Set all of textboxes to not be ReadOnly Set the checkCharge button to be visible Set the printBill button not to be visible Move the focus to the textbox accountNumber End checkCharge_Click Create an object of the class Billing using the transaction file:///D|/1/final/BBL0046.html (2 von 5) [01.12.2007 04:48:30]
Class Extensions in a Windows Program
date as the argument Store each of the textbox text into their respective fields of the object Display in the Total Charge textbox the calculation of HoursServed *HourlyRate Set each of the textboxes to read only Move the focus to the Print Bill button Make the Check Total Charge button invisible End
Coding: The code of the Form1 constructor should be the following: public Form1() { InitializeComponent(); theCharge.ReadOnly = true; theCharge.TabStop = false; checkCharge.Visible = true; printBill.Visible = false; accountNumber.Focus(); }
The code for the Check Total Charge should be the following: private void checkCharge_Click(object sender, EventArgs e) { theClient = new Billing(Int32.Parse(theMonth.Text), Int32.Parse(theDay.Text), Int32.Parse(theYear.Text)); theClient.Number = accountNumber.Text; theClient.Name = theName.Text; theClient.Address = theAddress.Text; theClient.City = theCity.Text; theClient.State = theState.Text; theClient.Zip = theZip.Text; theClient.TransactionNumber = theTransaction.Text; theClient.Lawyer = theLawyer.Text; theClient.Description = theDescription.Text; theClient.HourlyRate = double.Parse(theRate.Text); theClient.HoursServed = double.Parse(theHours.Text); theCharge.Text = string.Format("{0:c}", (theClient.HoursServed * theClient.HourlyRate)); accountNumber.ReadOnly = true; theName.ReadOnly = true; theAddress.ReadOnly = true; theCity.ReadOnly = true; theState.ReadOnly = true; theZip.ReadOnly = true; theMonth.ReadOnly = true; theDay.ReadOnly = true; theYear.ReadOnly = true; theTransaction.ReadOnly = true; theLawyer.ReadOnly = true;
file:///D|/1/final/BBL0046.html (3 von 5) [01.12.2007 04:48:30]
Class Extensions in a Windows Program
theDescription.ReadOnly = true; theRate.ReadOnly = true; theHours.ReadOnly = true; printBill.Visible = true; printBill.Focus(); checkCharge.Visible = false; }
The code for the Print Bill button should be like the following: private void printBill_Click(object sender, EventArgs e) { // printing of theClient information goes here. accountNumber.Text = ""; theName.Text = ""; theAddress.Text = ""; theCity.Text = ""; theState.Text = ""; theZip.Text = ""; theMonth.Text = ""; theDay.Text = ""; theYear.Text = ""; theTransaction.Text = ""; theLawyer.Text = ""; theDescription.Text = ""; theRate.Text = ""; theHours.Text = ""; theCharge.Text = ""; accountNumber.ReadOnly = false; theName.ReadOnly = false; theAddress.ReadOnly = false; theCity.ReadOnly = false; theState.ReadOnly = false; theZip.ReadOnly = false; theMonth.ReadOnly = false; theDay.ReadOnly = false; theYear.ReadOnly = false; theTransaction.ReadOnly = false; theLawyer.ReadOnly = false; theDescription.ReadOnly = false; theRate.ReadOnly = false; theHours.ReadOnly = false; checkCharge.Visible = true; printBill.Visible = false; accountNumber.Focus(); }
Upon completion, the form should look like the following:
file:///D|/1/final/BBL0046.html (4 von 5) [01.12.2007 04:48:30]
Class Extensions in a Windows Program
The program is to be called: SEATBilling.exe. The class: People is stored in the file: People.cs and the class: Billing is stored in the file: Billing.cs. The remaining files are: SEATBilling_Form1.cs, SEATBilling_Form1_Designer.cs and SEAT_Program.cs.
file:///D|/1/final/BBL0046.html (5 von 5) [01.12.2007 04:48:30]
Using the IDE Class Diagram to Code Inheritance
Using the IDE Class Diagram to Code Inheritance In previous lectures the IDE Class Diagram was used to code: enumerated data types, structures and then classes. The purpose of this exercise is to use the Class Diagram to code inheritance between the class: Customer and the class: Invoice. To begin with, open the project: processInvoices. As in the previous exercises using the Class Diagram, create the two classes by dragging the class icons onto the form. Name the classes: Customer and Invoice respectively. The ClassDiagram1.cd should appear as in the following graphic:
Next, notice that in the Toolbox there is an icon for Inheritance. Right mouse button click on this option and then click on Copy. Next drag this icon to connect from Invoice to Customer to show inheritance between these two classes. (The process may not work the first few times and therefore may require you to repeat this process until you can get the arrow to point from Invoice to Customer.) When you do, the following changes should be observed.
file:///D|/1/final/BBL0047.html (1 von 3) [01.12.2007 04:48:30]
Using the IDE Class Diagram to Code Inheritance
Observe that not only is the arrow going form Invoice to Customer but in the Invoice icon there is a reference to the class: Customer. Click on the icons and follow this by a right click on the mouse. Select Code View. What will be observed is the following code to show the inheritance of the class: Invoice from the class: Customer public class Customer { } public class Invoice : Customer { }
Another approach to this graphical relationship is not to connect the two graphics with the arrow in ClassDiagram1. cd. Instead it is possible to click Code View. Add the inheritance feature to the definition of Invoice. After completing this step, click back to ClassDiagram1.cd. As a result of that step, the arrow will now be drawn from the class Invoice to the class Customer. The completed graphic may be exported from Visual Studio .NET as a jpg file. To achieve this objective click a right mouse button on the graphic. When you do, the following pop up menu should appear:
file:///D|/1/final/BBL0047.html (2 von 3) [01.12.2007 04:48:30]
Using the IDE Class Diagram to Code Inheritance
Select Export Diagram as Image. Save the file as a jpg file. When you do, the following should be available in the project's folders:
To complete this exercise, take the definitions of these two classes in the example: inheritance1.cs. Add the fields and the methods as discussed previously when using the Class Diagram to create a class. After completing these steps click on Code View and notice that the two classes are defined as in the example. Complete the exercise by exporting the diagram as a jpg file.
file:///D|/1/final/BBL0047.html (3 von 3) [01.12.2007 04:48:30]
Lecture 5 Examples
Lecture 5 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
SEAT Billing:
These files contain the code for the SEAT billing program.
●
Form1.cs
●
Form1.Designer.cs
●
Program.cs.
Billing.cs
Contains the definition of the class: Billing. It is derived from the class: People and a composition of the class: DateTime.
classToString.cs
Demonstrates that a class may override the Object method: ToString().
composition1.cs
Demonstrates composition of classes.
composition2.cs
Demonstrates the use of instances of an enumerated data type to act as attributes of a class.
consdest.cs
Illustrates how constructors in a derived class call the constructors in the base class. If a base class has a constructor and data members and the constructor has an argument, then the derived class must have a constructor. The constructor in the base class is called before a constructor in a derived class. In addition to constructors, this program demonstrates how destructors are called. Notice that the destructors are called in reverse order to the constructors. That is the destructors in the derived class are called before the destructor in the base class is called.
constructor1.cs
Demonstrates the derivation of one class from another where the classes each use the default constructor.
constructor2.cs
Demonstrates the derivation of one class from another where the base class uses a non-defined default constructor and the derived class has a non-default constructor but calls the default constructor of the base class.
constructor3.cs
Demonstrates the derivation of one class from another where the base class has a defined default constructor and the derived class has a non-default constructor that is implicitly dependent on the base class' default constructor.
constructor4.cs
In this example the base class has an explicit default and non-default constructor. When an object of the derived class is defined, the default or the non-default constructor of the base class is called depending on which constructor of the derived class is called.
constructor5.cs
In this example the base class has an explicit default and non-default constructor. When an object of the derived class is defined, the default or the non-default constructor of the base class is called depending on which constructor of the derived class is called.
constructor6.cs
In this example the base class has an explicit default and non-default constructor. When an object of the derived class is defined, the default or the non-default constructor of the base class is called depending on which constructor of the derived class is called.
inheritance1.cs
Demonstrates how to use inheritance.
inheritance2.cs
Demonstrates how to use inheritance.
inheritance3.cs
In this example the base class has a protected attribute that is accessible in the derived class. In addition the derived class has methods with the same name as the base class and overcomes this restriction by using the keyword word: new.
inheritance4.cs
Demonstrates how to prevent inheritance. The program is the same as inheritance1.cs except the class Customer is sealed. The program inheritance1.cs compiled and ran but this program will not.
inheritance5.cs
Contains two class one of which is derived from the other. The base class and the derived class contain methods with the same name. While the program compiles and runs, it contains several warning error notifying the programmer that the two classes have methods with the same names.
inheritance6.cs
In this example the base class has a protected attribute that is accessible in the derived class. In addition the derived class has methods with the same name as the base class. This overcomes this restriction by using the keyword words: virtual in the base class and overridden in the derived class.
inheritance7.cs
In this example the base class has methods that are declared as virtual. The derived class does not have methods by these names. However the program compiles and runs.
nesting1.cs
Demonstrates the nesting of one class definition inside of another.
People.cs
Contains the definition of the class People.
theAbstract1.cs
Shows how an abstract class and method can be defined as well as how to derive a class from the abstract class. If the keyword: override is removed from the definition of the method show() in the derived class, the program will not compile.
file:///D|/1/final/BBL0048.html (1 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
theAbstract2.cs
Shows how an abstract class and method can be defined as well as how to derive a class from a class that is derived from an abstract class. In this case, this second derived class does not have to override the base class' abstract method.
theAbstract3.cs
Shows how an abstract class and method can be defined as well as how to derive a class from a class that is derived from an abstract class. In this case, a second derived class is derived from the first derived class. In this program a reference to the abstract base class is used to access methods of each of the derived classes as if it was a reference to the respective classes. Without this base class being abstract, this reference would have been forced to access the base class' method which would have been impossible because it is in turn abstract.
theReference1.cs
Shows how references to a base class can be used to access the base class part of an object of the derived class.
theReference2.cs
Shows how references to a base class can be used to access the base class part of an object of a class that is derived from a class that is derived from the base.
theReference3.cs.
Demonstrates that a reference to a derived class may not be used to access an object of the base class.
// program_id Billing.cs // written_by don voils // date_written 7/14/2006 // description This file contains the definition of the // class: Billing. It is derived from the // class: People and a composition of the // class: DateTime. // using System; using thePeople; namespace theBilling { class Billing : People { private DateTime theBillingDate; private string theTransactionNumber; private string theLawyer; private string theDescription; private double theHoursServed; private double theHourlyRate; public int theMonth { get { return theBillingDate.Month; } } public int theDay { get { return theBillingDate.Day; } } public int theYear { get { return theBillingDate.Year; } } public string TransactionNumber { get { return theTransactionNumber; } set { theTransactionNumber = value; } } public string Lawyer { get
file:///D|/1/final/BBL0048.html (2 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
{ return theLawyer; } set { theLawyer = value; } } public string Description { get { return theDescription; } set { theDescription = value; } } public double HoursServed { get { return theHoursServed; } set { theHoursServed = value; } } public double HourlyRate { get { return theHourlyRate; } set { theHourlyRate = value; } } public Billing() { theBillingDate = DateTime.Now; } public Billing(int aMonth, int aDay, int aYear) { theBillingDate = new DateTime(aYear,aMonth,aDay); } public double monthlyCharge() { return HourlyRate * HoursServed; } } }
// program_id classToString.cs // written_by don voils // date_written 12/28/2006 // description This program demonstractes that a class may override // the Object method: ToString(). // using System; namespace viewBankAccount { public class bankAccount { private string accountID; private string accountName; private double balanceAmount;
file:///D|/1/final/BBL0048.html (3 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
public bankAccount(string ID, string Name, double startAmount) { accountID = ID; accountName = Name; balanceAmount = startAmount; } public void depositSlip(double depositAmount) { balanceAmount += depositAmount; } public void withdrawalSlip(double checkAmount) { balanceAmount -= checkAmount; } public double showBalance() { return balanceAmount; } public override string ToString() { return ("Account ID: " + accountID.ToString() + "\nAccount Name: " + accountName.ToString() + "\nAccount Balance: $" + balanceAmount.ToString()); } }
class theProgram { static void Main(string[] args) { string ID; string Name; double startingAmount; Console.Write("What is the account ID? "); ID = Console.ReadLine(); Console.Write("What is the account name? "); Name = Console.ReadLine(); Console.Write("What is the starting balance? "); startingAmount = Double.Parse(Console.ReadLine()); bankAccount myAccount = new bankAccount(ID, Name, startingAmount); Console.Write("\n\nHow much was deposited to the account? "); myAccount.depositSlip(Double.Parse(Console.ReadLine())); Console.Write("\n\nHow much was the withdrawal from the account? "); myAccount.withdrawalSlip(Double.Parse(Console.ReadLine())); Console.WriteLine("\n\nThe account currently is:\n{0}\n\n", myAccount); } } }
// program_id composition1.cs // written_by don voils // date_written 12/21/2006 // description This program demonstrates composition // of classes. // using System;
namespace Composition
file:///D|/1/final/BBL0048.html (4 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
{ // Date class definition public class Date { private int month; // 1-12 private int day; // 1-31 based on month private int year; // any year // Constructor validates data and initializes values public Date(int monthValue, int dayValue, int yearValue) { if (monthValue > 0 && monthValue <= 12) { month = monthValue; } else { month = 1; Console.WriteLine("Month {0} is invalid. Set month to 1.", monthValue); } year = yearValue; day = CheckDay(dayValue); } // utility method confirms proper day value // based on month and year private int CheckDay(int testDay) { // The following is an array of ints. // int[] daysPerMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// check for leap year if (month == 2 && testDay == 29 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) return testDay; // check if day in range for the month if (testDay <= daysPerMonth[month]) return testDay; Console.WriteLine("Day {0} is invalid. Seting day to 1.", testDay); testDay = 1; return testDay; } public override string ToString() { return string.Format("{0}/{1}/{2}", month, day, year); } } public class Employee { private string firstName; private string lastName; private Date birthDate; // reference to Date object private Date hireDate; // reference to Date object // constructor initializes values public Employee(string first, string last, int birthMonth, int birthDay, int birthYear, int hireMonth, int hireDay, int hireYear) { firstName = first; lastName = last; // create new Date objects birthDate = new Date(birthMonth, birthDay,
file:///D|/1/final/BBL0048.html (5 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
birthYear); hireDate = new Date(hireMonth, hireDay, hireYear); } // convert Employee to string format public override string ToString() { return "Employee: " + firstName + " " + lastName + "\n" + "\nHired: " + hireDate.ToString() + "\nBirthday: " + birthDate.ToString(); } } class theProgram { static void Main(string[] args) { Employee e = new Employee("James", "Bond", 10, 10, 1970, 6, 20, 1988); Console.WriteLine(e.ToString()); Console.WriteLine("\n\n"); string theFirstName; string theLastName; int bMonth; int bDay; int bYear; int hMonth; int hDay; int hYear; Console.Write("\nWhat is your first name? "); theFirstName = Console.ReadLine(); Console.Write("What is your last name? "); theLastName = Console.ReadLine(); Console.WriteLine("\n"); Console.Write("What is the month of the your birthdate? "); bMonth = Int32.Parse(Console.ReadLine()); Console.Write("What is the day of the your birthdate? "); bDay = Int32.Parse(Console.ReadLine()); Console.Write("What is the year of the your birthdate? "); bYear = Int32.Parse(Console.ReadLine()); Console.WriteLine("\n"); Console.Write("What is the month of the your hire date? "); hMonth = Int32.Parse(Console.ReadLine()); Console.Write("What is the day of the your hire date? "); hDay = Int32.Parse(Console.ReadLine()); Console.Write("What is the year of the your hire date? "); hYear = Int32.Parse(Console.ReadLine()); Console.WriteLine("\n"); Employee f = new Employee(theFirstName, theLastName, bMonth, bDay, bYear, hMonth, hDay, hYear); Console.WriteLine(f.ToString()); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id composition2.cs // written_by don voils // date_written 12/21/2006 // description This class demonstrates the use of instances of // an enumerated data type to act as attributes of // a class. // using System; namespace Composition2 { public enum Colors
file:///D|/1/final/BBL0048.html (6 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
{ Red, Blue, Green, While, Black } public class Cars { private string theCompany; private string theModel; private string theYear; private decimal theCost; private Colors theColor = Colors.Black; public void settheCompany(string Company) { theCompany = Company; } public void settheModel(string Model) { theModel = Model; } public void settheYear(string Year) { theYear = Year; } public void settheCost(decimal Cost) { theCost = Cost; } public void settheColor(Colors Color) { theColor = Color; } public string gettheCompany() { return theCompany; } public string gettheModel() { return theModel; } public string gettheYear() { return theYear; } public decimal gettheCost() { return theCost; } public string gettheColor() { return theColor.ToString(); } } class theProgram { static void Main() { Cars MyCar = new Cars(); Console.Write("What is the company that made the car? "); MyCar.settheCompany(Console.ReadLine()); Console.Write("What is the model of the car? "); MyCar.settheModel(Console.ReadLine()); Console.Write("What is the year the car was made? "); MyCar.settheYear(Console.ReadLine()); Console.Write("What is the cost of the car? ");
file:///D|/1/final/BBL0048.html (7 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
MyCar.settheCost(Decimal.Parse(Console.ReadLine())); Console.Write("What was the color of the car? "); string ourColor = Console.ReadLine(); Colors newColor = (Colors)Enum.Parse(typeof(Colors), ourColor); MyCar.settheColor(newColor); Console.WriteLine("\n\n"); Console.WriteLine("Company: {0}", MyCar.gettheCompany()); Console.WriteLine("Model: {0}", MyCar.gettheModel()); Console.WriteLine("Year: {0}", MyCar.gettheYear()); Console.WriteLine("Cost: {0:c}", MyCar.gettheCost()); Console.WriteLine("Color: {0}\n\n", MyCar.gettheColor()); Console.ReadKey(); } } }
// program_id consdest.cs // written_by don voils // date_written 10/2/2006 // description This program illustrates how constructors // in a derived class call the constructors // in the base class. If a base class has a // constructor and data members and the // constructor has an argument, then the // derived class must have a constructor. // The constructor in the base class is // called before a constructor in a derived // derived class. // // In addition to constructors, this program // demonstrates how destructors are called. // Notice that the destructors are called in // reverse order to the constructors. That is // the destructors in the derived class are // called before the destructor in the base // class is called // using System; namespace inheritance { class stuffa { protected int int_stuff;
public stuffa() { int_stuff = 0; Console.WriteLine("Calling the stuffa no argument constructor."); } public stuffa(int a) { int_stuff = a; Console.WriteLine("Calling the stuffa argument constructor."); } ~stuffa() { Console.WriteLine("When int_stuff = {0} calling the stuffa destructor.", int_stuff); } public void print() { Console.WriteLine("through stuffa int_stuff = {0}", int_stuff); } }
file:///D|/1/final/BBL0048.html (8 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
class stuffb : stuffa { public stuffb() : base() { Console.WriteLine("Calling the stuffb no argument constructor."); } public stuffb(int a) : base(a) { Console.WriteLine("When int_stuff = {0} calling the stuffb argument constructor.", int_stuff); } ~stuffb() { Console.WriteLine("When int_stuff = {0} calling the stuffb destructor.", int_stuff); } public new void print() { Console.WriteLine("through stuffb int_stuff = {0}.", int_stuff); } } class myProgram { static void Main() { Console.WriteLine("\nDefining inta as an object of stuffa here with an argument."); stuffa inta = new stuffa(5); Console.WriteLine("\nDefining intb as an object of stuffb here with an argument."); // Notice that both the stuffb and the stuffa constructors are called. // The stuffa constructor is called first. // stuffb intb = new stuffb(15); Console.WriteLine("\nDefining intd as an object of stuffb here with no argument."); stuffb intd = new stuffb(); Console.WriteLine("\n\n"); Console.WriteLine("For inta "); inta.print(); Console.WriteLine("For intb "); intb.print(); Console.WriteLine("For intd "); intd.print(); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id constructor1.cs // written_by don voils // date_written 10/1/2006 // description This program demonstrates the derivation of // one class from another where the classes each // use the default constructor. // using System;
file:///D|/1/final/BBL0048.html (9 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
namespace constructor { class stuff { private short member; public void set_member(short a) { member = a; } public short show_member() { return member; } } class stuff1 : stuff { private short member1; public void set_member1(short a) { member1 = a; } public short show_member1() { return member1; } } class myProgram { static void Main() { // When object1 is defined below, the // consturctor of both the base class // and the derived class are called. // Both constructors in this case are // the implicit default constructors. // Console.WriteLine("An instance: object1 of the derived class stuff1 is defined.\n"); stuff1 object1 = new stuff1(); object1.set_member(10); object1.set_member1(15); Console.WriteLine("The value from member an attribute of the base class: stuff is {0}", object1.show_member()); Console.WriteLine("The value from member1 an attribute of the derived class: stuff1 is {0}\n\n", object1.show_member1()); Console.ReadKey(); } } }
// program_id constructor2.cs // written_by don voils // date_written 10/1/2006 // description This program demonstrates the derivation of // one class from another where the base class // uses a non-defined default constructor and the derived // class has a non-default constructor but calls // the default constructor of the base class. // using System; namespace constructor { class stuff { private short member; public void set_member(short a) { member = a; } public short show_member() { return member; } } class stuff1 : stuff
file:///D|/1/final/BBL0048.html (10 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
{ private short member1; public stuff1(short a) { member1 = a; } public short show_member1() { return member1; } } class myProgram { static void Main() { // When object11 is defined below, the impilict default constructor // of the base class as well as the explicit non-default construcotr // of the base class are called. // Console.WriteLine("An instance: object1 of the derived class stuff1 is defined.\n"); stuff1 object1 = new stuff1(15); Console.WriteLine("The base attribute of the instance: object1 is initialized.\n"); object1.set_member(10); Console.WriteLine("The base attribute: member from stuff is {0}", object1.show_member()); Console.WriteLine("The derived attribute: member1 from stuff1 is {0}\n\n", object1.show_member1()); Console.ReadKey(); } } }
// program_id constructor3.cs // written_by don voils // date_written 10/1/2006 // description This program demonstrates the derivation of // one class from another where the base classes has // a defined default constructor and the // derived class has a non-default constuctor that // is implicitly dependent on the base class' // default constructor. // using System; namespace constructor { class stuff { private short member; public stuff() { member = 1; Console.WriteLine("The value of member is {0}", member); } public void set_member(short a) { member = a; } public short show_member() { return member; } } class stuff1 : stuff { private short member1; public stuff1(short a) { member1 = a;
file:///D|/1/final/BBL0048.html (11 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
Console.WriteLine("The value of member1 is {0}", member1); } public short show_member1() { return member1; } }
class myProgram { static void Main() { // When object1 is defined below, the constructor // of the base and the constructor of the derived // class are both called. // Console.WriteLine("An instance: object1 of the derived class stuff1 is defined.\n"); stuff1 object1 = new stuff1(15); Console.WriteLine("\n\n"); Console.WriteLine("On definition the attribute: member from the base class: " + "stuff is {0}", object1.show_member()); Console.WriteLine("On definition the attribute: member1 from stuff1 is {0}", object1.show_member1()); object1.set_member(10); Console.WriteLine("\n\n"); Console.WriteLine("After the method: set_member() is called " + "the attribute: member from stuff is {0}\n\n", object1.show_member()); Console.ReadKey(); } } }
// program_id constructor4.cs // written_by don voils // date_written 10/1/2006 // description In this example the base class has // an explicit default and non-default // constructor. When an object of the // derived class is defined, the default // or the non-default constructor // of the base class is called depending // on which constructor of the derived // class is called. // using System; namespace constructor { class stuff { private short member; public stuff() { member = 1; Console.WriteLine("The default constructor of the base was called."); } public stuff(short a) { member = a; Console.WriteLine("The non default constructor of the base was called."); }
file:///D|/1/final/BBL0048.html (12 von 43) [01.12.2007 04:48:35]
Lecture 5 Examples
public void set_member(short a) { member = a; } public short show_member() { return member; } } class stuff1 : stuff { private short member1; public stuff1(short a) { member1 = a; Console.WriteLine("The default constructor of the derived class was called.\n"); } public stuff1(short a, short b) { member1 = a; set_member(b); Console.WriteLine("The non default constructor of the derived class was called.\n"); } public short show_member1() { return member1; } } class myProgram { static void Main() { // The instance object1 is defined and the default constructor // for the base class as well as the non-default constructor // of the derived class is called. // stuff1 object1 = new stuff1(15); Console.WriteLine("On definition of object1 the attribute: member from stuff is {0}", object1.show_member()); Console.WriteLine("On definition of object1 the attribute: member1 from stuff1 is {0}\n", object1.show_member1()); // The instance object2 of the derived class is defined // and the non-default constructor of the base is called. // stuff1 object2 = new stuff1(25, 35); Console.WriteLine("On definition of object2 the attribute: member from stuff is {0}", object2.show_member()); Console.WriteLine("On definition of object2 the attribute: member1 from stuff1 is {0}\n\n", object2.show_member1()); Console.ReadKey(); } } }
// program_id constructor5.cs // written_by don voils // date_written 10/2/2006 // description In this example the base class has // an explicit default and non-default // constructor. When an object of the // derived class is defined, the default // or the non-default constructor // of the base class is called depending // on which constructor of the derived // class is called. // using System;
file:///D|/1/final/BBL0048.html (13 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
namespace constructor { class stuff { private short member; public stuff() { member = 1; Console.WriteLine("The explicit default constructor of the base class was called."); } public stuff(short a) { member = a; Console.WriteLine("The non default constructor of the base class was called."); } public void set_member(short a) { member = a; } public short show_member() { return member; } } class stuff1 : stuff { private short member1; public stuff1(short a) { member1 = a; Console.WriteLine("The explicit non default constructor of the derived class\n" + "with one arguement was called."); } // Notice that this constructor calls // the non-default constructor of the // base class. public stuff1(short a, short b): base(b) { member1 = a; Console.WriteLine("The explicit non default constructor of the derived class\n" + "with two arguements was called."); } public short show_member1() { return member1; } } class myProgram { static void Main() { // The instance object1 is defined and the default constructor // for the base class as well as the non-default constructor // of the derived class is called. // stuff1 object1 = new stuff1(15); Console.WriteLine("\nOn definition of object1 the attribute: member from stuff is {0}", object1.show_member()); Console.WriteLine("On definition of object1 the attribute: member1 from stuff1 is {0}\n", object1.show_member1()); // The instance object2 of the derived class is defined // and the non-default constructor of the base with an argument is called. // stuff1 object2 = new stuff1(25, 35); Console.WriteLine("\nOn definition of object2 the attribute: member from stuff is {0}", object2.show_member()); Console.WriteLine("On definition of object2 the attribute: member1 from stuff1 is {0}\n\n", object2.show_member1());
file:///D|/1/final/BBL0048.html (14 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
Console.ReadKey(); } } }
// program_id constructor6.cs // written_by don voils // date_written 10/2/2006 // description In this example the base class has // an explicit default and non-default // constructor. When an object of the // derived class is defined, the default // or the non-default constructor // of the base class is called depending // on which constructor of the derived // class is called. // using System; namespace constructor { class stuff { private short member; public stuff() { member = 1; Console.WriteLine("Base class stuff explicit default constructor was called."); } public stuff(short a) { member = a; Console.WriteLine("Base class stuff non default constructor was called."); } public void set_member(short a) { member = a; } public short show_member() { return member; } } class stuff1 : stuff { private short member1; public stuff1() { member1 = 2; Console.WriteLine("Base class stuff1 explicit default constructor was called."); } public stuff1(short a) { member1 = a; Console.WriteLine("Base class stuff1 non default constructor\n" + "with one argument was called."); } public stuff1(short a, short b) : base(b) { member1 = a; Console.WriteLine("Base class stuff1 non default constructor\n" + "with two arguments was called."); } public short show_member1() { return member1; } }
file:///D|/1/final/BBL0048.html (15 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
class stuff2 : stuff1 { private short member2; public stuff2() { member2 = 3; Console.WriteLine("The derived class stuff2 explicit default constructor was called."); } public stuff2(short a) { member2 = a; Console.WriteLine("The derived class stuff2 explicit non default constructor\n" + "with one argument was called."); } public stuff2(short a, short b) : base(a) { member2 = b; Console.WriteLine("The derived class stuff2 explicit non default constructor\n" + "with two arguments was called."); } public stuff2(short a, short b, short c) : base(a, b) { member2 = c; Console.WriteLine("The derived class stuff2 explicit non default constructor\n" + "with three arguments that calls the two argument constructor\n" + "of the base class: stuff1 was called."); } public short show_member2() { return member2; } } class myProgram { static void Main() { // The instance object1 is defined and the default constructor // for both the base classs as well as the default constructor // of the derived class: stuff2 is called. // stuff2 object1 = new stuff2(); Console.WriteLine("\nOn definition of object1 the attribute: member from stuff is {0}", object1.show_member()); Console.WriteLine("On definition of object1 the attribute: member1 from stuff1 is {0}", object1.show_member1()); Console.WriteLine("On definition of object1 the attribute: member2 from stuff2 is {0}\n", object1.show_member2()); Console.WriteLine("\n"); // The instance object2 of the derived class: stuff2 is defined // and the default constructor of both bases are called. // stuff2 object2 = new stuff2(25); Console.WriteLine("\nOn definition of object2 the attribute: member from stuff is {0}", object2.show_member()); Console.WriteLine("On definition of object2 the attribute: member1 from stuff1 is {0}", object2.show_member1()); Console.WriteLine("On definition of object2 the attribute: member2 from stuff2 is {0}\n", object2.show_member2()); Console.WriteLine("\n"); // The instance object3 of the derived class: stuff2 is defined // and the default constructor of one of bases and the non default // constructor of the other base class is called. // stuff2 object3 = new stuff2(35, 45);
file:///D|/1/final/BBL0048.html (16 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
Console.WriteLine("\nOn definition of object3 the attribute: member from stuff is {0}", object3.show_member()); Console.WriteLine("On definition of object3 the attribute: member1 from stuff1 is {0}", object3.show_member1()); Console.WriteLine("On definition of object3 the attribute: member2 from stuff2 is {0}\n", object3.show_member2()); Console.WriteLine("\n"); // The instance object4 of the derived class: stuff2 is defined // and the non default constructors of both bases are called. // stuff2 object4 = new stuff2(55, 65, 75); Console.WriteLine("\nOn definition of object4 the attribute: member from stuff is {0}", object4.show_member()); Console.WriteLine("On definition of object4 the attribute: member1 from stuff1 is {0}", object4.show_member1()); Console.WriteLine("On definition of object4 the attribute: member2 from stuff2 is {0}\n\n", object4.show_member2()); Console.ReadKey(); } } }
// program_id inheritance1.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how // to use inheritance. // using System; class theProgram { public class Customer { private string CustomerID; private string CustomerName; private string CustomerAddress; private string CustomerCity; private string CustomerState; private string CustomerZipCode; public void setCustomerID(string ID) { CustomerID = ID; } public void setCustomerName(string Name) { CustomerName = Name; } public void setCustomerAddress(string Address) { CustomerAddress = Address; } public void setCustomerCity(string City) { CustomerCity = City; } public void setCustomerState(string State) { CustomerState = State; } public void setCustomerZipCode(string Code) { CustomerZipCode = Code; } public string getCustomerID() { return CustomerID;
file:///D|/1/final/BBL0048.html (17 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
} public string getCustomerName() { return CustomerName; } public string getCustomerAddress() { return CustomerAddress; } public string getCustomerCity() { return CustomerCity; } public string getCustomerState() { return CustomerState; } public string getCustomerZipCode() { return CustomerZipCode; } } public class Invoice : Customer { private decimal InvoiceAmount; public void setInvoiceAmount(decimal Amount) { InvoiceAmount = Amount; } public decimal getInvoiceAmount() { return InvoiceAmount; } } static void Main() { Invoice theTransaction = new Invoice(); Console.Write("What is the customer's ID? "); theTransaction.setCustomerID(Console.ReadLine()); Console.Write("What is the customer's name? "); theTransaction.setCustomerName(Console.ReadLine()); Console.Write("What is the customer's address? "); theTransaction.setCustomerAddress(Console.ReadLine()); Console.Write("What is the customer's city? "); theTransaction.setCustomerCity(Console.ReadLine()); Console.Write("What is the customer's state? "); theTransaction.setCustomerState(Console.ReadLine()); Console.Write("What is the customer's zip code? "); theTransaction.setCustomerZipCode(Console.ReadLine()); Console.Write("What is the amount of the invoice? "); theTransaction.setInvoiceAmount(Decimal.Parse(Console.ReadLine())); Console.Clear(); Console.WriteLine("Customer ID: {0}", theTransaction.getCustomerID()); Console.WriteLine("Customer Name: {0}", theTransaction.getCustomerName()); Console.WriteLine("Customer Address: {0}", theTransaction.getCustomerAddress()); Console.WriteLine("Customer City: {0}", theTransaction.getCustomerCity()); Console.WriteLine("Customer State: {0}", theTransaction.getCustomerState()); Console.WriteLine("Customer Zip Code: {0}", theTransaction.getCustomerZipCode()); Console.WriteLine("Invoice Amount: {0,15:c}\n\n", theTransaction.getInvoiceAmount()); Console.ReadKey(); }
}
file:///D|/1/final/BBL0048.html (18 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// program_id inheritance2.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how // to use inheritance. // using System; class theProgram { public class People { private string PeopleID; private string PeopleName; private string PeopleAddress; private string PeopleCity; private string PeopleState; private string PeopleZipCode; public void setPeopleID(string ID) { PeopleID = ID; } public void setPeopleName(string Name) { PeopleName = Name; } public void setPeopleAddress(string Address) { PeopleAddress = Address; } public void setPeopleCity(string City) { PeopleCity = City; } public void setPeopleState(string State) { PeopleState = State; } public void setPeopleZipCode(string Code) { PeopleZipCode = Code; } public string getPeopleID() { return PeopleID; } public string getPeopleName() { return PeopleName; } public string getPeopleAddress() { return PeopleAddress; } public string getPeopleCity() { return PeopleCity; } public string getPeopleState() { return PeopleState; } public string getPeopleZipCode() { return PeopleZipCode; } } public class Employee : People { private char PayType; private decimal PayRate;
file:///D|/1/final/BBL0048.html (19 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
private decimal GrossPay; public void setPayType(char Type) { PayType = Type; } public char getPayType() { return PayType; } public void setPayRate(decimal Rate) { PayRate = Rate; } public decimal getPayRate() { return PayRate; } public void setGrossPay(decimal Amount) { GrossPay = Amount; } public decimal getGrossPay() { return GrossPay; } } public class Customer : People { private decimal BalancetDue; public void setBalanceDue(decimal Amount) { BalancetDue = Amount; } public decimal getBalanceDue() { return BalancetDue; } } public class Vendor : People { private decimal AmountOwed; public void setAmountOwed(decimal Amount) { AmountOwed = Amount; } public decimal getAmountOwed() { return AmountOwed; } } static void Main() { bool processAgain = true; while (processAgain == true) { Console.WriteLine(" Account Type\n"); Console.WriteLine(" 1. Employee"); Console.WriteLine(" 2. Customer"); Console.WriteLine(" 3. Vendor"); Console.Write("\n Which? "); char TransactionType = Char.Parse(Console.ReadLine()); Console.Clear(); switch (TransactionType) { case '1': processEmployee(); break; case '2': processCustomer(); break; case '3': processVendor();
file:///D|/1/final/BBL0048.html (20 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
break; default: Console.WriteLine("You selected an incorrect type." + "Please try again.\n"); break; } Console.Write("\nDo you want to process another? Y or N "); TransactionType = Char.Parse(Console.ReadLine()); Console.Clear(); if ((TransactionType != 'y') && (TransactionType != 'Y')) processAgain = false; else processAgain = true; } } static void processEmployee() { Employee theTransaction = new Employee(); Console.Write("What is the employee's ID? "); theTransaction.setPeopleID(Console.ReadLine()); Console.Write("What is the employee's name? "); theTransaction.setPeopleName(Console.ReadLine()); Console.Write("What is the employee's address? "); theTransaction.setPeopleAddress(Console.ReadLine()); Console.Write("What is the employee's city? "); theTransaction.setPeopleCity(Console.ReadLine()); Console.Write("What is the employee's state? "); theTransaction.setPeopleState(Console.ReadLine()); Console.Write("What is the employee's zip code? "); theTransaction.setPeopleZipCode(Console.ReadLine()); char theType; do { Console.Write("What is the employee's pay type (H:Hourly or S:Salaried? "); theType = Char.Parse(Console.ReadLine()); } while ((theType != 'H') && (theType != 'h') && (theType != 'S') && (theType != 's')); theTransaction.setPayType(theType); Console.Write("What is the employee's pay rate? "); theTransaction.setPayRate(Decimal.Parse(Console.ReadLine())); Console.Write("What is the employee's gross pay? "); theTransaction.setGrossPay(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\n\n"); Console.Clear(); Console.WriteLine("Employee ID: {0}", theTransaction.getPeopleID()); Console.WriteLine("Employee Name: {0}", theTransaction.getPeopleName()); Console.WriteLine("Employee Address: {0}", theTransaction.getPeopleAddress()); Console.WriteLine("Employee City: {0}", theTransaction.getPeopleCity()); Console.WriteLine("Employee State: {0}", theTransaction.getPeopleState()); Console.WriteLine("Employee Zip Code: {0}", theTransaction.getPeopleZipCode()); Console.WriteLine("Employee Pay Type: {0}", theTransaction.getPayType()); Console.WriteLine("Employee Pay Rate: {0,15:c}", theTransaction.getPayRate()); Console.WriteLine("Employee Gross Pay: {0,15:c}", theTransaction.getGrossPay()); Console.WriteLine("\n\n"); } static void processCustomer() { Customer theTransaction = new Customer(); Console.Write("What is the customer's ID? "); theTransaction.setPeopleID(Console.ReadLine()); Console.Write("What is the customer's name? "); theTransaction.setPeopleName(Console.ReadLine());
file:///D|/1/final/BBL0048.html (21 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
Console.Write("What is the customer's address? "); theTransaction.setPeopleAddress(Console.ReadLine()); Console.Write("What is the customer's city? "); theTransaction.setPeopleCity(Console.ReadLine()); Console.Write("What is the customer's state? "); theTransaction.setPeopleState(Console.ReadLine()); Console.Write("What is the customer's zip code? "); theTransaction.setPeopleZipCode(Console.ReadLine()); Console.Write("What is the cutomer's balance due? "); theTransaction.setBalanceDue(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\n\n"); Console.Clear(); Console.WriteLine("Customer ID: {0}", theTransaction.getPeopleID()); Console.WriteLine("Customer Name: {0}", theTransaction.getPeopleName()); Console.WriteLine("Customer Address: {0}", theTransaction.getPeopleAddress()); Console.WriteLine("Customer City: {0}", theTransaction.getPeopleCity()); Console.WriteLine("Customer State: {0}", theTransaction.getPeopleState()); Console.WriteLine("Customer Zip Code: {0}", theTransaction.getPeopleZipCode()); Console.WriteLine("Cusomter Balance Due: {0,15:c}", theTransaction.getBalanceDue()); Console.WriteLine("\n\n"); }
static void processVendor() { Vendor theTransaction = new Vendor(); Console.Write("What is the vendor's ID? "); theTransaction.setPeopleID(Console.ReadLine()); Console.Write("What is the vendor's name? "); theTransaction.setPeopleName(Console.ReadLine()); Console.Write("What is the vendor's address? "); theTransaction.setPeopleAddress(Console.ReadLine()); Console.Write("What is the vendor's city? "); theTransaction.setPeopleCity(Console.ReadLine()); Console.Write("What is the vendor's state? "); theTransaction.setPeopleState(Console.ReadLine()); Console.Write("What is the vendor's zip code? "); theTransaction.setPeopleZipCode(Console.ReadLine()); Console.Write("What is the amount owed the vendor? "); theTransaction.setAmountOwed(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\n\n"); Console.Clear(); Console.WriteLine("Vendor ID: {0}", theTransaction.getPeopleID()); Console.WriteLine("Vendor Name: {0}", theTransaction.getPeopleName()); Console.WriteLine("Vendor Address: {0}", theTransaction.getPeopleAddress()); Console.WriteLine("Vendor City: {0}", theTransaction.getPeopleCity()); Console.WriteLine("Vendor State: {0}", theTransaction.getPeopleState()); Console.WriteLine("Vendor Zip Code: {0}", theTransaction.getPeopleZipCode()); Console.WriteLine("Amount Owed: {0,15:c}", theTransaction.getAmountOwed()); Console.WriteLine("\n\n"); } }
// program_id inheritance3.cs // written_by don voils // date_written 10/2/2006 // description In this example the base class has a // protected attribute that is accessible // in the derived class. In addition the // derived class has methods with the // same name as the base class and overcomes
file:///D|/1/final/BBL0048.html (22 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// //
this restriction by using the keyword word: new.
using System; namespace constructor { class stuff { protected int member; public void setMember(int a) { member = a; Console.WriteLine("Through the stuff class using the setMember() method.\n"); } public void print() { Console.WriteLine("Through the stuff class using the print() method: member = {0}.\n", member); } } class stuff1 : stuff { public new void setMember(int a) { member = a; Console.WriteLine("Through the class stuff1 using the setMember() method.\n"); } public new void print() { Console.WriteLine("Through the class stuff1 using the print() method: member = {0}.\n", member); } } class myProgram { static void Main() { Console.WriteLine("Defining theObject an object of the class stuff.\n"); stuff theObject = new stuff(); theObject.setMember(10); theObject.print(); Console.WriteLine("\n\n"); Console.WriteLine("Defining object1 an object of the class stuff1.\n"); stuff1 object1 = new stuff1(); object1.setMember(15); object1.print(); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id inheritance4.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how // to prevent inheritance. The program is // the same as inheritance1.cs except // the class Customer is sealed. The // program inheritance1.cs compiled and // ran but this program will not.
file:///D|/1/final/BBL0048.html (23 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// using System; class theProgram { sealed public class Customer { private string CustomerID; private string CustomerName; private string CustomerAddress; private string CustomerCity; private string CustomerState; private string CustomerZipCode; public void setCustomerID(string ID) { CustomerID = ID; } public void setCustomerName(string Name) { CustomerName = Name; } public void setCustomerAddress(string Address) { CustomerAddress = Address; } public void setCustomerCity(string City) { CustomerCity = City; } public void setCustomerState(string State) { CustomerState = State; } public void setCustomerZipCode(string Code) { CustomerZipCode = Code; } public string getCustomerID() { return CustomerID; } public string getCustomerName() { return CustomerName; } public string getCustomerAddress() { return CustomerAddress; } public string getCustomerCity() { return CustomerCity; } public string getCustomerState() { return CustomerState; } public string getCustomerZipCode() { return CustomerZipCode; } } public class Invoice : Customer { private decimal InvoiceAmount; public void setInvoiceAmount(decimal Amount) { InvoiceAmount = Amount; } public decimal getInvoiceAmount()
file:///D|/1/final/BBL0048.html (24 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
{ return InvoiceAmount; } } static void Main() { Invoice theTransaction = new Invoice(); Console.Write("What is the customer's ID? "); theTransaction.setCustomerID(Console.ReadLine()); Console.Write("What is the customer's name? "); theTransaction.setCustomerName(Console.ReadLine()); Console.Write("What is the customer's address? "); theTransaction.setCustomerAddress(Console.ReadLine()); Console.Write("What is the customer's city? "); theTransaction.setCustomerCity(Console.ReadLine()); Console.Write("What is the customer's state? "); theTransaction.setCustomerState(Console.ReadLine()); Console.Write("What is the customer's zip code? "); theTransaction.setCustomerZipCode(Console.ReadLine()); Console.Write("What is the amount of the invoice? "); theTransaction.setInvoiceAmount(Decimal.Parse(Console.ReadLine())); Console.Clear(); Console.WriteLine("Customer ID: {0}", theTransaction.getCustomerID()); Console.WriteLine("Customer Name: {0}", theTransaction.getCustomerName()); Console.WriteLine("Customer Address: {0}", theTransaction.getCustomerAddress()); Console.WriteLine("Customer City: {0}", theTransaction.getCustomerCity()); Console.WriteLine("Customer State: {0}", theTransaction.getCustomerState()); Console.WriteLine("Customer Zip Code: {0}", theTransaction.getCustomerZipCode()); Console.WriteLine("Invoice Amount: {0,15:c}", theTransaction.getInvoiceAmount()); Console.WriteLine("\n\n"); } }
// program_id inheritance5.cs // written_by don voils // date_written 10/2/2006 // description This example is contains two class // one of which is derived from the other. // The base class and the derived class contain // methods with the same name. While the program // compiles and runs, it contains several warning // error notifying the programmer that the two // classes have methods with the same names. // using System; namespace constructor { class stuff { protected int member; public void setMember(int a) { member = a; Console.WriteLine("Through the stuff class using the setMember() method.\n"); } public void print() { Console.WriteLine("Through the stuff class using the print() method: member = {0}.\n" , member); } }
file:///D|/1/final/BBL0048.html (25 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
class stuff1 : stuff { // has the same name as a method in the base class. // public void setMember(int a) { member = a; Console.WriteLine("Through the class stuff1 using the setMember() method.\n"); } // has the same name as a method in the base class. public void print() { Console.WriteLine("Through the class stuff1 using the print() method: member = {0}.\n", member); } } class myProgram { static void Main() { Console.WriteLine("Defining theObject an object of the class stuff.\n"); stuff theObject = new stuff(); theObject.setMember(10); theObject.print(); Console.WriteLine("\n\n"); Console.WriteLine("Defining object1 an object of the class stuff1.\n"); stuff1 object1 = new stuff1(); object1.setMember(15); object1.print(); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id inheritance6.cs // written_by don voils // date_written 10/2/2006 // description In this example the base class has a // protected attribute that is accessible // in the derived class. // // In addition the derived class has methods with the // same name as the base class. This overcomes // this restriction by using the keyword words: virtual // in the base class and overridden in the derived class. // using System; namespace theProgram { class theBase { protected int member; virtual public void setMember(int a) { member = a; Console.WriteLine("Through the theBase class using the setMember() method.\n"); }
file:///D|/1/final/BBL0048.html (26 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
virtual public void print() { Console.WriteLine("Through the theBase class using the print() method: member = {0}.\n", member); } } // Notice that the attribute member of theBase class was // declared as protected, therefore it is accessible in the // derived class as though it was a private attribute // of the derived class. // class theDerived : theBase { override public void setMember(int a) { member = a; Console.WriteLine("Through the class theDerived using setMember() method.\n"); } override public void print() { Console.WriteLine("Through the class theDerived using print() method: member = {0}.\n", member); } } class myProgram { static void Main() { Console.WriteLine("Defining theBaseObject an object of the class theBase.\n"); theBase theBaseObject = new theBase(); theBaseObject.setMember(10); theBaseObject.print(); Console.WriteLine("\n\n"); Console.WriteLine("Defining theDerivedObject an object of the class theDerived.\n"); theDerived theDerivedObject = new theDerived(); theDerivedObject.setMember(15); theDerivedObject.print(); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id inheritance7.cs // written_by don voils // date_written 10/2/2006 // description In this example the base class has a // methods that are declared as virtual. // The derived class does not have methods // by these names. However the program // compiles and runs. // using System; namespace theProgram { class theBase { protected int member; virtual public void setMember(int a)
file:///D|/1/final/BBL0048.html (27 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
{ member = a; Console.WriteLine("Through the theBase class using the setMember() method.\n"); } virtual public void print() { Console.WriteLine("Through the theBase class using the print() method: member = {0}.\n", member); } } class theDerived : theBase { } class myProgram { static void Main() { Console.WriteLine("Defining theBaseObject an object of the class theBase.\n"); theBase theBaseObject = new theBase(); theBaseObject.setMember(10); theBaseObject.print(); Console.WriteLine("\n\n"); Console.WriteLine("Defining theDerivedObject an object of the class theDerived.\n"); theDerived theDerivedObject = new theDerived(); theDerivedObject.setMember(15); theDerivedObject.print(); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id nesting1.cs // written_by don voils // date_written 10/1/2006 // description This program demonstrates the nesting of one // class definition inside of another. // using System; namespace theNewDate { public class theDate { private int theMonth; private int theDay; private int theYear; public int Month { get { return theMonth; } set { theMonth = (value < 1 || value > 12) ? (1) : (value); } } public int Day { get
file:///D|/1/final/BBL0048.html (28 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
{ return theDay; } set { theDay = (value < 1 || value > 31) ? (1) : (value); } } public int Year { get { return theYear; } set { theYear = value; } } public override string ToString() { // The following is an array of strings. Arrays // will be discussed in a later lecture. // string[] monthName = {"","JANUARY","FEBRUARY","MARCH", "APRIL", "MAY","JUNE","JULY","AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER","DECEMBER"}; if (Year < 10) { Year += 2000; } else if (Year < 100) { Year += 1900; } return ("\n\n" + monthName[Month] + " " + Day + ", " + Year + "\n\n"); } // Notice the definition of the class: Drawdate which is // nested inside of the class theDate. // internal class DrawDate { public void Drawing(theDate d) { Console.WriteLine("Drawing the month {0}", d.Month); Console.WriteLine("Drawing the day {0}", d.Day); Console.WriteLine("Drawing the year {0}", d.Year); } } } class theProgram { static void Main(string[] args) { theDate aDate = new theDate(); Console.Write("What is the month? "); aDate.Month = int.Parse(Console.ReadLine()); Console.Write("What is the day? "); aDate.Day = int.Parse(Console.ReadLine()); Console.Write("What is the year? "); aDate.Year = int.Parse(Console.ReadLine()); Console.WriteLine("\n\n"); Console.WriteLine("The date is {0}", aDate.ToString()); Console.WriteLine("\n\n"); // Notice that the instance newDate is defined to be
file:///D|/1/final/BBL0048.html (29 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// an instance of the class DrawDate which is nested // inside of the class: theDate. // theDate.DrawDate newDate = new theDate.DrawDate(); newDate.Drawing(aDate); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id People.cs // written_by don voils // date_written 7/13/2006 // description This file contains the definition of // the class People. // namespace thePeople { class People { private string accountNumber; private string name; private string address; private string city; private string state; private string zip; public string Number { get { return accountNumber; } set { accountNumber = value; } } public string Name { get { return name; } set { name = value; } } public string Address { get { return address; } set { address = value; } } public string City { get { return city; } set { city = value; }
file:///D|/1/final/BBL0048.html (30 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
} public string State { get { return state; } set { state = value; } } public string Zip { get { return zip; } set { zip = value; } } } }
// program_id Form1.cs // written_by don voils // date_written 7/14/2006 // description This file is part of the program: SEATBilling.exe // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using thePeople; using theBilling; namespace SEATBilling { public partial class Form1 : Form { private Billing theClient; public Form1() { InitializeComponent(); theCharge.ReadOnly = true; theCharge.TabStop = false; checkCharge.Visible = true; printBill.Visible = false; accountNumber.Focus(); } // This event handler prints the data and then clears the form // private void printBill_Click(object sender, EventArgs e) { // printing of theClient goes here. // accountNumber.Text = ""; theName.Text = ""; theAddress.Text = ""; theCity.Text = ""; theState.Text = ""; theZip.Text = ""; theMonth.Text = ""; theDay.Text = ""; theYear.Text = "";
file:///D|/1/final/BBL0048.html (31 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
theTransaction.Text = ""; theLawyer.Text = ""; theDescription.Text = ""; theRate.Text = ""; theHours.Text = ""; theCharge.Text = ""; accountNumber.ReadOnly = false; theName.ReadOnly = false; theAddress.ReadOnly = false; theCity.ReadOnly = false; theState.ReadOnly = false; theZip.ReadOnly = false; theMonth.ReadOnly = false; theDay.ReadOnly = false; theYear.ReadOnly = false; theTransaction.ReadOnly = false; theLawyer.ReadOnly = false; theDescription.ReadOnly = false; theRate.ReadOnly = false; theHours.ReadOnly = false; checkCharge.Visible = true; printBill.Visible = false; accountNumber.Focus(); } // This event handler stores the data into the object // calculates the fee and then changes the status // of the textboxes. // private void checkCharge_Click(object sender, EventArgs e) { theClient = new Billing(Int32.Parse(theMonth.Text),Int32.Parse(theDay.Text),Int32.Parse(theYear.Text)); theClient.Number = accountNumber.Text; theClient.Name = theName.Text; theClient.Address = theAddress.Text; theClient.City = theCity.Text; theClient.State = theState.Text; theClient.Zip = theZip.Text; theClient.TransactionNumber = theTransaction.Text; theClient.Lawyer = theLawyer.Text; theClient.Description = theDescription.Text; theClient.HourlyRate = double.Parse(theRate.Text); theClient.HoursServed = double.Parse(theHours.Text); theCharge.Text = string.Format("{0:c}", (theClient.HoursServed * theClient.HourlyRate)); accountNumber.ReadOnly = true; theName.ReadOnly = true; theAddress.ReadOnly = true; theCity.ReadOnly = true; theState.ReadOnly = true; theZip.ReadOnly = true; theMonth.ReadOnly = true; theDay.ReadOnly = true; theYear.ReadOnly = true; theTransaction.ReadOnly = true; theLawyer.ReadOnly = true; theDescription.ReadOnly = true; theRate.ReadOnly = true; theHours.ReadOnly = true; printBill.Visible = true; printBill.Focus(); checkCharge.Visible = false; } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 7/14/2006 // description This file is part of the program: SEATBilling.exe // namespace SEATBilling
file:///D|/1/final/BBL0048.html (32 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
{ partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.accountNumber = new System.Windows.Forms.TextBox(); this.theName = new System.Windows.Forms.TextBox(); this.theAddress = new System.Windows.Forms.TextBox(); this.theCity = new System.Windows.Forms.TextBox(); this.theState = new System.Windows.Forms.TextBox(); this.theZip = new System.Windows.Forms.TextBox(); this.theMonth = new System.Windows.Forms.TextBox(); this.theDay = new System.Windows.Forms.TextBox(); this.theYear = new System.Windows.Forms.TextBox(); this.theTransaction = new System.Windows.Forms.TextBox(); this.theLawyer = new System.Windows.Forms.TextBox(); this.theDescription = new System.Windows.Forms.TextBox(); this.theHours = new System.Windows.Forms.TextBox(); this.theRate = new System.Windows.Forms.TextBox(); this.printBill = new System.Windows.Forms.Button(); this.label13 = new System.Windows.Forms.Label(); this.theCharge = new System.Windows.Forms.TextBox(); this.checkCharge = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(35, 30); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(127, 17); this.label1.TabIndex = 0; this.label1.Text = "Account Number"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(35, 60);
file:///D|/1/final/BBL0048.html (33 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(49, 17); this.label2.TabIndex = 1; this.label2.Text = "Name"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(35, 90); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(67, 17); this.label3.TabIndex = 2; this.label3.Text = "Address"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(35, 120); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(35, 17); this.label4.TabIndex = 3; this.label4.Text = "City"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(35, 150); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(46, 17); this.label5.TabIndex = 4; this.label5.Text = "State"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(35, 180); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(31, 17); this.label6.TabIndex = 5; this.label6.Text = "Zip"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(35, 270); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(59, 17); this.label7.TabIndex = 6; this.label7.Text = "Lawyer"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(35, 210); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(246, 17); this.label8.TabIndex = 7; this.label8.Text = "Transaction Date (MM/DD/YYYY)"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(35, 240); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(155, 17); this.label9.TabIndex = 8; this.label9.Text = "Transaction Number"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(35, 300); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(90, 17); this.label10.TabIndex = 9;
file:///D|/1/final/BBL0048.html (34 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
this.label10.Text = "Description"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(35, 330); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(107, 17); this.label11.TabIndex = 10; this.label11.Text = "Hours Served"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(35, 360); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(94, 17); this.label12.TabIndex = 11; this.label12.Text = "Hourly Rate"; // // accountNumber // this.accountNumber.Location = new System.Drawing.Point(220, 30); this.accountNumber.Name = "accountNumber"; this.accountNumber.Size = new System.Drawing.Size(100, 22); this.accountNumber.TabIndex = 1; // // theName // this.theName.Location = new System.Drawing.Point(220, 60); this.theName.Name = "theName"; this.theName.Size = new System.Drawing.Size(100, 22); this.theName.TabIndex = 2; // // theAddress // this.theAddress.Location = new System.Drawing.Point(220, 90); this.theAddress.Name = "theAddress"; this.theAddress.Size = new System.Drawing.Size(190, 22); this.theAddress.TabIndex = 3; // // theCity // this.theCity.Location = new System.Drawing.Point(220, 120); this.theCity.Name = "theCity"; this.theCity.Size = new System.Drawing.Size(100, 22); this.theCity.TabIndex = 4; // // theState // this.theState.Location = new System.Drawing.Point(220, 150); this.theState.Name = "theState"; this.theState.Size = new System.Drawing.Size(100, 22); this.theState.TabIndex = 5; // // theZip // this.theZip.Location = new System.Drawing.Point(220, 180); this.theZip.Name = "theZip"; this.theZip.Size = new System.Drawing.Size(100, 22); this.theZip.TabIndex = 6; // // theMonth // this.theMonth.Location = new System.Drawing.Point(285, 210); this.theMonth.Name = "theMonth"; this.theMonth.Size = new System.Drawing.Size(26, 22); this.theMonth.TabIndex = 7; // // theDay // this.theDay.Location = new System.Drawing.Point(320, 210); this.theDay.Name = "theDay"; this.theDay.Size = new System.Drawing.Size(26, 22);
file:///D|/1/final/BBL0048.html (35 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
this.theDay.TabIndex = 8; // // theYear // this.theYear.Location = new System.Drawing.Point(355, 210); this.theYear.Name = "theYear"; this.theYear.Size = new System.Drawing.Size(55, 22); this.theYear.TabIndex = 9; // // theTransaction // this.theTransaction.Location = new System.Drawing.Point(220, 240); this.theTransaction.Name = "theTransaction"; this.theTransaction.Size = new System.Drawing.Size(100, 22); this.theTransaction.TabIndex = 10; // // theLawyer // this.theLawyer.Location = new System.Drawing.Point(220, 270); this.theLawyer.Name = "theLawyer"; this.theLawyer.Size = new System.Drawing.Size(100, 22); this.theLawyer.TabIndex = 11; // // theDescription // this.theDescription.Location = new System.Drawing.Point(220, 300); this.theDescription.Name = "theDescription"; this.theDescription.Size = new System.Drawing.Size(190, 22); this.theDescription.TabIndex = 12; // // theHours // this.theHours.Location = new System.Drawing.Point(220, 330); this.theHours.Name = "theHours"; this.theHours.Size = new System.Drawing.Size(100, 22); this.theHours.TabIndex = 13; this.theHours.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // theRate // this.theRate.Location = new System.Drawing.Point(220, 360); this.theRate.Name = "theRate"; this.theRate.Size = new System.Drawing.Size(100, 22); this.theRate.TabIndex = 14; this.theRate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // printBill // this.printBill.Location = new System.Drawing.Point(308, 445); this.printBill.Name = "printBill"; this.printBill.Size = new System.Drawing.Size(102, 23); this.printBill.TabIndex = 17; this.printBill.Text = "Print Bill"; this.printBill.UseVisualStyleBackColor = true; this.printBill.Click += new System.EventHandler(this.printBill_Click); // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(35, 390); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(102, 17); this.label13.TabIndex = 16; this.label13.Text = "Total Charge"; // // theCharge // this.theCharge.Location = new System.Drawing.Point(220, 394); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(100, 22); this.theCharge.TabIndex = 15; this.theCharge.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // checkCharge
file:///D|/1/final/BBL0048.html (36 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// this.checkCharge.Location = new System.Drawing.Point(38, 445); this.checkCharge.Name = "checkCharge"; this.checkCharge.Size = new System.Drawing.Size(175, 23); this.checkCharge.TabIndex = 16; this.checkCharge.Text = "Check Total Charge"; this.checkCharge.UseVisualStyleBackColor = true; this.checkCharge.Click += new System.EventHandler(this.checkCharge_Click); // // Form1 // this.ClientSize = new System.Drawing.Size(455, 487); this.Controls.Add(this.checkCharge); this.Controls.Add(this.theCharge); this.Controls.Add(this.label13); this.Controls.Add(this.printBill); this.Controls.Add(this.theRate); this.Controls.Add(this.theHours); this.Controls.Add(this.theDescription); this.Controls.Add(this.theLawyer); this.Controls.Add(this.theTransaction); this.Controls.Add(this.theYear); this.Controls.Add(this.theDay); this.Controls.Add(this.theMonth); this.Controls.Add(this.theZip); this.Controls.Add(this.theState); this.Controls.Add(this.theCity); this.Controls.Add(this.theAddress); this.Controls.Add(this.theName); this.Controls.Add(this.accountNumber); this.Controls.Add(this.label12); this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.Name = "Form1"; this.Text = "SEAT Monthly Billing"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox accountNumber; private System.Windows.Forms.TextBox theName; private System.Windows.Forms.TextBox theAddress; private System.Windows.Forms.TextBox theCity; private System.Windows.Forms.TextBox theState; private System.Windows.Forms.TextBox theZip; private System.Windows.Forms.TextBox theMonth; private System.Windows.Forms.TextBox theDay; private System.Windows.Forms.TextBox theYear; private System.Windows.Forms.TextBox theTransaction; file:///D|/1/final/BBL0048.html (37 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
private System.Windows.Forms.TextBox theLawyer; private System.Windows.Forms.TextBox theDescription; private System.Windows.Forms.TextBox theHours; private System.Windows.Forms.TextBox theRate; private System.Windows.Forms.Button printBill; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox theCharge; private System.Windows.Forms.Button checkCharge; } }
// program_id Program.cs // written_by don voils // date_written 7/14/2006 // description This file is part of the program: SEATBilling.exe // using System; using System.Collections.Generic; using System.Windows.Forms; namespace SEATBilling { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id theAbstract1.cs // written by don voils // date_written 10/3/2006 // Descriptioin The program shows how an abstract // class and method can be defined as // well as how to derive a class from the // abstract class. If the keyword: override // is removed from the definition of the // method show() in the derived class, // the program will not compile. // using System; class theProgram { abstract public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } abstract public short show(); } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort;
file:///D|/1/final/BBL0048.html (38 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
} override public short show() { return theDerivedMember; } } static void Main() { theDerived theDerivedReference = new theDerived(1, 2); Console.WriteLine("The value of theBaseMember is {0}.\n\n", theDerivedReference.show()); Console.ReadKey(); }
}
// program_id theAbstract2.cs // written by don voils // date_written 10/3/2006 // Descriptioin This program shows how an abstract // class and method can be defined as // well as how to derive a class from a class // that is derived from an abstract class. // In this case, this second derived class // does not have to override the base class' // abstract method. // using System; class theProgram { abstract public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } abstract public short show(); } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort): base(firstShort) { theDerivedMember = secondShort; } override public short show() { return theDerivedMember; } } public class nextDerived : theDerived { private short theNextDerivedMember; public nextDerived(short firstShort, short secondShort, short thirdShort) : base(firstShort, secondShort) { theNextDerivedMember = thirdShort; } public short showNextDerived() { return theNextDerivedMember; } }
file:///D|/1/final/BBL0048.html (39 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
static void Main() { nextDerived theReference = new nextDerived(1, 2, 3); Console.WriteLine("The value of theNextDerivedMember is {0}.\n\n", theReference.show()); Console.ReadKey(); }
}
// program_id theAbstract3.cs // written by don voils // date_written 10/3/2006 // Descriptioin This program shows how an abstract // class and method can be defined as // well as how to derive a class from a class // that is derived from an abstract class. // In this case, a second derived class // is derived from the first derived class. // In this program a reference to the abstract // base class is used to access methods of // each of the derived classes as if it was // a reference to the respecitive classes. // Without this base class being abstract, // this reference would have been forced to // access the base class' method which would // have been impossible because it is in turn // abstract. // using System; class theProgram { abstract public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } abstract public short show(); } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort; } override public short show() { return theDerivedMember; } } public class nextDerived : theDerived { private short theNextDerivedMember; public nextDerived(short firstShort, short secondShort, short thirdShort) : base(firstShort, secondShort) { theNextDerivedMember = thirdShort; } override public short show() { return theNextDerivedMember;
file:///D|/1/final/BBL0048.html (40 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
} } static void Main() { theDerived theDerivedReference = new theDerived(4, 5); theBase theBaseReference = theDerivedReference; Console.WriteLine("The value of theDerivedMember is {0}.\n", theBaseReference.show()); nextDerived theNextDerivedReference = new nextDerived(1, 2, 3); theBaseReference = theNextDerivedReference; Console.WriteLine("The value of theNextDerivedMember is {0}.\n\n", theBaseReference.show()); Console.ReadKey(); } }
// program_id theReference1.cs // written by don voils // date_written 10/3/2006 // Descriptioin The program shows how references to a base // class can be used to access the base class // part of an object of the derived class. // using System; class theProgram { public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } public short show_theBase() { return theBaseMember; } } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort; } public short show_theDerived() { return theDerivedMember; } } static void Main() { theBase theBaseReference; theDerived theDerivedReference = new theDerived(1, 2); theBaseReference = theDerivedReference; Console.WriteLine("The value of theBaseMember is {0}.\n", theBaseReference.show_theBase());
file:///D|/1/final/BBL0048.html (41 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// // The following line will not compile. Why? // // Console.WriteLine("The value of theDerivedMember is {0}.\n", // theBaseReference.show_theDerived()); Console.WriteLine("\n\n"); Console.ReadKey(); }
}
// program_id theReference2.cs // written by don voils // date_written 10/3/2006 // Descriptioin The program shows how references to a base // class can be used to access the base class // part of an object of a class that is derived from a // class that is derived from the base. // using System; class theProgram { public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } public short show_theBase() { return theBaseMember; } } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort; } public short show_theDerived() { return theDerivedMember; } } public class anotherDerived : theDerived { private short anotherDerivedMember; public anotherDerived(short firstShort, short secondShort, short thirdShort) : base(firstShort, secondShort) { anotherDerivedMember = thirdShort; } public short show_anotherDerived() { return anotherDerivedMember; } } static void Main() { theBase theBaseReference; theDerived theDerivedReference = new theDerived(1, 2);
file:///D|/1/final/BBL0048.html (42 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
theBaseReference = theDerivedReference; Console.WriteLine("The value of theBaseMember is {0}.\n", theBaseReference.show_theBase()); anotherDerived anotherDerivedReference = new anotherDerived(5, 6, 7); theBaseReference = anotherDerivedReference; Console.WriteLine("The value of theBaseMember is {0}.\n\n", theBaseReference.show_theBase()); Console.ReadKey(); }
}
// program_id theReference3.cs // written by don voils // date_written 10/3/2006 // Descriptioin The program shows that a reference to // a derived class may not be used to reference // a base class object. // using System; class theProgram { public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } public short show_theBase() { return theBaseMember; } } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort; } public short show_theDerived() { return theDerivedMember; } } static void Main() { theBase theBaseReference = new theBase(2); theDerived theDerivedReference; theDerivedReference = theBaseReference; Console.WriteLine("\n\n"); Console.ReadKey(); }
}
file:///D|/1/final/BBL0048.html (43 von 43) [01.12.2007 04:48:36]
Lecture 6: Operator Overloading
Lecture 6: Operator Overloading Definition of Operator Overloading Up to this point in C# the programmer could define operations on structure instances and class objects by using a function. For example: c = add(a,b);
where a, b and c are instances of one of the system data types, of a structure or of a class reference. However, this is using non-standard operators. C# as with C++ permits the programmer to use some of the standard operators in a more natural way using what is called: operator overloading. As with C++, the programmer should take care how these operators are defined and these defined operators should model the real world. The approach to this subject in C# is slightly different from the C++ approach. To define operator overloading on class objects requires that the operator: ●
is a system operator.
●
maintains the system order of precedence
●
can not change type: i.e. between unary and binary operators
●
is static and therefore may not use this in the definitions (also may not be virtual, override nor sealed).
●
must be a class method.
●
must have at least one of the parameters an object of the class
●
has in the operator's definition the keyword: operator
Notice the main differences between C# and C++ is that all of the operators in C# are public and static class methods. While this is true, operators may not be virtual, abstract, override or sealed. The permissible operators for overloading are:
Open table as spreadsheet OVERLOADABLE OPERATORS +
-
*
/
%
^
&
|
~
!
>=
=
<
>
<=
==
++
--
>>
<<
!=
Note: The operators: %=, +=, *=, -= and /= are missing from the above table because they are implicitly defined if the operators %, +, *, - and / are defined on the class. Note: While it is better to use the overloaded operators above when appropriate, there are additional needs for C# because this feature is not in the Common Language Specification. For example VB.NET might not support operator overloading and it is important to ensure that your company's classes support alternative methods that file:///D|/1/final/BBL0049.html (1 von 2) [01.12.2007 04:48:36]
Lecture 6: Operator Overloading
these other languages might call to create the same effect. To be compatible with the other languages in the .NET environment, functions like Add() should be included in the class' definition to match the traditional operator. In addition, it is also important to overload the method; Equal() which should be compatible with the operator==(). One of the reasons for overriding this method is that using the object method Equal() will only determine that the two class references contain the same addresses and not that the fields of two different objects are equal.
file:///D|/1/final/BBL0049.html (2 von 2) [01.12.2007 04:48:36]
Member Operators
Member Operators Unlike C++, C# operators on classes must be public static member operators with a header like the following: public static theOutPutType operator overloadedoperator(signature)
where the signature must contain one or more objects of the class (or other data types) and that the output is an instance of some data type: theOutPutType (which may be an object of the class but it could also be an instance of a system or some other data type.) Since these operators are static, they are not called by objects of the class. For example if *() is a member operator of a class: theClass, then the header of the member function could be: public static theClass operator*(theClass a, theClass b)
which has both of theClass objects a and b as parameters. Then a * b really means the call: theClass.operator*(a, b)
The above statement is what the compiler sees but if the programmer writes the above statement an error will occur.
file:///D|/1/final/BBL0050.html [01.12.2007 04:48:37]
Unary Operators
Unary Operators * There are several unary operators [ ] including:
++( ) // pre increment --( ) // pre decrement ( )++ // post increment ( )-- // post decrement
While these operators would not make sense on all classes, the first two of them would on the structure date. Where ++() would mean tomorrow and --() would mean yesterday. For example, the following statements: Date today = new Date(12,31,2006); ++today;
would make today have the date: 1/1/2007. (Recall that ++today really means Date.operator++(today).) For another example: Date today = new Date(1,1,2007); --today;
would make today become the date 12/31/2006. (Recall that --today really means: Date.operator--(today).) The above example showed how the pre increment and the pre decrement worked and the following would show how the post increment and the post decrement would work: Date today = new Date(1,1,2007); Date anotherDay = new Date(); anotherDay = today++;
would make today be: 1/2/2007 but anotherDay would be: 1/1/2007. Similarly Date today = new Date(1,1,2007); Date anotherDay = new Date(); anotherDay = today--;
would make today be: 12/31/2006 and anotherDay would be 1/1/2007. To see this example link to: unaryoperator1_struct.cs. (Notice that the default constructor is commented out because the default constructor for structures must be implicit.) Now the example above worked fine for structures. However these operators do not work for classes as they should. For example in the dates anotherDay and today seem to some times reference the same object. To see an example of these same operators on a class link to: unaryoperator1.cs file:///D|/1/final/BBL0051.html (1 von 2) [01.12.2007 04:48:37]
Unary Operators
The major difference between these two examples is the use of the word class instead of struct and the inclusion of an explicit default constructor for the class. [*]C#
only supports an explicit definition of the pre increment and the pre decrement but not an explicit definition of the post increment nor the post decrement. Once the pre increment and pre decrement are explicitly defined, the post are implicitly defined by the compiler.
file:///D|/1/final/BBL0051.html (2 von 2) [01.12.2007 04:48:37]
Binary Operators - Arithmetic
Binary Operators - Arithmetic There are times when it is desirable to extend the binary arithmetic operators: +, -, /, * and %. These operators as with all C# operators must be public static member functions. While it is desirable to have communitivity for some binary operators i.e. a+b=b+a
this does not occur by default. What must be done is to define the binary operator so that communitivity holds.
Binary Operators On the Complex Numbers Not every class lends itself to all operators. The class date discussed earlier works fine for the two unary operators but it has no need for all the binary operators. A class for which most of the binary operators would be meaningful would be the complex numbers. While it is possible for the programmer to write: c_complex = a_complex + b_complex;
which is then rewritten by the compiler and the actual code for this member function is: c_complex = complex.operator+(a_complex, b_complex);
It also possible to define the operations: -, * and /. Once these operations are defined then the operators: +=, -=, *= and /= are implicitly defined. For example: complex.cs. In this example after the operator + is defined, += is implicitly defined. You should also define: Add() to make it compatible with VB .NET. In addition to this class, it is also possible to define a structure to represent the complex numbers. To see this example, link to complex_struct.cs. The only difference is that the word struct is used instead of the word class and the default constructor is commented out since structures may not have an explicit default constructor.
Binary Operators On Dates While not all binary operators would be meaningful on the class Date, some would. For example: 10/21/2006 - 9/12/2006
would be meaningful to find the number of days between the two Dates. Notice that this should return an integer and not a Date. Other useful binary operations on the class Date would be the following: 1/21/2007 + 10
or
file:///D|/1/final/BBL0052.html (1 von 2) [01.12.2007 04:48:38]
Binary Operators - Arithmetic
1/21/2007 - 10
These two examples of binary operators are also possible on Date. However, from your mathematics classes, you have learned additional rules like the law of communitivity. For example, while 10/21/2006 + 10
is not equivalent to 10 + 10/21/2006
in terms of the definition of the operators, the output of these two statements should return the same value even though the input is different. That is, both of these two statements should yield a Date that is 10 days in the future. In C# these operators may be designed to achieve this desired result. Recall that in C++, to achieve this result required the use of friend functions. However, this type of function is not necessary in C# to enable the definitions of these two operators. For example: dateoptr.cs
file:///D|/1/final/BBL0052.html (2 von 2) [01.12.2007 04:48:38]
Binary Operators - Relational
Binary Operators - Relational In C# the binary relational operators: <, <=, ==, !=, > and >= may be extendible to user defined data types They would not be meaningful for the complex class but they would be meaningful as member operators on the Date class. For example: if(date1 <= 12/31/2006) cout << "The date was before the end of 2006" << endl;
Again notice that the output of each of these relational operations is not a class object but a variable of the bool data type. Thus the explicit arguments and the output are not required to be class objects and can be any data type. Note: The relational operators must be defined in pairs. That is: ●
if the operator: < is defined, then the operator: > must be defined and conversely.
●
if the operator: <= is defined, then the operator: >= must be defined and conversely.
●
if the operator: == is defined, then the operator: != must be defined and conversely.
See example: datereln.cs Note: When ever the operator == is defined, it is necessary to override the System.Object methods: Equals() and GetHashCode() to ensure that Equals() is based upon the equality of the fields and not the equality of the address of the object to which the references point. In the above example Equals() was overridden by using the following definition: public override bool Equals(object o) { bool resp; if(!(o is date)) resp = false; else resp = ((this == (date)o)? true:false); return resp; }
Next notice the following which overrides GetHashCode(): public override int GetHashCode() { return this.ToString().GetHashCode(); }
Notice that this method is not static. Therefore the this reference could be used in the body of the method.
file:///D|/1/final/BBL0053.html (1 von 2) [01.12.2007 04:48:38]
Binary Operators - Relational
file:///D|/1/final/BBL0053.html (2 von 2) [01.12.2007 04:48:38]
Binary Operators - Assignment
Binary Operators - Assignment The binary arithmetic assignment operators: +=, -=, /=, *= and %= are extendible as well. While they would not be meaningful on the date class, at least the first four would be meaningful on the complex class. These operators are possible on the complex class and permit statements like the following: a_complex += b_complex; a_complex -= b_complex; a_complex /= b_complex; a_complex *= b_complex;
What is different from C++, is that in C# no additional operators need to be defined. Each of these is based upon their respective operators: +, -, / and *. For example: cmlxasgn.cs.
file:///D|/1/final/BBL0054.html [01.12.2007 04:48:39]
Data Conversion
Data Conversion As we design classes, one of the operator types to consider is data conversion. When working with the system data types, it was necessary to convert from one data type to another. For example: an_int = (int) a_float; an_int = (int) a_char; a_float = (float) an_int;
The class date again is not a good candidate for a data conversion operator. However if the class ratio (i.e. numbers of the form a/b where a & b are integers and b is non-zero) was defined, it would be desirable to convert back and forth between the objects of ratio and the system data types. That is it would be desirable to have the following statements work: an_int = (int) a_ratio; a_float = (float) a_ratio; a_double (double) a_ratio;
and a_ratio = (ratio) an_int; a_ratio = (ratio) a_float; a_ratio = (ratio) a_double;
In order to make this work in C#, it is necessary to use the keyword: explicit and implicit in the following manner: public static implicit operator ratio(double a_double) { return new ratio((int)(a_double*1000000),1000000); } public static explicit operator double(ratio theRatio) { double temp = (double)((theRatio.top*1.0)/(theRatio.bottom*1.0)); return temp; }
Definitions similar to the above implicit and explicit type conversions, need to be done for each of the system data types. See conversion.cs. When you run this program, be sure to stay within the bounds of the respective data types. Also note how well the conversion takes place and how much data is lost in the conversions. If a program has a method: theMethod() that has as a parameter an object: theObject of a class: theClass, then the call could be like the following: theMethod(theObject). If in addition theClass has an implicit type conversion from theClass to anotherClass, then if anObject is an object of anotherClass the following could be called: theMethod(anObject)
file:///D|/1/final/BBL0055.html (1 von 2) [01.12.2007 04:48:40]
Data Conversion
There is an example of this concept in a later section of this lecture.
Open table as spreadsheet Implicit onverting from type
Implicity coverting to type
bool
no conversion possible
byte
ushort, short, uint, int, ulong, long, decimal, float or double
char
ushort, int, uint, long, ulong, decimal, float or double
decimal
no possible implicit conversions to other types
double
no possible implicity conversions to other types
float
double
int
long, decimal, float or double
long
decimal, float or double
sbyte
short, int, long, decimal, float or double
short
int, long, decimal, float or double
uint
ulong, long, decimal, float or double
ulong
decimal, float or double
ushort
uint, int, ulong, long, decimal, float or decimal
file:///D|/1/final/BBL0055.html (2 von 2) [01.12.2007 04:48:40]
Inclass Example - Stocks
Inclass Example - Stocks Specification: You work for Business Software Inc. They have been contracted by a client who is in the business of buying and selling stocks. You have been assigned to come up with a design for the class: theStock whose data members are to be: stockName, stockID and stockPrice. This class should be able to use the overloading of the relational operators with respect to the data member: stockName. Coding: The program stocks.cs demonstrates the overloading of the relational operators based upon the stockName data member. There is one thing to note. In C# the class string does not have the relational operators defined on which this program would be based in C++. Instead this program uses the string class method: Compare(leftString, rightString)
where leftString and rightString are strings and the method: Compare(,) returns: ●
a negative number if leftString is less than rightString
●
a positive number if leftString is greater than rightString
●
a 0 if leftString is equal to rightString
Note: This program overrides the Object method Equals() but does not override the Object method GetHashCode(). As a result, the compiler will provide a warning but it compiles and runs successfully. Recall that the Equals() method needs to be overridden so that the comparison will determine that the two stocks being compared are the same values and not just containing the same addresses.
file:///D|/1/final/BBL0056.html [01.12.2007 04:48:40]
Inclass Example - Rational Numbers
Inclass Example - Rational Numbers Specifications: Create the class: rationals with the data members: ●
top
●
bottom
and the class has for methods: ●
the default constructor that initializes bottom to 1
●
a get and a set for each data member
and that the class overloads each of the following operators: ●
●
●
the binary arithmetic operations with the result in reduced form: ❍
+ (addition)
❍
- (subtraction)
❍
* (multiplication)
❍
/ (division)
the relational operators ❍
<
❍
<=
❍
>
❍
>=
❍
==
the string operator ❍
ToString()
Create a program that inputs two objects of rationals and then tests whether each of the methods of the class works properly Design: The following is the UML chart for the class rationals. Notice that an additional class: object was added to the UML classes in order to implement the method: Equals(). This method needs to be overridden in order to truly check equality. If this was not done, then the object method Equals() would be called and it would only determine whether the two rationals references being compared contained the same addresses. In addition notice that the method GetHashCode() has been overridden as well. This is required when overloading Equal() or there will be a warning error.
file:///D|/1/final/BBL0057.html (1 von 2) [01.12.2007 04:48:41]
Inclass Example - Rational Numbers
Coding: The following files meet the specifications: ●
rationals.h
●
doRationals.cs
Next check the following example to observe that a double could be used instead of one of the rational operands because the class has both the implicit and the explicit conversion operators that permit the use of a double instead of one of the rationals. ●
rationals.h
●
doRationals2.cs
file:///D|/1/final/BBL0057.html (2 von 2) [01.12.2007 04:48:41]
Lecture 6 Examples
Lecture 6 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
cmlxasgn.cs
Illustrates the overloading of the binary operations +=, -=, *=, and /= to the complex numbers of the form a+bi. Notice that this does not require any additional operations other than the operators: +, -, * and /.
complex.cs
Illustrates the overloading of the binary operations +, -, *, and / to the complex numbers of the form a+bi.
complex_struct.cs
Illustrates the overloading of the binary operations +, -, *, and / to the complex numbers of the form a+bi on a structure. This program is similar to complex.cs except the default constructor is commented out.
conversion.cs
Illustrates the conversion of fractions to and from the system numeric data types.
dateoptr.cs
Demonstrates the use of difference operator on the date class that returns an integer.
datereln.cs
This program, among other things, demonstrates the use of the relational operators
doRationals.cs
Tests the features of the class rationals.
doRationals2.cs
Tests the features of the class rationals with respect to explicit and implicit type conversion when applied to the arithmetic and relational operators of the class rationals.
rationals.cs
Contains the definition of the class rationals.
stocks.cs
Illustrates the definition of the relational operators on the class theStock and the use of the Object method: Equals().
unaryoperator1.cs
Demonstrates the use of unary operators.
unaryoperator1_struct. cs
// // // // // // // // // // //
Demonstrates the use of unary operators on structures.
program_id cmlxasgn.cs author don voils date written 12/31/2006 program description This program illustrates the overloading of the binary operations +=, -=, *=, and /= to the complex numbers of the form a+bi. Notice that this does not require any additional operations other than the operators: +, -, * and /.
using System;
class complex { protected double real; file:///D|/1/final/BBL0058.html (1 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
protected double imaginary; public complex() { }
public complex(double r, double i) { real = r; imaginary=i; } double show_real() { return real; } double show_imaginary() { return imaginary; } public override string ToString() { string theNumber = " "+real+" + "+imaginary +"i"; return theNumber.ToString (); } public static complex operator+(complex b,complex a) { complex temp = new complex(); temp.real = b.real+a.real; temp.imaginary = b.imaginary+a.imaginary; return temp; } public static complex operator-(complex b,complex a) { complex temp = new complex(); temp.real = b.real-a.real; temp.imaginary = b.imaginary-a.imaginary; return temp; } public static complex operator*(complex b,complex a) { complex temp = new complex(); temp.real = b.real*a.real-b.imaginary*a.imaginary; temp.imaginary=b.real*a.imaginary+b.imaginary*a.real; return temp; } public static complex operator/(complex b,complex a) { complex temp = new complex();
file:///D|/1/final/BBL0058.html (2 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
temp = b * a.reciprical(); return temp; } public complex reciprical() { complex temp = new complex(); temp.real = real/(real*real + imaginary*imaginary); temp.imaginary = (-imaginary)/(real*real + imaginary*imaginary); return temp; } }
class theProgram { static void Main() { double real, imaginary; Console.WriteLine("Enter the first complex number"); Console.Write("\nWhat is the real value? "); real = Double.Parse(Console.ReadLine()); Console.Write("\nWhat is the imaginary value? "); imaginary = Double.Parse(Console.ReadLine()); complex complex_1 = new complex(real,imaginary); Console.WriteLine("\nEnter the second complex number."); Console.Write("\nWhat is the real value? "); real = Double.Parse(Console.ReadLine()); Console.Write("\nWhat is the imaginary value? "); imaginary = Double.Parse(Console.ReadLine()); Console.WriteLine("\n\n"); complex complex_2 = new complex(real,imaginary); complex complex_3 = new complex(); Console.WriteLine("The operation:"); Console.WriteLine("\n"+complex_1.ToString() + " += " + complex_2.ToString()+"\n"); complex_3 = complex_1; complex_3 += complex_2; Console.WriteLine("\nChanges {0} to {1}",complex_1,complex_3); Console.WriteLine("\n\n"); Console.WriteLine("The operation:"); Console.WriteLine("\n"+complex_1.ToString() + " -= " + complex_2.ToString()+"\n"); complex_3 = complex_1; complex_3 -= complex_2; Console.WriteLine("\nChanges {0} to {1}",complex_1,complex_3); Console.WriteLine("\n\n");
file:///D|/1/final/BBL0058.html (3 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
Console.WriteLine("The operation:"); Console.WriteLine("\n"+complex_1.ToString() + " *= " + complex_2.ToString()+"\n"); complex_3 = complex_1; complex_3 *= complex_2; Console.WriteLine("\nChanges {0} to {1}",complex_1,complex_3); Console.WriteLine("\n\n"); Console.WriteLine("The operation:"); Console.WriteLine("\n"+complex_1.ToString() + " /= " + complex_2.ToString()+"\n"); complex_3 = complex_1; complex_3 += complex_2; Console.WriteLine("\nChanges {0} to {1}",complex_1,complex_3); Console.WriteLine("\n\n"); } }
// // // // // // // // // // //
program_id author date written
complex.cs don voils 12/28/2006
program description This program illustrates the overloading of the binary operations +, -, *, and / to the complex numbers of the form a+bi on a class. This program is similar to comples_struct.cs except the default constructor is defined.
using System; class complex { private double real; private double imaginary; public complex() { } public complex(double theReal, double theImaginary) { real = theReal; imaginary = theImaginary; } public double Real { get { return real; } set { real = value; } } public double Imaginary
file:///D|/1/final/BBL0058.html (4 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
{ get { return imaginary; } set { imaginary = value; } } public override string ToString() { string theNumber = " " + Real + " + " + Imaginary + "i"; return theNumber.ToString(); } public static complex Add(complex theFirst, complex theSecond) { complex temp = new complex(); temp.Real = theFirst.Real + theSecond.Real; temp.Imaginary = theFirst.Imaginary + theSecond.Imaginary; return temp; } public static complex operator +(complex theFirst, complex theSecond) { complex temp = new complex(); temp.Real = theFirst.Real + theSecond.Real; temp.Imaginary = theFirst.Imaginary + theSecond.Imaginary; return temp; } public static complex operator -(complex theFirst, complex theSecond) { complex temp = new complex(); temp.Real = theFirst.Real - theSecond.Real; temp.Imaginary = theFirst.Imaginary - theSecond.Imaginary; return temp; } public static complex operator *(complex theFirst, complex theSecond) { complex temp = new complex(); temp.real = theFirst.Real * theSecond.Real - theFirst.Imaginary * theSecond.Imaginary; temp.imaginary = theFirst.Real * theSecond.Imaginary + theFirst.Imaginary * theSecond.Real; return temp; } public static complex operator /(complex theFirst, complex theSecond)
file:///D|/1/final/BBL0058.html (5 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
{ complex temp = new complex(); temp = theFirst * theSecond.reciprical(); return temp; } public complex reciprical() { complex temp = new complex(); temp.Real = Real / (Real * Real + Imaginary * Imaginary); temp.Imaginary = (-Imaginary) / (Real * Real + Imaginary * Imaginary); return temp; } }
class theProgram { static void Main() { double real, imaginary; Console.WriteLine("Enter the first complex number"); Console.Write("\nWhat is the real value? "); real = Double.Parse(Console.ReadLine()); Console.Write("\nWhat is the imaginary value? "); imaginary = Double.Parse(Console.ReadLine()); complex complex_1 = new complex(real, imaginary); Console.WriteLine("\n\n"); Console.WriteLine("Enter the second complex number."); Console.Write("\nWhat is the real value? "); real = Double.Parse(Console.ReadLine()); Console.Write("\nWhat is the imaginary value? "); imaginary = Double.Parse(Console.ReadLine()); complex complex_2 = new complex(real, imaginary); complex complex_3 = new complex(); Console.WriteLine("\n\n"); complex_3 = complex_1 + complex_2; Console.WriteLine(complex_3.ToString() + " = " + complex_1.ToString() + " + " + complex_2.ToString() + "\n"); complex_3 = complex_1 - complex_2; Console.WriteLine(complex_3.ToString() + " = " + complex_1.ToString() + " - "
file:///D|/1/final/BBL0058.html (6 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
+ complex_2.ToString() + "\n"); complex_3 = complex_1 * complex_2; Console.WriteLine(complex_3.ToString() + " = " + complex_1.ToString() + " * " + complex_2.ToString() + "\n"); complex_3 = complex_1 / complex_2; Console.WriteLine(complex_3.ToString() + " = " + complex_1.ToString() + " / " + complex_2.ToString() + "\n");
complex_3 = complex.Add(complex_1, complex_2); Console.WriteLine(complex_3.ToString() + " = Add(" + complex_1.ToString() + " , " + complex_2.ToString() + ")\n"); Console.WriteLine("\n\n"); } }
// // // // // // // // // // //
program_id author date written
complex_struct.cs don voils 12/28/2006
program description This program illustrates the overloading of the binary operations +, -, *, and / to the complex numbers of the form a+bi on a structure. This program is similar to comples.cs except the default constructor is commented out.
using System; struct complex { private double real; private double imaginary; //public complex() { } public complex(double theReal, double theImaginary) { real = theReal; imaginary = theImaginary; } public double Real { get { return real; } set {
file:///D|/1/final/BBL0058.html (7 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
real = value; } } public double Imaginary { get { return imaginary; } set { imaginary = value; } } public override string ToString() { string theNumber = " " + Real + " + " + Imaginary + "i"; return theNumber.ToString(); } public static complex Add(complex theFirst, complex theSecond) { complex temp = new complex(); temp.Real = theFirst.Real + theSecond.Real; temp.Imaginary = theFirst.Imaginary + theSecond.Imaginary; return temp; } public static complex operator +(complex theFirst, complex theSecond) { complex temp = new complex(); temp.Real = theFirst.Real + theSecond.Real; temp.Imaginary = theFirst.Imaginary + theSecond.Imaginary; return temp; } public static complex operator -(complex theFirst, complex theSecond) { complex temp = new complex(); temp.Real = theFirst.Real - theSecond.Real; temp.Imaginary = theFirst.Imaginary - theSecond.Imaginary; return temp; } public static complex operator *(complex theFirst, complex theSecond) { complex temp = new complex(); temp.real = theFirst.Real * theSecond.Real - theFirst.Imaginary * theSecond.Imaginary; temp.imaginary = theFirst.Real * theSecond.Imaginary + theFirst.Imaginary * theSecond.Real;
file:///D|/1/final/BBL0058.html (8 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
return temp; } public static complex operator /(complex theFirst, complex theSecond) { complex temp = new complex(); temp = theFirst * theSecond.reciprical(); return temp; } public complex reciprical() { complex temp = new complex(); temp.Real = Real / (Real * Real + Imaginary * Imaginary); temp.Imaginary = (-Imaginary) / (Real * Real + Imaginary * Imaginary); return temp; } }
class theProgram { static void Main() { double real, imaginary; Console.WriteLine("Enter the first complex number"); Console.Write("\nWhat is the real value? "); real = Double.Parse(Console.ReadLine()); Console.Write("\nWhat is the imaginary value? "); imaginary = Double.Parse(Console.ReadLine()); complex complex_1 = new complex(real, imaginary); Console.WriteLine("\n\n"); Console.WriteLine("Enter the second complex number."); Console.Write("\nWhat is the real value? "); real = Double.Parse(Console.ReadLine()); Console.Write("\nWhat is the imaginary value? "); imaginary = Double.Parse(Console.ReadLine()); complex complex_2 = new complex(real, imaginary); complex complex_3 = new complex(); Console.WriteLine("\n\n"); complex_3 = complex_1 + complex_2; Console.WriteLine(complex_3.ToString() + " = " + complex_1.ToString() + " + " + complex_2.ToString() + "\n");
file:///D|/1/final/BBL0058.html (9 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
complex_3 = complex_1 - complex_2; Console.WriteLine(complex_3.ToString() + " = " + complex_1.ToString() + " - " + complex_2.ToString() + "\n"); complex_3 = complex_1 * complex_2; Console.WriteLine(complex_3.ToString() + " = " + complex_1.ToString() + " * " + complex_2.ToString() + "\n"); complex_3 = complex_1 / complex_2; Console.WriteLine(complex_3.ToString() + " = " + complex_1.ToString() + " / " + complex_2.ToString() + "\n");
complex_3 = complex.Add(complex_1, complex_2); Console.WriteLine(complex_3.ToString() + " = Add(" + complex_1.ToString() + " , " + complex_2.ToString() + ")\n"); Console.WriteLine("\n\n"); } }
// // // // // // // //
program_id conversion.cs author don voils date written 12/28/2006 program description This program illustrates the conversion of fractions to and from the system numeric data types.
using System;
class ratio { private int top; private int bottom; public ratio() { } public ratio(int n, int d) { top=n; bottom=d; } public int gettop() { return top;
file:///D|/1/final/BBL0058.html (10 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
} public int getbottom() { return bottom; } public void reduced() { int GCD = gcd(top,bottom); top = (top/GCD); bottom = (bottom/GCD); } public static implicit operator ratio(double a_double) { return new ratio((int)(a_double*1000000),1000000); } public static explicit operator double(ratio theRatio) { double temp = (double)((theRatio.top*1.0)/(theRatio.bottom*1.0)); return temp; } public static explicit operator float(ratio theRatio) { float temp = (float)((theRatio.top*1.0)/(theRatio.bottom*1.0)); return temp; } public static implicit operator ratio(float a_float) { return new ratio((int)(a_float*1000000.0f),1000000); } public static explicit operator int(ratio theRatio) { return (int)((theRatio.top*1.0)/(theRatio.bottom*1.0)); } public override string ToString() { string theString =""+top+"/"+bottom+""; return theString; } public static implicit operator ratio(int an_int) { return new ratio(an_int,1); } int gcd(int a, int b) { int c, d; d = (a
file:///D|/1/final/BBL0058.html (11 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
while(d!=0) { int e,f; e = c/d; f = c - d*e; c = d; d = f; } return c; } }
class theProgram { static void Main() { int top, bottom; Console.WriteLine("Enter the rational number"); Console.Write("\nWhat is the numerator? "); top = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the denominator? "); bottom =Int32.Parse(Console.ReadLine()); Console.WriteLine("\n"); ratio theRational = new ratio(top,bottom); Console.WriteLine("The rational number {0} is equivalent to the integer {1}\n", theRational,(int)theRational); Console.WriteLine("The rational number {0} is equivalent to the float {1}\n", theRational,(float)theRational); Console.WriteLine("The rational number {0} is equivalent to the double {1}\n", theRational,(double)theRational); Console.WriteLine("\n\n"); Console.Write("What is the integer? "); int theInteger = Int32.Parse(Console.ReadLine()); theRational = (ratio)theInteger; Console.WriteLine("The integer {0} is equivalent to the rational number {1}\n", theInteger,theRational); Console.Write("What is the float? "); float theFloat = float.Parse(Console.ReadLine()); theRational = (ratio)theFloat; Console.WriteLine("The float {0} is equivalent to the rational number {1}\n", theFloat,theRational); Console.Write("What is the double? "); double theDouble = Double.Parse(Console.ReadLine()); theRational = (ratio)theDouble; Console.WriteLine("The double {0} is equivalent to the rational number {1}\n", theDouble,theRational); Console.WriteLine("\n\n"); } }
file:///D|/1/final/BBL0058.html (12 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
// program_id dateoptr.cs // written_by don voils // date_written 12/28/2006 // description This program demonstrates the use of difference // operator on the date class that returns an integer // using System; public class Date { private int month; private int day; private int year; public int Month { get { return month; } set { month = value; } } public int Day { get { return day; } set { day = value; } } public int Year { get { return year; } set { year = value; } } public static int lastDay(int theMonth, int theYear) { int theLastDay; // Arrays are discussed in Lecture 8 // int[] daysInMonth = new int[13] { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (theMonth != 2)
file:///D|/1/final/BBL0058.html (13 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
theLastDay = daysInMonth[theMonth]; else if (leapYear(theYear)) theLastDay = 29; else theLastDay = daysInMonth[theMonth]; return theLastDay; } public override string ToString() { return "" + Month + "/" + Day + "/" + Year + " "; } public void getDate() { do { Console.Write("What is the month? "); Month = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the day? "); Day = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the year? "); Year = Int32.Parse(Console.ReadLine()); } while (incorrectDate(Month, Day, Year)); } public void setDate(int theMonth, int theDay, int theYear) { Month = theMonth; Day = theDay; Year = theYear; } public static bool leapYear(int theYear) { bool leapTest; if (((theYear % 4 == 0) && (theYear % 100 != 0)) || (theYear % 400 == 0)) leapTest = true; else leapTest = false; return leapTest; } // Recall from the examples on increment and decrement that this operation // does not work correctly on classes. However if this example // was changed to a structure instead, then the following two // definitions could be uncommented. // //public static Date operator ++(Date temp) //{ // if (temp.Day < lastDay(temp.Month, temp.Year)) // temp.Day = temp.Day + 1; // else // { // if (temp.Month < 12) // { // temp.Month = temp.Month + 1;
file:///D|/1/final/BBL0058.html (14 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
// temp.Day = 1; // } // else // { // temp.Month = 1; // temp.Day = 1; // temp.Year = temp.Year + 1; // } // } // return temp; //} //public static Date operator --(Date temp) //{ // if (temp.Day != 1) // { // temp.Day -= 1; // } // else // { // if (temp.Month != 1) // { // temp.Month -= 1; // temp.Day = lastDay(temp.Month, temp.Year); // } // else // { // temp.Month = 12; // temp.Day = 31; // temp.Year -= 1; // } // } // return temp; //} public static int daysSince(int theMonth, int theDay, int theYear) { int number = 1461 * f(theMonth, theYear) / 4 + 153 * g(theMonth) / 5 + theDay; return (number); }
public static int f(int theMonth, int theYear) { int number = (theMonth <= 2) ? theYear - 1 : theYear; return (number); } public static int g(int theMonth) { int number = (theMonth <= 2) ? theMonth + 13 : theMonth + 1; return (number); } public static bool incorrectDate(int theMonth, int theDay, int theYear) {
file:///D|/1/final/BBL0058.html (15 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
bool notCorrect; if ((theMonth >= 1) && (theMonth <= 12) && (theDay >= 1) && (theDay <= lastDay(theMonth,theYear))) notCorrect = false; else notCorrect = true; return notCorrect; } public static int operator -(Date aDate, Date bDate) { int days; days = daysSince(aDate.Month, aDate.Day, aDate.Year) - daysSince(bDate.Month, bDate.Day, bDate.Year); return days; } public static Date operator +(int numberDays, Date theDate) { Date nextDay = new Date(); nextDay.setDate(theDate.Month, theDate.Day, theDate.Year); for (int index = 1; index <= numberDays; ++index) { if (nextDay.Day < lastDay(nextDay.Month, nextDay.Year)) { nextDay.Day += 1; } else { if (nextDay.Month < 12) { nextDay.Month += 1; nextDay.Day = 1; } else { nextDay.Month = 1; nextDay.Day = 1; nextDay.Year += 1; } } } return nextDay; } public static Date operator +(Date theDate, int numberDays) { Date nextDay = new Date(); nextDay.setDate(theDate.Month, theDate.Day, theDate.Year); for (int index = 1; index <= numberDays; ++index) { if (nextDay.Day < lastDay(nextDay.Month, nextDay.Year))
file:///D|/1/final/BBL0058.html (16 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
{ nextDay.Day += 1; } else { if (nextDay.Month < 12) { nextDay.Month += 1; nextDay.Day = 1; } else { nextDay.Month = 1; nextDay.Day = 1; nextDay.Year += 1; } } } return nextDay; } public static Date operator -(Date theDate, int numberDays) { Date nextDay = new Date(); nextDay.setDate(theDate.Month, theDate.day, theDate.Year); for (int index = 1; index <= numberDays; ++index) { if (nextDay.Day != 1) { nextDay.Day -= 1; } else { if (nextDay.Month != 1) { nextDay.Month -= 1; nextDay.Day = lastDay(nextDay.Month, nextDay.Year); } else { nextDay.Month = 12; nextDay.Day = 31; nextDay.Year -= 1; } } } return nextDay; } } class theProgram { static void Main() { Date theDay = new Date(); Date theOther = new Date();
file:///D|/1/final/BBL0058.html (17 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
int theNumber; Console.WriteLine("Enter the first date:\n"); theDay.getDate(); Console.WriteLine("\n\nEnter the Second date:\n"); theOther.getDate(); theNumber = theDay - theOther; Console.WriteLine("\n\n{0} = {1} - {2}", theNumber, theDay, theOther); Console.Write("\n\nHow many days in the future do you want from the first date? "); theNumber = Int32.Parse(Console.ReadLine()); theOther = theNumber + theDay; Console.WriteLine("\n\n{0} = {1} + {2}", theOther, theNumber, theDay); Console.Write("\n\nHow many days in the past do you want from the first date? "); theNumber = Int32.Parse(Console.ReadLine()); theOther = theDay - theNumber; Console.WriteLine("\n\n{0} = {1} - {2}", theOther, theDay, theNumber); Console.Write("\n\nHow many days in the future do you want from the first date? "); theNumber = Int32.Parse(Console.ReadLine()); theOther = theDay + theNumber; Console.WriteLine("\n\n{0} = {1} + {2}", theOther, theDay, theNumber); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id datereln.cs // written_by don voils // date_written 12/31/2006 // description This program, among other things, demonstrates the use of // the relational operators // using System; public class Date { private int month; private int day; private int year; public int Month { get {
file:///D|/1/final/BBL0058.html (18 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
return month; } set { month = value; } } public int Day { get { return day; } set { day = value; } } public int Year { get { return year; } set { year = value; } } public static int lastDay(int theMonth, int theYear) { int lastDay; // Arrays are discussed in Lecture 8 // int[] daysInMonth = new int[13] {0,31,28,31,30,31, 30,31,31,30,31,30,31}; if (theMonth != 2) lastDay = daysInMonth[theMonth]; else if (leapYear(theYear)) lastDay = 29; else lastDay = daysInMonth[theMonth]; return lastDay; } public override string ToString() { return "" + Month + "/" + Day + "/" + Year + " "; } public void getDate() { do {
file:///D|/1/final/BBL0058.html (19 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
Console.Write("What is the month? "); Month = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the day? "); Day = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the year? "); Year = Int32.Parse(Console.ReadLine()); } while (incorrectDate(Month, Day, Year)); } public void setDate(int theMonth, int theDay, int theYear) { Month = theMonth; Day = theDay; Year = theYear; } public static bool leapYear(int theYer) { bool leapTest; if (((theYer % 4 == 0) && (theYer % 100 != 0)) || (theYer % 400 == 0)) leapTest = true; else leapTest = false; return leapTest; } public static int daysSince(int theMonth, int theDay, int theYear) { int number = 1461 * f(theMonth, theYear) / 4 + 153 * g(theMonth) / 5 + theDay; return (number); }
public static int f(int theMonth, int theYear) { int number = (theMonth <= 2) ? theYear - 1 : theYear; return (number); } public static int g(int theMonth) { int number = (theMonth <= 2) ? theMonth + 13 : theMonth + 1; return (number); } public static bool incorrectDate(int theMonth, int theDay, int theYear) { bool notCorrect; if ((theMonth >= 1) && (theMonth <= 12) && (theDay >= 1) && (theDay <= lastDay(theMonth, theYear))) notCorrect = false; else notCorrect = true; return notCorrect; }
file:///D|/1/final/BBL0058.html (20 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
public static int operator -(Date aDate, Date bDate) { int days; days = daysSince(aDate.Month, aDate.Day, aDate.Year) - daysSince(bDate.Month, bDate.Day, bDate.Year); return days; } public static Date operator +(int numberDays, Date theDate) { Date nextDay = new Date(); nextDay.setDate(theDate.Month, theDate.Day, theDate.Year); for (int index = 1; index <= numberDays; ++index) { if (nextDay.Day < lastDay(nextDay.Month, nextDay.Year)) { nextDay.Day += 1; } else { if (nextDay.Month < 12) { nextDay.Month += 1; nextDay.Day = 1; } else { nextDay.Month = 1; nextDay.Day = 1; nextDay.Year += 1; } } } return nextDay; } public static Date operator +(Date theDate, int numberDays) { Date nextDay = new Date(); nextDay.setDate(theDate.Month, theDate.day, theDate.Year); for (int index = 1; index <= numberDays; ++index) { if (nextDay.Day < lastDay(nextDay.Month, nextDay.Year)) { nextDay.Day += 1; } else { if (nextDay.Month < 12) { nextDay.Month += 1; nextDay.Day = 1; }
file:///D|/1/final/BBL0058.html (21 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
else { nextDay.Month = 1; nextDay.Day = 1; nextDay.Year += 1; } } } return nextDay; } public static Date operator -(Date theDate, int numberDays) { Date nextDay = new Date(); nextDay.setDate(theDate.Month, theDate.Day, theDate.Year); for (int index = 1; index <= numberDays; ++index) { if (nextDay.Day != 1) { nextDay.Day -= 1; } else { if (nextDay.Month != 1) { nextDay.Month -= 1; nextDay.day = lastDay(nextDay.Month, nextDay.Year); } else { nextDay.Month = 12; nextDay.Day = 31; nextDay.Year -= 1; } } } return nextDay; } public static bool operator >(Date lDate, Date rDate) { bool resp; int leftDate, rightDate; leftDate = daysSince(lDate.Month, lDate.Day, lDate.Year); rightDate = daysSince(rDate.Month, rDate.Day, rDate.Year); resp = (leftDate > rightDate) ? true : false; return resp; } public static bool operator <(Date lDate, Date rDate) { bool resp;
file:///D|/1/final/BBL0058.html (22 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
int leftDate, rightDate; leftDate = daysSince(lDate.Month, lDate.Day, lDate.Year); rightDate = daysSince(rDate.Month, rDate.Day, rDate.Year); resp = (leftDate < rightDate) ? true : false; return resp; } public static bool operator >=(Date lDate, Date rDate) { bool resp; int leftDate, rightDate; leftDate = daysSince(lDate.Month, lDate.Day, lDate.Year); rightDate = daysSince(rDate.Month, rDate.Day, rDate.Year); resp = (leftDate >= rightDate) ? true : false; return resp; } public override bool Equals(object o) { bool resp; if (!(o is Date)) resp = false; else resp = ((this == (Date)o) ? true : false); return resp; } public override int GetHashCode() { return this.ToString().GetHashCode(); } public static bool operator ==(Date lDate, Date rDate) { bool resp; int leftDate, rightDate; leftDate = daysSince(lDate.Month, lDate.Day, lDate.Year); rightDate = daysSince(rDate.Month, rDate.Day, rDate.Year); resp = (leftDate == rightDate) ? true : false; return resp; }
file:///D|/1/final/BBL0058.html (23 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
public static bool operator <=(Date lDate, Date rDate) { bool resp; int leftDate, rightDate; leftDate = daysSince(lDate.Month, lDate.Day, lDate.Year); rightDate = daysSince(rDate.Month, rDate.Day, rDate.Year); resp = (leftDate <= rightDate) ? true : false; return resp; } public static bool operator !=(Date lDate, Date rDate) { bool resp; int leftDate, rightDate; leftDate = daysSince(lDate.Month, lDate.Day, lDate.Year); rightDate = daysSince(rDate.Month, rDate.Day, rDate.Year); resp = (leftDate != rightDate) ? true : false; return resp; } }
class theProgram { static void Main() { Date theDay = new Date(); Date theOther = new Date(); Console.WriteLine("Enter the first date:\n"); theDay.getDate(); Console.WriteLine("\n\nEnter the Second date:\n"); theOther.getDate(); if (theDay < theOther) { Console.WriteLine("\n\n{0} < {1}", theDay, theOther); } if (theDay <= theOther) { Console.WriteLine("\n\n{0} <= {1}", theDay, theOther); } if (theDay == theOther)
file:///D|/1/final/BBL0058.html (24 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
{ Console.WriteLine("\n\n{0} == {1}", theDay, theOther); } if (theDay != theOther) { Console.WriteLine("\n\n{0} != {1}", theDay, theOther); } if (theDay > theOther) { Console.WriteLine("\n\n{0} > {1}", theDay, theOther); } if (theDay >= theOther) { Console.WriteLine("\n\n{0} >= {1}", theDay, theOther); } if (Equals(theDay, theOther)) { Console.WriteLine("\n\n{0} equals {1}", theDay, theOther); } else { Console.WriteLine("\n\n{0} does not equal {1}", theDay, theOther); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id doRationals2.cs // written_by don voils // date_writte 12/31/2006 // description This program tests the features of the class // rationals with respect to explicit and implicit // type conversion when applied to the arithmetic // and relational operators of the class rationals. // using System; using Rationals; namespace doRationals2 { class theProgram { static void Main(string[] args) { rationals theFirst = new rationals(); rationals theSecond = new rationals(); double theDouble; long theTop = new long(); long theBottom = new long(); bool notCorrect;
file:///D|/1/final/BBL0058.html (25 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
do { Console.Write("Enter the first rational number "); Console.Write("\n\nWhat is the numerator of the first rational number? "); theTop = long.Parse(Console.ReadLine()); Console.Write("\nWhat is the denominator of the first rational number? "); theBottom = long.Parse(Console.ReadLine()); if (theBottom == 0) { notCorrect = true; Console.WriteLine("\nThe bottom must be non-zero!!!\n"); } else { theFirst.setTop(theTop); theFirst.setBottom(theBottom); notCorrect = false; } } while (notCorrect); Console.Write("\nEnter the double. "); theDouble = double.Parse(Console.ReadLine()); Console.WriteLine("\n\n"); theSecond = theFirst + theDouble; Console.WriteLine("\n{0} = {1} + {2} \n", theSecond, theFirst, theDouble); theSecond = theFirst - theDouble; Console.WriteLine("\n{0} = {1} - {2} \n", theSecond, theFirst,theDouble); theSecond = theFirst * theDouble; Console.WriteLine("\n{0} = {1} * {2} \n", theSecond, theFirst, theDouble); theSecond = theFirst / theDouble; Console.WriteLine("\n{0} = {1} / {2} \n", theSecond, theFirst, theDouble); if (theFirst < theDouble) Console.WriteLine("\n{0} is less than {1}\n", theFirst, theDouble); else Console.WriteLine("\n{0} is greater than or equal to {1}\n", theFirst, theDouble); if (theFirst <= theDouble) Console.WriteLine("\n{0} is less than or equal to {1}\n", theFirst, theDouble); else Console.WriteLine("\n{0} is greater than {1}\n", theFirst, theDouble); if (theFirst > theDouble) Console.WriteLine("\n{0} is greater than {1}\n", theFirst, theDouble); else Console.WriteLine("\n{0} is less than or equal to {1}\n", theFirst, theDouble); ; if (theFirst >= theDouble) Console.WriteLine("\n{0} is greater than or equal to {1}\n", theFirst, theDouble); else Console.WriteLine("\n{0} is less than {1}\n", theFirst, theDouble);
file:///D|/1/final/BBL0058.html (26 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
if (theFirst == theDouble) Console.WriteLine("\n{0} is equal to {1}\n", theFirst, theDouble); else Console.WriteLine("\n{0} is not equal to {1}\n", theFirst, theDouble); if (Equals(theFirst, theDouble)) Console.WriteLine("\n{0} is equal to {1}\n", theFirst, theDouble); else Console.WriteLine("\n{0} is not equal to {1}\n\n", theFirst, theDouble); Console.ReadLine(); } } }
// program_id doRationals.cs // written_by don voils // date_writte 12/31/2006 // description This program tests the features of the class // rationals. //
using System; using Rationals; namespace doRationals { class theProgram { static void Main(string[] args) { rationals theFirst = new rationals(); rationals theSecond = new rationals(); rationals theThird = new rationals(); long theTop = new long(); long theBottom = new long(); bool notCorrect; do { Console.Write("Enter the first rational number "); Console.Write("\n\nWhat is the numerator of the first rational number? "); theTop = long.Parse(Console.ReadLine()); Console.Write("\nWhat is the denominator of the first rational number? "); theBottom = long.Parse(Console.ReadLine()); if(theBottom == 0) { notCorrect = true; Console.WriteLine("\nThe bottom must be non-zero!!!\n"); } else { theFirst.setTop(theTop);
file:///D|/1/final/BBL0058.html (27 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
theFirst.setBottom(theBottom); notCorrect = false; } }while(notCorrect); do { Console.Write("\nEnter the second rational number "); Console.Write("\n\nWhat is the numerator of the second rational number? "); theTop = long.Parse(Console.ReadLine()); Console.Write("\nWhat is the denominator of the second rational number? "); theBottom = long.Parse(Console.ReadLine()); if(theBottom == 0) { notCorrect = true; Console.WriteLine("\nThe bottom must be non-zero!!!\n"); } else { theSecond.setTop(theTop); theSecond.setBottom(theBottom); notCorrect = false; } }while(notCorrect); Console.WriteLine("\n\n"); theThird = theFirst + theSecond; Console.WriteLine("\n{0} = {1} + {2} \n",theThird,theFirst,theSecond); theThird = theFirst - theSecond; Console.WriteLine("\n{0} = {1} - {2} \n",theThird,theFirst,theSecond); theThird = theFirst * theSecond; Console.WriteLine("\n{0} = {1} * {2} \n",theThird,theFirst,theSecond); theThird = theFirst / theSecond; Console.WriteLine("\n{0} = {1} / {2} \n",theThird,theFirst,theSecond); if(theFirst < theSecond) Console.WriteLine("\n{0} is less than {1}\n",theFirst,theSecond); else Console.WriteLine("\n{0} is greater than or equal to {1}\n",theFirst,theSecond); if(theFirst <= theSecond) Console.WriteLine("\n{0} is less than or equal to {1}\n",theFirst,theSecond); else Console.WriteLine("\n{0} is greater than {1}\n",theFirst,theSecond); if(theFirst > theSecond) Console.WriteLine("\n{0} is greater than {1}\n",theFirst,theSecond); else Console.WriteLine("\n{0} is less than or equal to {1}\n",theFirst,theSecond); ; if(theFirst >= theSecond) Console.WriteLine("\n{0} is greater than or equal to {1}\n",theFirst,theSecond); else Console.WriteLine("\n{0} is less than {1}\n",theFirst,theSecond);
file:///D|/1/final/BBL0058.html (28 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
if(theFirst == theSecond) Console.WriteLine("\n{0} is equal to {1}\n",theFirst,theSecond); else Console.WriteLine("\n{0} is not equal to {1}\n",theFirst,theSecond); if(Equals(theFirst,theSecond)) Console.WriteLine("\n{0} is equal to {1}\n",theFirst,theSecond); else Console.WriteLine("\n{0} is not equal to {1}\n\n",theFirst,theSecond); Console.ReadLine(); } } }
This is my Stock 5344 534.34 This is your Stock 5212 414.34
// program_id rationals.cs // written_by don voils // date_written 12/31/2006 // // description This file contains the definition of the // class rationals. // namespace Rationals { class rationals { private long top; private long bottom; public rationals() { top = 0; bottom = 1; } public rationals(long theTop,long theBottom) { top = theTop; bottom = theBottom; } public void setTop(long theTop) { rationals temp = new rationals(theTop,bottom); temp.reduced(); top = temp.top; bottom = temp.bottom;
file:///D|/1/final/BBL0058.html (29 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
} public void setBottom(long theBottom) { rationals temp = new rationals(top,theBottom); temp.reduced(); top = temp.top; bottom = temp.bottom; } public long getTop() { return top; } public long getBottom() { return bottom; } public void reduced() { long GCD = gcd(top,bottom); top = (long)((top*1.0)/(GCD*1.0)); bottom = (long)((bottom*1.0)/(GCD*1.0)); if(bottom < 0) { bottom *=-1; top *=-1; } } public static long gcd(long a, long b) { long c, d; d = (a
file:///D|/1/final/BBL0058.html (30 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
} public static rationals operator -(rationals theLeft,rationals theRight) { rationals temp = new rationals(theLeft.top*theRight.bottom-theLeft.bottom*theRight.top, theLeft.bottom*theRight.bottom); temp.reduced(); if(temp.bottom < 0) { temp.bottom = -temp.bottom; temp.top = -temp.top; } return temp; } public static rationals operator *(rationals theLeft,rationals theRight) { rationals temp = new rationals(theLeft.top*theRight.top, theLeft.bottom*theRight.bottom); temp.reduced(); if(temp.bottom < 0) { temp.bottom = -temp.bottom; temp.top = -temp.top; } return temp; } public static rationals operator /(rationals theLeft,rationals theRight) { rationals temp = new rationals(theLeft.top*theRight.bottom, theLeft.bottom*theRight.top); temp.reduced(); return temp; } public static bool operator <(rationals theLeft,rationals theRight) { return (theLeft.top * theRight.bottom < theRight.top * theLeft.bottom); } public static bool operator <=(rationals theLeft,rationals theRight) { return (theLeft.top * theRight.bottom <= theRight.top * theLeft.bottom); } public static bool operator >(rationals theLeft,rationals theRight) { return (theLeft.top * theRight.bottom > theRight.top * theLeft.bottom); } public static bool operator >=(rationals theLeft,rationals theRight) { return (theLeft.top * theRight.bottom >= theRight.top * theLeft.bottom); } public static bool operator ==(rationals theLeft,rationals theRight) {
file:///D|/1/final/BBL0058.html (31 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
return (theLeft.top * theRight.bottom == theRight.top * theLeft.bottom); } public static bool operator !=(rationals theLeft,rationals theRight) { return (theLeft.top * theRight.bottom != theRight.top * theLeft.bottom); } public override bool Equals(object o) { bool resp; if(!(o is rationals)) resp = false; else resp = ((this == (rationals)o)? true:false); return resp; } public override int GetHashCode() { return this.ToString().GetHashCode(); } public override string ToString() { return ""+ top + "/" + bottom+""; } public static implicit operator rationals(double a_double) { return new rationals((int)(a_double * 1000000), 1000000); } public static explicit operator double(rationals theRatio) { double temp = (double)((theRatio.top * 1.0) / (theRatio.bottom * 1.0)); return temp; } } }
This is my Stock 5344 534.34 This is your Stock 5212 414.34
// // // // // // //
program_id author date written
stocks.cs don voils 12/28/2006
program description This program illustrates the definition of the relational operators on the class theStock
file:///D|/1/final/BBL0058.html (32 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
// // //
and the use of the Object method: Equals().
using System;
class theStock { private string stockName; private string stockID; private decimal stockPrice; public void setstockName(string theName) { stockName=theName; } public void setstockID(string theID) { stockID=theID; } public void setstockPrice(decimal thePrice) { stockPrice=thePrice; } public string getstockName() { return stockName; } public string getstockID() { return stockID; } public decimal getstockPrice() { return stockPrice; } public override string ToString() { return "Stock Name: "+stockName + "\nStock ID: " +stockID + "\nStock Price: $" + stockPrice+" "; } public static bool operator <(theStock myStock,theStock yourStock) { bool temp = new bool(); int theValue = new int(); theValue = string.Compare(myStock.stockName,yourStock.stockName); if(theValue < 0) temp = true; else temp = false; return temp; }
file:///D|/1/final/BBL0058.html (33 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
public static bool operator >=(theStock myStock,theStock yourStock) { bool temp = new bool(); int theValue = new int(); theValue = string.Compare(myStock.stockName,yourStock.stockName); if(theValue >= 0) temp = true; else temp = false; return temp; } public static bool operator >(theStock myStock,theStock yourStock) { bool temp = new bool(); int theValue = new int(); theValue = string.Compare(myStock.stockName,yourStock.stockName); if(theValue > 0) temp = true; else if(theValue <= 0) temp = false; return temp; } public static bool operator <=(theStock myStock,theStock yourStock) { bool temp = new bool(); int theValue = new int(); theValue = string.Compare(myStock.stockName,yourStock.stockName); if(theValue <= 0) temp = true; else temp = false; return temp; } public static bool operator ==(theStock myStock,theStock yourStock) { bool temp = new bool(); int theValue = new int(); theValue = string.Compare(myStock.stockName,yourStock.stockName); if(theValue == 0) temp = true; else temp = false;
file:///D|/1/final/BBL0058.html (34 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
return temp; } public static bool operator !=(theStock myStock,theStock yourStock) { bool temp = new bool(); int theValue = new int(); theValue = string.Compare(myStock.stockName,yourStock.stockName); if(theValue != 0) temp = true; else temp = false; return temp; } public override bool Equals(object o) { bool resp; if(!(o is theStock)) resp = false; else if(string.Compare(this.stockName,(string)o)==0) resp = true; else resp = false; return resp; } }
class theProgram { static void Main() { theStock firstStock = new theStock(); theStock secondStock = new theStock(); Console.WriteLine("Enter the first stock: "); Console.Write("\nWhat is the stock name? "); firstStock.setstockName(Console.ReadLine()); Console.Write("\nWhat is the stock ID? "); firstStock.setstockID(Console.ReadLine()); Console.Write("\nWhat is the stock price? "); firstStock.setstockPrice(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\n\n"); Console.WriteLine("Enter the second stock: "); Console.Write("\nWhat is the stock name? "); secondStock.setstockName(Console.ReadLine()); Console.Write("\nWhat is the stock ID? "); secondStock.setstockID(Console.ReadLine()); Console.Write("\nWhat is the stock price? "); secondStock.setstockPrice(Decimal.Parse(Console.ReadLine()));
file:///D|/1/final/BBL0058.html (35 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
Console.WriteLine("\n\n"); if(firstStock < secondStock) Console.WriteLine("{0}\n\n is less than \n\n{1}\n\n", firstStock,secondStock); if(firstStock <= secondStock) Console.WriteLine("{0}\n\n is less than or equal to\n\n{1}\n\n", firstStock,secondStock); if(firstStock == secondStock) Console.WriteLine("{0}\n\n is equal to\n\n{1}\n\n", firstStock,secondStock); if(firstStock > secondStock) Console.WriteLine("{0}\n\n is greater than\n\n{1}\n\n", firstStock,secondStock); if(firstStock >= secondStock) Console.WriteLine("{0}\n\n is greater than or equal to\n\n{1}\n\n", firstStock,secondStock); Console.WriteLine("\n\n"); } }
// program_id unaryoperator1.cs // written_by don voils // date_written 12/28/2006 // description This program demonstrates the use of unary // operators on a class. This program is the // same as unaryoperator1_struct.cs except // that the keyword class is used instead of // struct and this class contains and explicit // default constructor. // using System; public class Date { private int month; private int day; private int year; public Date() { } public Date(int aMonth, int aDay, int aYear) { month = aMonth; day = aDay; year = aYear; } public int Month { get { return month; } set { month = value;
file:///D|/1/final/BBL0058.html (36 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
} } public int Day { get { return day; } set { day = value; } } public int Year { get { return year; } set { year = value; } } public static int lastDay(int aMonth, int aYear) { int theLastDay; // Arrays are discussed in Lecture 8 // int[] daysInMonth = new int[13] { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (aMonth != 2) theLastDay = daysInMonth[aMonth]; else if (leapYear(aYear)) theLastDay = 29; else theLastDay = daysInMonth[aMonth]; return theLastDay; } public void getDate() { do { Console.Write("What is the month? "); Month = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the day? "); Day = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the year? "); Year = Int32.Parse(Console.ReadLine()); if (Year < 20) Year += 2000; else if(Year < 100) Year += 1900;
file:///D|/1/final/BBL0058.html (37 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
} while (incorrectDate(Month, Day, Year)); } public static bool leapYear(int aYear) { bool leapTest; if (((aYear % 4 == 0) && (aYear % 100 != 0)) || (aYear % 400 == 0)) leapTest = true; else leapTest = false; return leapTest; } public static Date operator ++(Date theDay) { if (theDay.Day < lastDay(theDay.Month, theDay.Year)) theDay.Day = theDay.Day + 1; else { if (theDay.Month < 12) { theDay.Month = theDay.Month + 1; theDay.Day = 1; } else { theDay.Month = 1; theDay.Day = 1; theDay.Year = theDay.Year + 1; } } return new Date(theDay.Month, theDay.Day, theDay.Year); } public static Date operator --(Date theDay) { if (theDay.Day != 1) { theDay.Day -= 1; } else { if (theDay.Month != 1) { theDay.Month -= 1; theDay.Day = lastDay(theDay.Month, theDay.Year); } else { theDay.Month = 12; theDay.Day = 31; theDay.Year -= 1; } } return new Date(theDay.Month, theDay.Day, theDay.Year);
file:///D|/1/final/BBL0058.html (38 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
} public static bool incorrectDate(int aMonth, int aDay, int aYear) { bool notCorrect; if ((aMonth >= 1) && (aMonth <= 12) && (aDay >= 1) && (aDay <= lastDay(aMonth,aYear))) notCorrect = false; else notCorrect = true; return notCorrect; } } class theProgram { static void Main() { Date theDay = new Date(); Date nextDay = new Date(); Date aDay = new Date(); Date bDay = new Date(); Console.WriteLine("Enter theDay:\n"); theDay.getDate(); Console.WriteLine("\ntheDay is {0}/{1}/{2}," ,theDay.Month ,theDay.Day ,theDay.Year); ++theDay; Console.WriteLine("\ntheDay after increment would be {0}/{1}/{2}" ,theDay.Month ,theDay.Day ,theDay.Year); nextDay = ++theDay;
Console.WriteLine("\ntheDay after another increment would be {0}/{1}/{2}." ,theDay.Month ,theDay.Day ,theDay.Year); Console.WriteLine("Assign nextDay = ++theDay which is now {0}/{1}/{2}." ,nextDay.Month ,nextDay.Day ,nextDay.Year); nextDay = theDay++; Console.WriteLine("\nIncrement theDay with a post increment would be {0}/{1}/{2}." , theDay.Month , theDay.Day , theDay.Year);
file:///D|/1/final/BBL0058.html (39 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
Console.WriteLine("nextDay = theDay++ and nextDay is {0}/{1}/{2}." , nextDay.Month , nextDay.Day , nextDay.Year);
Console.WriteLine("\n\nEnter aDate:\n"); aDay.getDate(); Console.WriteLine("\n\naDay is {0}/{1}/{2}" , aDay.Month , aDay.Day , aDay.Year); --aDay; Console.WriteLine("\n\naDay after the decrement is {0}/{1}/{2}" , aDay.Month , aDay.Day , aDay.Year); bDay = --aDay; Console.WriteLine("\naDay after another decrement that would be {0}/{1}/{2}" , aDay.Month , aDay.Day , aDay.Year); Console.WriteLine("Assigned bDay = --aDay which is now: {0}/{1}/{2}" , bDay.Month , bDay.Day , bDay.Year); bDay = aDay--; Console.WriteLine("\nThe post decrement is used on aDay which is now: {0}/{1}/{2}" , aDay.Month , aDay.Day , aDay.Year); Console.WriteLine("Assigned bDay = aDay-- and is {0}/{1}/{2}" , bDay.Month , bDay.Day , bDay.Year); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id unaryoperator1_struct.cs // written_by don voils // date_written 12/28/2006 // description This program demonstrates the use of unary // operators on structures. This program is the // same as unaryoperator1.cs except that
file:///D|/1/final/BBL0058.html (40 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
// the default constructor is commented out // and a structure is used instead of a class. // Notice that the results are not the same. // using System; public struct Date { private int month; private int day; private int year; public Date(int aMonth, int aDay, int aYear) { month = aMonth; day = aDay; year = aYear; } public int Month { get { return month; } set { month = value; } } public int Day { get { return day; } set { day = value; } } public int Year { get { return year; } set { year = value; } } public static int lastDay(int aMonth, int aYear) { int theLastDay; // Arrays are discussed in Lecture 8 // int[] daysInMonth = new int[13] { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
file:///D|/1/final/BBL0058.html (41 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
if (aMonth != 2) theLastDay = daysInMonth[aMonth]; else if (leapYear(aYear)) theLastDay = 29; else theLastDay = daysInMonth[aMonth]; return theLastDay; } public void getDate() { do { Console.Write("What is the month? "); Month = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the day? "); Day = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the year? "); Year = Int32.Parse(Console.ReadLine()); if (Year < 20) Year += 2000; else if(Year < 100) Year += 1900; } while (incorrectDate(Month, Day, Year)); } public static bool leapYear(int aYear) { bool leapTest; if (((aYear % 4 == 0) && (aYear % 100 != 0)) || (aYear % 400 == 0)) leapTest = true; else leapTest = false; return leapTest; } public static Date operator ++(Date theDay) { if (theDay.Day < lastDay(theDay.Month, theDay.Year)) theDay.Day = theDay.Day + 1; else { if (theDay.Month < 12) { theDay.Month = theDay.Month + 1; theDay.Day = 1; } else { theDay.Month = 1; theDay.Day = 1; theDay.Year = theDay.Year + 1; }
file:///D|/1/final/BBL0058.html (42 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
} return new Date(theDay.Month, theDay.Day, theDay.Year); } public static Date operator --(Date theDay) { if (theDay.Day != 1) { theDay.Day -= 1; } else { if (theDay.Month != 1) { theDay.Month -= 1; theDay.Day = lastDay(theDay.Month, theDay.Year); } else { theDay.Month = 12; theDay.Day = 31; theDay.Year -= 1; } } return new Date(theDay.Month, theDay.Day, theDay.Year); } public static bool incorrectDate(int aMonth, int aDay, int aYear) { bool notCorrect; if ((aMonth >= 1) && (aMonth <= 12) && (aDay >= 1) && (aDay <= lastDay(aMonth,aYear))) notCorrect = false; else notCorrect = true; return notCorrect; } } class theProgram { static void Main() { Date theDay = new Date(); Date nextDay = new Date(); Date aDay = new Date(); Date bDay = new Date(); Console.WriteLine("Enter theDay:\n"); theDay.getDate(); Console.WriteLine("\ntheDay is {0}/{1}/{2}," ,theDay.Month ,theDay.Day
file:///D|/1/final/BBL0058.html (43 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
,theDay.Year); ++theDay; Console.WriteLine("\ntheDay after increment would be {0}/{1}/{2}" ,theDay.Month ,theDay.Day ,theDay.Year); nextDay = ++theDay;
Console.WriteLine("\ntheDay after another increment would be {0}/{1}/{2}." ,theDay.Month ,theDay.Day ,theDay.Year); Console.WriteLine("Assign nextDay = ++theDay which is now {0}/{1}/{2}." ,nextDay.Month ,nextDay.Day ,nextDay.Year); nextDay = theDay++; Console.WriteLine("\nIncrement theDay with a post increment would be {0}/{1}/{2}." , theDay.Month , theDay.Day , theDay.Year); Console.WriteLine("nextDay = theDay++ and nextDay is {0}/{1}/{2}." , nextDay.Month , nextDay.Day , nextDay.Year);
Console.WriteLine("\n\nEnter aDate:\n"); aDay.getDate(); Console.WriteLine("\n\naDay is {0}/{1}/{2}" , aDay.Month , aDay.Day , aDay.Year); --aDay; Console.WriteLine("\n\naDay after the decrement is {0}/{1}/{2}" , aDay.Month , aDay.Day , aDay.Year); bDay = --aDay; Console.WriteLine("\naDay after another decrement that would be {0}/{1}/{2}" , aDay.Month , aDay.Day , aDay.Year); Console.WriteLine("Assigned bDay = --aDay which is now: {0}/{1}/{2}"
file:///D|/1/final/BBL0058.html (44 von 45) [01.12.2007 04:48:45]
Lecture 6 Examples
, bDay.Month , bDay.Day , bDay.Year); bDay = aDay--; Console.WriteLine("\nThe post decrement is used on aDay which is now: {0}/{1}/{2}" , aDay.Month , aDay.Day , aDay.Year); Console.WriteLine("Assigned bDay = aDay-- and is {0}/{1}/{2}" , bDay.Month , bDay.Day , bDay.Year); Console.WriteLine("\n\n"); Console.ReadKey(); } }
file:///D|/1/final/BBL0058.html (45 von 45) [01.12.2007 04:48:45]
Lecture 7: Interfaces
Lecture 7: Interfaces Introduction to Interfaces In C++ the definition of a class could be based upon multiple inheritances. For example theClass could be derived from the classes: Class1, Class2 and Class3 and its definition could look like the following: public class theClass: private Class1, public Class2, protected Class3 { ........ }
In C++ there is a problem with inheritances like this and so it is recommended that multiple inheritances should be avoided. To avoid the problems encountered with multiple inheritances in C++, C# does not permit multiple inheritances. While this is true, some of the features of multiple inheritances are desirable. To implement this preference for some of the features of multiple inheritances, C# utilizes a construct called an interface . Under this scenario, a class or a structure may be derived from multiple interfaces even though a class may only be derived from one class (Recall that a structure may not be derived from either a structure or a class). What you will find is that the real power of "inheritance" comes from interfaces rather than from classes. So why are interfaces used instead of abstract classes? An abstract class is best when dealing with objects in a series of derived classes. However an interface is used to bring together objects that relate to one another only through that interface. Interfaces provide uniform sets of methods, properties and events for objects of different classes. Thus interfaces allow programs to provide for the objects of these different classes polymorphicly. As you will notice below, an interface provides no method definitions while an abstract class may provide methods already defined that the derived class may use without further coding. A class that is derived from an abstract class has the "is-a" relationship while an interface implements the features of the interface. Interfaces are meant to force the derived class to implement the interface's methods, properties and events. An abstract class serves as the basis for a hereditary tree of classes while interfaces are meant to be mixed into inheritance trees where needed. An interface is similar to a class that has only abstract methods. An interface may have instances of a reference type while an abstract class may not. Although an interface may have instances, they must be initialized indirectly. For example if theClass is derived from the interface: Aninterface then the following is permissible: theClass theReference = new theClass(); Aninterface theIReference = (AnInterface)theReference;
With this arrangement, theIReference may be used to manipulate the contents of the object derived from the interface to which theReference refers. This is similar to references of abstract classes. The general construct of an interface is: [attribute] [access-specifier] interface Interfacename [: base-list] { interface-body}
where
file:///D|/1/final/BBL0059.html (1 von 3) [01.12.2007 04:48:46]
Lecture 7: Interfaces ●
attribute is a feature that is not discussed in these lecture notes.
●
access-specifier may be: public, private, protected, internal or protected internal. and is public by default.
●
interface is a keyword that must be supplied.
●
Interfacename is the programmer's name for the interface and usually begins with the letter I.
●
:base-list means that this interface may be derived from one or more other interfaces (but not classes).
●
interface-body is a list of the declarations of properties, events or methods.
Interfaces: ●
may have no fields not even static but may have properties instead.
●
may have no constructors nor destructor.
●
may have no modifiers for the methods nor the properties but they are public by default.
●
may not use nesting of enumerated data types, structures, classes or other interfaces.
●
may not be derived from enumerated data types, structures or classes but may be derived from other interfaces.
The interface's definition does not include an access specifier (assumed to be public) but it is defined by placing the keyword interface at the beginning of the definition as in the following: interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); }
Notice in the definition of IAccounts above that the methods only have a prototype. It is left to the implementing class to complete the definition of each method. Further the definition of IAccounts requires that a class that implements this interface must also define the property: theBalance with a get accessor for implementing the field. While this interface requires that the property and the two methods must be implemented, all that is required is that the method's name, the output type and the signature must be used and that the property's name and its accessor must be defined. In addition there is no restriction on the class' ability to define other fields, other properties and other methods. Nor is there a restriction put on the class about it being derived from other interfaces or another class. All that is required of the derived class is that it must at least implement the features of the interface. A UML chart that represents this interface is the following:
Notice the + to the left of the interface's property and the methods. This would imply that they are public. However these pluses should not be there except Visio would not permit them to be eliminated. In addition, neither the
file:///D|/1/final/BBL0059.html (2 von 3) [01.12.2007 04:48:46]
Lecture 7: Interfaces
property nor the methods of an interface have explicit access modifiers. The access modifiers are public by default. If access modifiers are used in their declarations a compiler error will occur. Note: Visio has an interface graphic but it did not seem to provide the necessary information to describe a C# interface. Therefore the above UML chart was created with a class icon rather than the interface icon. In some texts, the <> appears above the name of the interface. However this does not seem to work when using a class icon and even when the interface icon was used this still occurred.
file:///D|/1/final/BBL0059.html (3 von 3) [01.12.2007 04:48:46]
Deriving a Class or a Structure from an Interface
Deriving a Class or a Structure from an Interface Deriving a Class from an Interface The general form of the class' definition that is dependent on interfaces is the following: [attribute] [access-modifier] class [theName]: [base-class][interface-list] { the-body}
where ●
attribute is a feature that is not discussed in these lecture notes.
●
access-specifier may be: public, private, protected, internal, protected internal or sealed.
●
class is a keyword that must be supplied.
●
thName is the programmer's name for the class
●
base-class means that this class may be derived explicitly from at most one other class (if no base class is explicitly listed, then the class is implicitly derived from object).
●
interface-list means that this class may be derived from one or more interfaces whose names may be listed in any order and separated by commas.
●
the-body is a list of the declarations of the events, fields, properties or methods as long as each of the features of the interface(s) are implemented.
A class that inherits from an interface: ●
must specify that it implements the interface(s)
●
must provide implementations for every method, for every property and every event specified in the interface (s)' definition.
●
must match for each interface the methods and properties with the same name, the same signature and the same return type.
●
must match exactly any parameter of the methods that has a ref or an out in the interface(s) methods.
●
may have any additional fields, methods, properties or events other than those specified by the interface(s).
How a class implements an interface is completely up to the programmer. That is two different classes could implement the same interface's features in entirely different ways. For example suppose that a program had the following interface defined: interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); }
file:///D|/1/final/BBL0060.html (1 von 3) [01.12.2007 04:48:47]
Deriving a Class or a Structure from an Interface
then it would be possible to define the class: Checking to implement the interface IAccounts and each of the interface's methods and its properties like in the following definition: class Checking: IAccounts { private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } }
See theChecking.cs for an implementation of this interface and this class that is derived from the interface. The following is a UML chart that depicts the relationship between the class Checking and the interface: IAccounts:
Notice that the name of the interface appears in the header of the class' UML chart. In addition notice that the interface connector does not touch the interface UML chart. Further notice the different symbol that connects the class with the interface. This symbol is referred to as a "lollipop". This is a symbol different from the one that shows inheritance or from the one that shows composition. In addition note that Visio places a + to the left of the interface's property and its method declarations even though they are not to have an explicit access specifier. file:///D|/1/final/BBL0060.html (2 von 3) [01.12.2007 04:48:47]
Deriving a Class or a Structure from an Interface
Using References to an Interface to Access the Inherited Features of a Class In the example above, an object of the class was used to access the inherited features from the interface. However, it is also possible to use a reference to the interface to access these features as well. To do this the reference must be defined and initialized as in the following: theClass theObject = new theClass(); theInterface theReference = (theInterface) theObject; theReference.inheritedMethod();
While it is possible to declare a reference of an interface, it is not possible to define an object of the interface because the new operator is not defined on interfaces. While a reference to the interface may access the inherited features, it may not be used to access either non-inherited features of the class or features inherited from another class or another interface. For an example see theChecking3.cs
Deriving a Structure from an Interface In the example above a class was derived from an interface. In addition to classes being derived from an interface, it is also possible for a structure to be derived from an interface. Modifying the above definition of the class: Checking to the following (where it is now a structure) demonstrates that a structure may be derived from an interface as well as having a class derived from the interface: struct Checking: IAccounts { public decimal Balance; public decimal theBalance { get { return Balance; } } public Checking(decimal theAmount) { Balance = theAmount; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } }
For an example of a structure being derived from an interface see theChecking2.cs.
file:///D|/1/final/BBL0060.html (3 von 3) [01.12.2007 04:48:47]
Deriving a Class from both a Class and an Interface
Deriving a Class from both a Class and an Interface In addition to being derived from an interface, a class may also be derived from a class and one or more interfaces at the same time. When a class is derived from an interface as well as a class, the name of the class must be listed first in the derived class' definition header. For example suppose that a program had the interface IAccounts defined as the following: interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); }
and that the class: People is defined as the following: public class People { private string PeopleID; private string PeopleName; private string PeopleAddress; private string PeopleCity; private string PeopleState; private string PeopleZipCode; public void setPeopleID(string ID) { PeopleID = ID; } public void setPeopleName(string Name) { PeopleName = Name; } public void setPeopleAddress(string Address) { PeopleAddress = Address; } public void setPeopleCity(string City) { PeopleCity = City; } public void setPeopleState(string State) { PeopleState = State; } public void setPeopleZipCode(string Code) { PeopleZipCode = Code; } public string getPeopleID() { return PeopleID;
file:///D|/1/final/BBL0061.html (1 von 3) [01.12.2007 04:48:47]
Deriving a Class from both a Class and an Interface
} public string getPeopleName() { return PeopleName; } public string getPeopleAddress() { return PeopleAddress; } public string getPeopleCity() { return PeopleCity; } public string getPeopleState() { return PeopleState; } public string getPeopleZipCode() { return PeopleZipCode; } public override string ToString() { string theValue= "ID: " + PeopleID+ "\n" + "Name: " + PeopleName +"\n" + "Address: " + PeopleAddress + "\n" + "City: " + PeopleCity + "\n" + "State: " + PeopleState + "\n" + "Zip: " + PeopleZipCode + "\n"; return theValue; } }
Then the class Checking could be defined as in the following: class Checking: People, IAccounts { private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount;
file:///D|/1/final/BBL0061.html (2 von 3) [01.12.2007 04:48:47]
Deriving a Class from both a Class and an Interface
} }
See PeopleChecking.cs for the full implementation of this derivation. The following is a UML chart that shows the relationship of the class Checking with the base class People and the interface IAccount:
Notice in the above UML chart that there are different connectors between the class: Checking and the base class People vs the interface IAccounts. Further, notice in the UML chart for Checking that the base class and the interface are both listed after the derived class' name.
file:///D|/1/final/BBL0061.html (3 von 3) [01.12.2007 04:48:47]
Deriving a Class or a Structure from One or More Interfaces
Deriving a Class or a Structure from One or More Interfaces Deriving a Class from More than One Interface While the previous examples had a class that was derived from only one interface, it is possible to have a class derived from more than one interface. For example suppose that the following interface was added to the class Checking above: interface IChecking { decimal theFee {get; set;} }
This could then be used with the class Checking as in the following where both the interfaces IChecking and IAccounts as well as the class: People are used to define the class Checking: class Checking: People, IChecking, IAccounts { ..... }
Note: The class People must be listed first and then the interfaces follow but they may be listed in any order. See FeeChecking.cs for an implementation of a class being derived from multiple interfaces. The following is a UML chart for these relationships:
file:///D|/1/final/BBL0062.html (1 von 3) [01.12.2007 04:48:48]
Deriving a Class or a Structure from One or More Interfaces
Deriving a Class from an Interface that is Derived from an Interface In the example above, the class had two different interfaces that it was derived from. Each of these interfaces was root interfaces meaning that they were not themselves derived from another interface. But it is possible to have one of the interfaces that a class is derived from itself to be derived from another interface. For example taking the previous example and changing the interface IChecking to the following: interface IChecking: IAccounts { decimal theFee {get; set;} }
and then changing the heading of the class: Checking to the following: class Checking: People, IChecking { ........ }
permits the interface IChecking to extend the interface IAccounts and still the class Checking is based upon the interface IAccounts. See extendedInterface.cs. A UML chart for these relationships is the following:
file:///D|/1/final/BBL0062.html (2 von 3) [01.12.2007 04:48:48]
Deriving a Class or a Structure from One or More Interfaces
Notice in the example above that having the interface IChecking derived from the interface IAccounts in no way affected the way that the interface IChecking is defined. It is defined the same as it was in the previous example where it was not derived from another interface. Further notice that there is no indication in the body of IChecking that shows that it is implementing the properties or methods of IAccounts. Note: While it is possible for an interface to be derived from another interface, it is not possible for an interface to be derived from a class. Note: The two examples above demonstrated what could be possible when a class is derived from another class and in addition from one or more interfaces. What is also possible is that the base class and the interfaces could themselves be derived from even more complex derivations.
Deriving a Structure from an Interface that is in Turn Derived from an Interface But how about a structure? Using some of the code of the above example except defining Checking as a structure, then the following form of the definition is possible: struct Checking: IChecking { ........ }
Notice that the class People was not used. Recall that structures can not be derived from either other structures or classes but they can be derived from interfaces. For an example see extendedInterface2.cs
file:///D|/1/final/BBL0062.html (3 von 3) [01.12.2007 04:48:48]
Interface References to Access Class or Structure Instances
Interface References to Access Class or Structure Instances As discussed above, it is possible to define a reference to an interface but it is not possible to define an instance of an interface because the new operator is not defined on interfaces. That is the following statement would not compile: ItheInterface theReference = new ItheInterface();
While this is true, interface references may be used to access an instance of a derived class or structure like a reference to an abstract class may access an instance of a derived class through type casting. For example suppose that the class: Checking is derived from the interface IAccounts. Then it is possible to have the following statements: Checking theAccount = new Checking(); IAccount myAccount = (IAccount) theAccount;
or combining these two statements, this relationship could be stated as the following: IAccount myAccount = (IAccount) new Checking();
To see this implemented link to interfacereferences.cs. This example used the interface reference to access an instance of a class that is derived from the interface. The same could be true for structures. For an example using a structure that is derived from an interface see interfacereferences2.cs.
file:///D|/1/final/BBL0063.html [01.12.2007 04:48:48]
Overriding Interface Implementations
Overriding Interface Implementations In a previous lecture the terms new and override with respect to methods were discussed. For a review suppose that class Derived is derived from class Base. Suppose that Base has a method: show(). Therefore when Derived is defined there are two options for the method show(): 1. have the objects of Derived use the show() from Base 2. define a method show() for the class Derived that would hide the base class Base method show(). Another option could be achieved using the modifier: new on the implementation of the show() method in the derived class Derived. In addition, if the method show() in the base class Base was a virtual method, then the definition of the show() in the class Derived could hide the show() in Base by using the keyword override on the definition of the class Derived. The question should therefore arise as to whether it is possible for a Derived class that is derived from Base class that in turn is derived from an interface may override the interfaces methods that are implemented in the Base class. See overrideInterface.cs to see an example which illustrates that this is possible.
file:///D|/1/final/BBL0064.html [01.12.2007 04:48:49]
Using the is and the as Operators
Using the is and the as Operators Some times it is not clear whether a reference to an interface does in fact have access to the class' object. This condition may be checked by using the is or the as operator. For example suppose that a program has a class: theClass and it is derived from the interface: Interface. Then the question is whether theReference of Interface can be used to access an object of theClass in the following: theClass theClassReference = new theClass(); Interface theReference = (Interface) theClassReference;
Further suppose that theClass has a method: theMethod(). What is desired is whether: theReference.theMethod();
is syntactically correct. If it is not, then an exception of type: System.InvalidCastException is thrown. (More will be said about exceptions in a later lecture.) To prevent this exception from occurring, this relationship could be tested prior to implementing the type casting and the call of the method: theMethod() by theReference using the following code: if((theClassReference is Interface) { Interface theReference = (Interface) theClassReference; theReference.theMethod(); }
As a result of the above, theReference would only call theMethod() should theClass have implemented the interface: Interface. The operator as works similar to is. Using as, the above could be implemented in the following manner: theClassReference = new theClass(); Interface theReference = theClassReference as Interface; if(theReference != null) theReference.theMethod();
In this if( ) statement theReference would be null should it not represent the object of theClass to which theClassReference refers.
file:///D|/1/final/BBL0065.html [01.12.2007 04:48:49]
Explicit Interface Implementation
Explicit Interface Implementation Suppose that theClass is derived from two different and unrelated interfaces: Interface1 and Interface2. Further suppose that each of these interfaces has a method: theMethod() with the same signature. The question is how to define theClass so that each theMethod() is implemented. To do this requires what is called an explicit implementation. An explicit implementation requires that at least one of the implemented methods of theClass has its name preceded with the name of the interface (which in this case is called an explicit implementation of the method). When this is done, the implemented method does not have an access specifier. An explicit implementation helps to distinguish which implementation is being used if there is more than one. For example the two methods could be defined in the class as in the following: theMethod() { .... } Interface2.theMethod() { .... }
That is suppose the program contained the following code: interface Interface1 { void theFirstOne(); void theMethod(); } interface Interface2 { void theSecondOne(); void theMethod(); } class theClass: Interface1, Interface2 { . ........ public void theFirstOne() { ..... } public void theSecondOne() { ...... } // The following will implement the Interface1 method // public void theMethod() { ... } // The following will be an explicit implementation of // the Interface2 method. Notice no access specifier. //
file:///D|/1/final/BBL0066.html (1 von 2) [01.12.2007 04:48:50]
Explicit Interface Implementation
Interface2.theMethod() { .... } }
so that when defining an instance of theClass, as in the following: theClass theObject = new theClass();
and then the call of theMethod() would be the following: theObject.theMethod();
but this would be calling theMethod() that was derived from the interface: Interface1 without any additional explicit notation. In order to access the explicit implementation: Interface2.theMethod() a reference to the interface: Interface2 must be declared as in the following: Interface2 theReference = (Interface2) theObject;
Then, using theReference, the explicit implementation may be accessed as in the following: theReference.theMethod();
For an example of this concept see: explicitImplimentation.cs The example above only made one of theMethod() functions an explicit implementation. What may be desirable would be to make each an explicit implementation. Some authors on C# recommend that each method inherited from an interface be an explicit implementation. In this way there would be fewer problems when the code was modified by other programmers or if the code was in the component library with little or no documentation to warn about the problems that may be encountered deriving a class from the component interfaces.
file:///D|/1/final/BBL0066.html (2 von 2) [01.12.2007 04:48:50]
Using the IDE Class Diagram to Code Interface Implementations
Using the IDE Class Diagram to Code Interface Implementations In previous lectures it was demonstrated how to use the IDE Class Diagram to code enumerated data types, structures, classes and class inheritance. This lecture will demonstrate how to use the Class Diagram to write programs with interfaces and classes to implement interface inheritances. Example 1: The first demonstration will show how to write the code for interface: IAccounts and the derived class: Checking that were a part of the example: theChecking.cs. Create a console project: testChecking. Once the project is open, click on Project on the menu bar. Next on the Project menu select Add New Item. Follow this by selecting: Class Diagram and then click the Add button. When the ClassDiagram1.cd appears, click on the Toolbox link. So far these are the same steps used in the previous Class Diagram examples. Next, select the Interface icon and drag it onto the ClassDiagram1.cd. As before, a form will appear to specify the initial conditions. When the New Interface form appears, enter as the Interface name: IAccounts. Change the File name to: Program.cs under the Add to existing file option. What should appear is the following:
Click the OK button to register this interface. Next drag a class icon onto ClassDiagram1.cd. When the New Class form appears enter Checking for the Class name. Change the File name to Program.cs under Add to existing file. What should be visible will be similar to the following graphic:
file:///D|/1/final/BBL0067.html (1 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
Click the OK button to register the class. The ClassDiagram1.cd should now contain a graphic for the interface: IAccounts and one for the class: Checking. The resulting graphics should look like the following:
Next, click on the icon for IAccounts and do a right mouse button. Select Add and then Property as shown in the file:///D|/1/final/BBL0067.html (2 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
following graphic:
When this selection is made, a blank will appear at the bottom of the IAccounts icon to type in theBalance like the following:
file:///D|/1/final/BBL0067.html (3 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
After this property has been entered, do a right mouse on theBalance. When the pop up menu appears select Properties like the following:
When the properties menu appears change the Type from the default of int to decimal and that it would be public as in the following:
file:///D|/1/final/BBL0067.html (4 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
As you may recall, IAccounts has two methods: Deposit() and Withdrawal() both of which have void output. To enter these methods into the IAccounts icon do a right mouse button on the icon and select Method from the pop up menu like the following:
A blank should now appear on the IAccounts icon below the word Method. Type in Deposit. Check the
file:///D|/1/final/BBL0067.html (5 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
Properties for this method to ensure that the output is void. When you do the following should appear:
Repeat the process for the method Withdrawal. After having completed these steps, the icon should appear like the following:
file:///D|/1/final/BBL0067.html (6 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
The next step is to view the code by doing a right mouse on the icon. When this is done the following menu should appear and select the View Code option.
file:///D|/1/final/BBL0067.html (7 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
The code should now appear as the following: using System; using System.Collections.Generic; using System.Text; namespace testChecking { class Program { static void Main(string[] args) { } } public interface IAccounts { decimal theBalance { get; set; } void Deposit(); void Withdrawal(); } public class Checking { } }
file:///D|/1/final/BBL0067.html (8 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
Notice that by default the property: theBalance has both the get and the set. In this particular example only the get is to be used so delete the set. After the set has been deleted, theBalance becomes ReadOnly. Modify the signatures of the method: Deposit() to Deposit(decimal theAmount) and the signature of the method: Withdrawal () to Withdrawal(decimal theAmount). Next add IAccounts as a base to the class Checking and the code should now appear as the following: using System; using System.Collections.Generic; using System.Text; namespace testChecking { class Program { static void Main(string[] args) { } } interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } public class Checking: IAccounts { } }
After the above code has been written into the IDE, do a right mouse button on the IAccounts following the name of the class. A popup menu like the following should appear:
Next, click on the Implement Interface option. Once this has been selected, the following should now appear inside of the definition of the class: Checking:
file:///D|/1/final/BBL0067.html (9 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
class Checking : IAccounts { #region IAccounts Members public decimal theBalance { get { throw new Exception("The method or operation " + "is not implemented."); } } public void Deposit(decimal theAmount) { throw new Exception("The method or operation is " + "not implemented."); } public void Withdrawal(decimal theAmount) { throw new Exception("The method or operation is " + "not implemented."); } #endregion }
Notice how the shell of the class Checking has been rewritten to implement the interface: IAccounts. What is left is to do is to modify the body of each feature inherited from the interface. Then return to ClassDiagram1.cd and add the field Balance and the constructor which are needed by the class Checking. Be sure to check the field Balance to ensure that it is decimal and private. To see how the icons have changed, click on ClassDiagram1.cd tab. When you do, the following should appear:
file:///D|/1/final/BBL0067.html (10 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
Notice that the field: Balance, the property: theBalance, the methods: Deposit and Withdrawal as well as the constructor have been added to the Checking icon automatically. Further notice that automatically the IAccounts interface connector was added to the top of this icon. After making all of these modifications, select View Code and notice how the class Checking has been modified. Example 2: The previous example only showed a class that was derived from one interface. However sometimes a class is derived from more than one interface as in the example: FeeChecking.cs Create a new project: testingIDE2 in Visual Studio .NET 2005. Using the techniques from the previous example place two interface icons: IAccounts and IChecking onto the ClassDiagram1.cd. Next add two class icons: People and Checking. The icons should now be available as in the following:
file:///D|/1/final/BBL0067.html (11 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
Using the techniques discussed above, add the following features to IAccounts: ●
property: ❍
●
decimal theBalance {get;}
methods: ❍
void Deposit(decimal theAmount);
❍
void Withdrawal(decimal theAmount);
and for IChecking: ●
property: ❍
decimal theFee {get; set;}
Remember that the set; will have to be removed when viewing the code for the interface: IAccounts making theBalance a ReadOnly property. While viewing the code add the base class People and the two interfaces: IAccounts and IChecking to the header of the class: Checking. Once these steps have been accomplished, the icons should now appear as the following:
file:///D|/1/final/BBL0067.html (12 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
Next while in View Code, do a right mouse button on each of the interfaces in the heading of the class Checking one at a time. While pointing at each of the interfaces, right mouse button and select: Implement Interface for each of the interfaces. The IDE rewrites the code for the class: Checking and it should now appear as the following: public class Checking: People, IAccounts, IChecking { #region IAccounts Members public decimal theBalance { get { throw new Exception("The method or operation" + " is not implemented."); } } public void Deposit() { throw new Exception("The method or operation" + " is not implemented."); } public void Withdrawal() { throw new Exception("The method or operation" + " is not implemented."); } #endregion #region IChecking Members public decimal theFee { get { throw new Exception("The method or operation is not implemented.");
file:///D|/1/final/BBL0067.html (13 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
} set { throw new Exception("The method or operation is not implemented."); } } #endregion }
The icons in ClassDiagram1.cs should look like the following:
Notice how the properties and the methods in Checking that it inherited from the two interfaces have been added to the Checking icon. In addition notice that the class inheritance pointer shows the derivation from the class People. Further an interface connector to the two interfaces is also attached to the Checking icon. What needs to be done now is to complete the construction of Checking and People by adding the fields, properties and methods remaining for each class using the same technique that was used for the two interfaces. When this is done the icons should appear as the following:
file:///D|/1/final/BBL0067.html (14 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
After completing these steps, the bodies of the methods of the two classes needs to be completed. After these steps have been taken, all that would need to be done would be to complete the writing of the code in Main(). Example 3: In addition to the Implement Interface option used in the examples above, there is also an Implement Interface Explicit option. Earlier in this lecture theClass was defined so that it was derived from Interface1 and Interface2 in the program: explicitImplimentation.cs. The derivation from Interface1 was a regular interface derivation. However the derivation from Interface2 was an explicit derivation. This example will demonstrate how the IDE may be used for an explicit implementation that was used in this program. Create a project: testingtheClass. Create a ClassDiagram1.cd as in the previous examples. Drag onto ClassDiagram1.cd the two interface icons named: Interface1 and Interface2. Place each of them in the file: Program.cs. For Interface1 add two methods: theFirstOne() and theMethod(). For Interface2 add two methods: theSecondOne() and theMethod(). (Notice that each of the interfaces has a method: theMethod() so that could be a problem for a class that is inheriting from both of these interfaces.) Next drag a class icon, name it: theClass and place it into Program.cs as well. The ClassDiagram1.cd should now contain the following icons:
file:///D|/1/final/BBL0067.html (15 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
Next View Code and the following should appear after placing Interface1 and Interface2 after theClass name in the code to show the inheritance from the two interfaces: interface Interface1 { void theFirstOne(); void theMethod(); } interface Interface2 { void theSecondOne(); void theMethod(); } class theClass: Interface1,Interface2 { }
The ClassDiagram1.cd icons should now appear as the following:
file:///D|/1/final/BBL0067.html (16 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
After modifying theClass' header in View Code, right click on Interface1 in theClass header and select Implement Interface. Next right click on Interface2 and selection Implement Interface Explicit. When these steps are completed, the code should now appear like the following: interface Interface1 { void theFirstOne(); void theMethod(); } interface Interface2 { void theSecondOne(); void theMethod(); } class theClass : Interface1, Interface2 { #region Interface1 Members public void theFirstOne() { throw new Exception("The method or operation is not implemented."); } public void theMethod() { throw new Exception("The method or operation is " + "not implemented."); } #endregion #region Interface2 Members void Interface2.theSecondOne() { throw new Exception("The method or operation is " + "not implemented."); } void Interface2.theMethod() { throw new Exception("The method or operation is " + "not implemented."); } #endregion }
The icons in ClassDiagram1.cd should now appear as the following:
file:///D|/1/final/BBL0067.html (17 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
Observe how the methods inherited from the two interfaces have been added to the icon for theClass. The only difference between the above example and the original program is that both of the methods from Interface2 were turned into an explicit implementation. What could be done, would be to change theSecondOne() so that it is not an explicit implementation. However you may recall that some are recommending that all interfaces be an explicit implementation as was just done by the IDE. Using the IDE tools in ClassDiagram1.cd, complete the code for theClass. What should be done next would be to add the fields: theFirst and theSecond. Next add the constructor to theClass. Once these steps are completed the icons should look like the following:
file:///D|/1/final/BBL0067.html (18 von 19) [01.12.2007 04:48:51]
Using the IDE Class Diagram to Code Interface Implementations
After these have been added, return to View Code and modify the methods that were inherited from the interfaces and the constructor. This should complete the definition of theClass. What is left is the modification of Main() which should be done while viewing the code.
file:///D|/1/final/BBL0067.html (19 von 19) [01.12.2007 04:48:51]
Lecture 7 Examples
Lecture 7 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
explicitImplimentation. cs
Demonstrates the use of an explicit implementation of a interfaces method.
extendedInterface2.cs
Demonstrates a structure derived from an interface that is derived from an interface.
extendedInterface.cs
Demonstrates a class derived from a class and an interface.
FeeChecking.cs
Demonstrates that a class may be derived from more than one interface.
interfacereferences2.cs
Demonstrates the use of a reference to an interface being used to access an instance of a structure that is derived from the interface.
interfacereferences.cs
Demonstrates the use of a reference to an interface acting as a reference to an instance of a class that is derived from the interface.
overrideInterface.cs
Demonstrates a class derived from a class that overrides the base class' implementation of the interface's method.
PeopleChecking.cs
Demonstrates that a class may be derived from another class and an interface.
theChecking2.cs
A structure that is derived from an interface.
theChecking3.cs
Demonstrates the use of reference to the interface that acts on the inherited features of the class derived from the interface.
theChecking.cs
A class that is derived from an interface.
theMethodTest.cs
Demonstrates how a class may define interface methods where both interfaces have a common method name.
usingAS.cs
Demonstrates a reference to an interface acting on an instance of a class.
usingIS.cs
Demonstrates a reference to an interface acting on an instance of a class.
// program_id explicitImplimentation.cs // written_by don voils // date_written 7/23/2006 // description This program demonstrates the use of an explicit // implementation of a interfaces method. // using System; namespace theChecking { interface Interface1 { void theFirstOne(); void theMethod(); } interface Interface2 { void theSecondOne(); void theMethod(); }
file:///D|/1/final/BBL0068.html (1 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
class theClass: Interface1,Interface2 { private int theFirst; private int theSecond; public theClass() { theFirst = 5; theSecond = 15; } public void theFirstOne() { Console.WriteLine("The first is {0}\n", theFirst); } public void theSecondOne() { Console.WriteLine("The second is {0}\n", theSecond); } public void theMethod() { Console.WriteLine("The product is {0}\n", theFirst*theSecond); } // The following will be an explicit implementation of // the Interface2 method. Notice no access specifier while // the other implementation has an access specifier. // void Interface2.theMethod() { Console.WriteLine("The sum is {0}\n", theFirst + theSecond); } } class theProgram { static void Main() { theClass theObject = new theClass(); theObject.theFirstOne(); theObject.theSecondOne(); // theObject can directly access theMethod from Interface1 // by using the dot operator. // theObject.theMethod(); // theObject can not directly access theMethod from Interface2 // and must go through an Interface2 reference. // Interface2 theReference = (Interface2)theObject; theReference.theMethod(); Console.ReadKey(); } } }
file:///D|/1/final/BBL0068.html (2 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
// program_id extendedInterface2.cs // written_by don voils // date_written 1/6/2006 // description This program demonstrates a structure // derived from an interface // where the interface itself is derived // from another interface. // using System; namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } interface IChecking: IAccounts { decimal theFee {get; set;} } struct Checking: IChecking { public decimal Fee; public decimal theFee { get { return Fee; } set { Fee = value; } } public decimal Balance; public Checking(decimal theAmount) { Fee = 0.00m; Balance = theAmount; } public decimal theBalance { get { return Balance; } } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) {
file:///D|/1/final/BBL0068.html (3 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
Balance -= theAmount; } } class theProgram { static void Main() { Checking newAccount = new Checking(0.00m); Console.Write("\nWhat is the starting balance for this account? "); newAccount.Balance = Decimal.Parse(Console.ReadLine()); Console.Write("\nWhat is the fee for this account? "); newAccount.theFee = Decimal.Parse(Console.ReadLine()); Console.Write("\nWhat is the deposit amount? "); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is the withdrawal amount? "); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.Clear(); if(newAccount.theBalance <= 500.00m) { newAccount.Withdrawal(newAccount.theFee); Console.WriteLine("The account was charged a fee of {0:c}",newAccount.theFee); } Console.WriteLine("\nCurrent balance is {0:c}.\n\n",newAccount.theBalance); Console.ReadKey(); } }
}
// program_id extendedInterface.cs // written_by don voils // date_written 1/3/2006 // description This program demonstrates a class // derived from a class and an interface // where the interface itself is derived // from another interface. // using System; namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount);
file:///D|/1/final/BBL0068.html (4 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
void Withdrawal(decimal theAmount); } interface IChecking: IAccounts { decimal theFee {get; set;} } public class People { private string PeopleID; private string PeopleName; private string PeopleAddress; private string PeopleCity; private string PeopleState; private string PeopleZipCode; public void setPeopleID(string ID) { PeopleID = ID; } public void setPeopleName(string Name) { PeopleName = Name; } public void setPeopleAddress(string Address) { PeopleAddress = Address; } public void setPeopleCity(string City) { PeopleCity = City; } public void setPeopleState(string State) { PeopleState = State; } public void setPeopleZipCode(string Code) { PeopleZipCode = Code; } public string getPeopleID() { return PeopleID; } public string getPeopleName() { return PeopleName; } public string getPeopleAddress() { return PeopleAddress; } public string getPeopleCity() { return PeopleCity; } public string getPeopleState()
file:///D|/1/final/BBL0068.html (5 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
{ return PeopleState; } public string getPeopleZipCode() { return PeopleZipCode; } public override string ToString() { string theValue= "ID: " + PeopleID+ "\n" + "Name: " + PeopleName +"\n" + "Address: " + PeopleAddress + "\n" + "City: " + PeopleCity + "\n" + "State: " + PeopleState + "\n" + "Zip: " + PeopleZipCode + "\n"; return theValue; } } class Checking: People, IChecking { private decimal Fee; public decimal theFee { get { return Fee; } set { Fee = value; } } private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram
file:///D|/1/final/BBL0068.html (6 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
{ static void Main() { Checking newAccount = new Checking(); Console.Write("What is the customer's name? "); newAccount.setPeopleName(Console.ReadLine()); Console.Write("\nWhat is {0}'s ID? ",newAccount.getPeopleName()); newAccount.setPeopleID(Console.ReadLine()); Console.Write("\nWhat is {0}'s address? ",newAccount.getPeopleName()); newAccount.setPeopleAddress(Console.ReadLine()); Console.Write("\nWhat is {0}'s city? ",newAccount.getPeopleName()); newAccount.setPeopleCity(Console.ReadLine()); Console.Write("\nWhat is {0}'s state? ",newAccount.getPeopleName()); newAccount.setPeopleState(Console.ReadLine()); Console.Write("\nWhat is {0}'s zip code? ",newAccount.getPeopleName()); newAccount.setPeopleZipCode(Console.ReadLine()); Console.Write("\nWhat is {0}'s fee for this account? ",newAccount.getPeopleName()); newAccount.theFee = Decimal.Parse(Console.ReadLine()); Console.Write("\nWhat is {0}'s deposit amount? ",newAccount.getPeopleName()); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is {0}'s withdrawal amount? ",newAccount.getPeopleName()); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.Clear(); Console.WriteLine("{0}",newAccount.ToString()); if(newAccount.theBalance <= 500.00m) { newAccount.Withdrawal(newAccount.theFee); Console.WriteLine("{0} was charged a fee of {1:c}", newAccount.getPeopleName(),newAccount.theFee); } Console.WriteLine("\nCurrent balance is {0:c}.\n\n",newAccount.theBalance); Console.ReadKey(); } } }
// program_id FeeChecking.cs // written_by don voils // date_written 1/3/2006 // description This program demonstrates that a class may be // derived from more than one interface. //
file:///D|/1/final/BBL0068.html (7 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
using System; namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } interface IChecking { decimal theFee {get; set;} } public class People { private string PeopleID; private string PeopleName; private string PeopleAddress; private string PeopleCity; private string PeopleState; private string PeopleZipCode; public void setPeopleID(string ID) { PeopleID = ID; } public void setPeopleName(string Name) { PeopleName = Name; } public void setPeopleAddress(string Address) { PeopleAddress = Address; } public void setPeopleCity(string City) { PeopleCity = City; } public void setPeopleState(string State) { PeopleState = State; } public void setPeopleZipCode(string Code) { PeopleZipCode = Code; } public string getPeopleID() { return PeopleID; } public string getPeopleName() { return PeopleName;
file:///D|/1/final/BBL0068.html (8 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
} public string getPeopleAddress() { return PeopleAddress; } public string getPeopleCity() { return PeopleCity; } public string getPeopleState() { return PeopleState; } public string getPeopleZipCode() { return PeopleZipCode; } public override string ToString() { string theValue= "ID: " + PeopleID+ "\n" + "Name: " + PeopleName +"\n" + "Address: " + PeopleAddress + "\n" + "City: " + PeopleCity + "\n" + "State: " + PeopleState + "\n" + "Zip: " + PeopleZipCode + "\n"; return theValue; } } class Checking: People, IChecking, IAccounts { private decimal Fee; public decimal theFee { get { return Fee; } set { Fee = value; } } private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) {
file:///D|/1/final/BBL0068.html (9 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram { static void Main() { Checking newAccount = new Checking(); Console.Write("What is the customer's name? "); newAccount.setPeopleName(Console.ReadLine()); Console.Write("\nWhat is {0}'s ID? ",newAccount.getPeopleName()); newAccount.setPeopleID(Console.ReadLine()); Console.Write("\nWhat is {0}'s address? ",newAccount.getPeopleName()); newAccount.setPeopleAddress(Console.ReadLine()); Console.Write("\nWhat is {0}'s city? ",newAccount.getPeopleName()); newAccount.setPeopleCity(Console.ReadLine()); Console.Write("\nWhat is {0}'s state? ",newAccount.getPeopleName()); newAccount.setPeopleState(Console.ReadLine()); Console.Write("\nWhat is {0}'s zip code? ",newAccount.getPeopleName()); newAccount.setPeopleZipCode(Console.ReadLine()); Console.Write("\nWhat is {0}'s fee for this account? ",newAccount.getPeopleName()); newAccount.theFee = Decimal.Parse(Console.ReadLine()); Console.Write("\nWhat is {0}'s deposit amount? ",newAccount.getPeopleName()); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is {0}'s withdrawal amount? ",newAccount.getPeopleName()); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.Clear(); Console.WriteLine("{0}",newAccount.ToString()); if(newAccount.theBalance <= 500.00m) { newAccount.Withdrawal(newAccount.theFee); Console.WriteLine("{0} was charged a fee of {1:c}", newAccount.getPeopleName(),newAccount.theFee); } Console.WriteLine("\nCurrent balance is {0:c}.\n\n",newAccount.theBalance); Console.ReadKey(); } }
file:///D|/1/final/BBL0068.html (10 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
}
// program_id interfacereferences2.cs // written_by don voils // date_written 1/6/2006 // description This program demonstrates the use of a reference // to an interface being used to access an instance // of a structure that is derived from the interface. //
using System; namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } struct Checking: IAccounts { public decimal Balance; public decimal theBalance { get { return Balance; } } public Checking(decimal theAmount) { Balance = theAmount; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram { static void Main() { Checking theAccount = new Checking(0.00m); IAccounts newAccount = (IAccounts) theAccount; Console.Write("What is the deposit amount? ");
file:///D|/1/final/BBL0068.html (11 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is the withdrawal amount? "); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\nThe current balance is {0:c}.\n\n",newAccount.theBalance); Console.ReadKey(); } } }
// program_id interfacereferences.cs // written_by don voils // date_written 1/6/2006 // description This program demonstrates the use of a reference // to an interface acting as a reference to an // instance of a class that is derived from the interface. //
using System; namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } class Checking: IAccounts { private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } }
file:///D|/1/final/BBL0068.html (12 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
class theProgram { static void Main() { Checking theAccount = new Checking(); IAccounts newAccount = (IAccounts) theAccount; Console.Write("What is the deposit amount? "); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is the withdrawal amount? "); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\nThe current balance is {0:c}.\n\n",newAccount.theBalance); Console.ReadKey(); } } }
// program_id overrideInterface.cs // written_by don voils // date_written 1/6/2006 // description This program demonstrates a class // derived from a class that overrides // the base class' implementation // of the interface's method. // using System; namespace theChecking { interface IAccounts { decimal theBalance {set; get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } interface IFee: IAccounts { decimal theFee {get; set;} void CalculateFee(); } class Checking: IFee { private decimal Fee; public decimal theFee { get { return Fee; } set
file:///D|/1/final/BBL0068.html (13 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
{ Fee = value; } } private decimal Balance; public decimal theBalance { get { return Balance; } set { Balance = value; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } public virtual void CalculateFee() { Balance -= Fee; } } class Savings : Checking { public override void CalculateFee() { theBalance *= (1 + theFee); } public decimal ShowInterest() { return (theBalance * theFee); } } class theProgram { static void Main() { Checking checkingAccount = new Checking(); Savings savingsAccount = new Savings(); Console.Clear(); Console.Write("What is the checking account fee? "); checkingAccount.theFee = Decimal.Parse(Console.ReadLine());
file:///D|/1/final/BBL0068.html (14 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
Console.Write("\nWhat was the checking account deposits? "); checkingAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("What was the checking account withdrawals? "); checkingAccount.Withdrawal(Decimal.Parse(Console.ReadLine()));
if(checkingAccount.theBalance <= 500.00m) { checkingAccount.CalculateFee(); Console.WriteLine("\nThe checking account was charged a fee of {0:c}", checkingAccount.theFee); } Console.WriteLine("\nCurrent balance of the checking account is {0:c}.", checkingAccount.theBalance); Console.Write("\n\nWhat is the savings account interest rate? "); savingsAccount.theFee = Decimal.Parse(Console.ReadLine())/100; Console.Write("\nWhat was the savings account deposits? "); savingsAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("What was the savings account withdrawals? "); savingsAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); if(savingsAccount.theBalance >= 500.00m) { Console.WriteLine("\nThe savings account was awarded an interest fee of {0:c}", savingsAccount.ShowInterest()); savingsAccount.CalculateFee(); } Console.WriteLine("\nCurrent balance of the savings account is {0:c}.", savingsAccount.theBalance); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id PeopleChecking.cs // written_by don voils // date_written 1/3/2006 // description This program demonstrates that a class // may be derived from another class as // well as an interface.Notice in the definition // of the derived class that the name of the // base class was listed before the name of // the interface. If this is not done, an // error occurs. // using System;
file:///D|/1/final/BBL0068.html (15 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } public class People { private string PeopleID; private string PeopleName; private string PeopleAddress; private string PeopleCity; private string PeopleState; private string PeopleZipCode; public void setPeopleID(string ID) { PeopleID = ID; } public void setPeopleName(string Name) { PeopleName = Name; } public void setPeopleAddress(string Address) { PeopleAddress = Address; } public void setPeopleCity(string City) { PeopleCity = City; } public void setPeopleState(string State) { PeopleState = State; } public void setPeopleZipCode(string Code) { PeopleZipCode = Code; } public string getPeopleID() { return PeopleID; } public string getPeopleName() { return PeopleName; } public string getPeopleAddress() { return PeopleAddress; } public string getPeopleCity() { return PeopleCity; }
file:///D|/1/final/BBL0068.html (16 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
public string getPeopleState() { return PeopleState; } public string getPeopleZipCode() { return PeopleZipCode; } public override string ToString() { string theValue= "ID: " + PeopleID+ "\n" + "Name: " + PeopleName +"\n" + "Address: " + PeopleAddress + "\n" + "City: " + PeopleCity + "\n" + "State: " + PeopleState + "\n" + "Zip: " + PeopleZipCode + "\n"; return theValue; } } class Checking: People, IAccounts { private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram { static void Main() { Checking newAccount = new Checking(); Console.Write("What is the customer's name? "); newAccount.setPeopleName(Console.ReadLine()); Console.Write("\nWhat is {0}'s ID? ",newAccount.getPeopleName()); newAccount.setPeopleID(Console.ReadLine()); Console.Write("\nWhat is {0}'s address? ",newAccount.getPeopleName());
file:///D|/1/final/BBL0068.html (17 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
newAccount.setPeopleAddress(Console.ReadLine()); Console.Write("\nWhat is {0}'s city? ",newAccount.getPeopleName()); newAccount.setPeopleCity(Console.ReadLine()); Console.Write("\nWhat is {0}'s state? ",newAccount.getPeopleName()); newAccount.setPeopleState(Console.ReadLine()); Console.Write("\nWhat is {0}'s zip code? ",newAccount.getPeopleName()); newAccount.setPeopleZipCode(Console.ReadLine()); Console.Write("\nWhat is {0}'s deposit amount? ",newAccount.getPeopleName()); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is {0}'s withdrawal amount? ",newAccount.getPeopleName()); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.Clear(); Console.WriteLine("{0}",newAccount.ToString()); Console.WriteLine("\nCurrent balance is {0:c}.\n\n",newAccount.theBalance); Console.ReadKey(); } }
}
// program_id theChecking2.cs // written_by don voils // date_written 1/6/2006 // description This program demonstrates the use of a structure // that is derived from an interface. //
using System; namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } struct Checking: IAccounts { public decimal Balance; public decimal theBalance { get { return Balance;
file:///D|/1/final/BBL0068.html (18 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
} } public Checking(decimal theAmount) { Balance = theAmount; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram { static void Main() { Checking newAccount = new Checking(0.00m); Console.Write("What is the deposit amount? "); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is the withdrawal amount? "); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\nThe current balance is {0:c}.\n",newAccount.theBalance); Console.ReadKey(); } } }
// program_id theChecking3.cs // written_by don voils // date_written 1/3/2006 // description This program demonstrates the use of reference // to the interface which acts on the inherited // features of the class derived from the interface. //
using System; namespace theChecking { interface IAccounts { decimal theBalance { get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } class Checking : IAccounts {
file:///D|/1/final/BBL0068.html (19 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram { static void Main() { Checking newAccount = new Checking(); IAccounts theReference = (IAccounts)newAccount; Console.Write("What is the deposit amount? "); theReference.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is the withdrawal amount? "); theReference.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\nThe current balance is {0:c}.\n\n", theReference.theBalance); Console.ReadKey(); } } }
// program_id theChecking.cs // written_by don voils // date_written 1/3/2006 // description This program demonstrates the use of a class // that is derived from an interface. //
using System; namespace theChecking { interface IAccounts {
file:///D|/1/final/BBL0068.html (20 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } class Checking: IAccounts { private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram { static void Main() { Checking newAccount = new Checking(); Console.Write("What is the deposit amount? "); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is the withdrawal amount? "); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\nThe current balance is {0:c}.\n\n",newAccount.theBalance); Console.ReadKey(); } } }
// program_id theMethodTest.cs // written_by don voils // date_written 1/6/2006 // description This program demonstrates how a class // may define interface methods where // both interfaces have a common method // name.
file:///D|/1/final/BBL0068.html (21 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
using System; namespace theMethodTest { interface Interface1 { short theFirst{set;} short theFirstOne(); short theMethod(); } interface Interface2 { double theSecond{set;} double theSecondOne(); double theMethod(); } class theClass: Interface1, Interface2 { short aFirst; public short theFirst { set { aFirst = value; } } double aSecond; public double theSecond { set { aSecond = value; } } public short theFirstOne() { return aFirst; } public virtual short theMethod() { return aFirst; } public double theSecondOne() { return aSecond; } double Interface2.theMethod() { return 10.0 * aSecond; } } class theProgram { static void Main() { theClass theClassReference = new theClass(); Console.Write("What is the short? "); theClassReference.theFirst = short.Parse(Console.ReadLine());
file:///D|/1/final/BBL0068.html (22 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
Console.Write("\n\nWhat is the double? "); theClassReference.theSecond = double.Parse(Console.ReadLine()); Interface1 theRef1 = theClassReference as Interface1; if(theRef1 != null) Console.WriteLine("\nInterface1 reference yields: {0}",theRef1.theMethod()); Interface2 theRef2 = theClassReference as Interface2; if(theRef2 != null) Console.WriteLine("\nInterface2 reference yields: {0:n}",theRef2.theMethod()); Console.WriteLine("\ntheClass reference yields: {0}",theClassReference.theMethod()); Console.WriteLine("\n\n"); } } }
// program_id usingAS.cs // written_by don voils // date_written 1/6/2006 // description This program demonstrates the use of a reference // to an interface acting as a reference to an // instance of a class that is derived from the interface. // It checks using the as operator before acting. //
using System; namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } class Checking: IAccounts { private decimal Balance; public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) {
file:///D|/1/final/BBL0068.html (23 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram { static void Main() { Checking theAccount = new Checking(); IAccounts newAccount = theAccount as IAccounts; if(newAccount != null) { Console.Write("What is the deposit amount? "); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is the withdrawal amount? "); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\nThe current balance is {0:c}.",newAccount.theBalance); } else Console.WriteLine("An error has occurred."); Console.WriteLine("\n\n"); } } }
// program_id usingIS.cs // written_by don voils // date_written 1/6/2006 // description This program demonstrates the use of a reference // to an interface acting as a reference to an // instance of a class that is derived from the interface. // It checks using the is operator before acting. //
using System; namespace theChecking { interface IAccounts { decimal theBalance {get;} void Deposit(decimal theAmount); void Withdrawal(decimal theAmount); } class Checking: IAccounts { private decimal Balance;
file:///D|/1/final/BBL0068.html (24 von 25) [01.12.2007 04:48:54]
Lecture 7 Examples
public decimal theBalance { get { return Balance; } } public Checking() { Balance = 0.00M; } public void Deposit(decimal theAmount) { Balance += theAmount; } public void Withdrawal(decimal theAmount) { Balance -= theAmount; } } class theProgram { static void Main() { Checking theAccount = new Checking(); IAccounts newAccount = (IAccounts) theAccount; if(newAccount is Checking) { Console.Write("What is the deposit amount? "); newAccount.Deposit(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat is the withdrawal amount? "); newAccount.Withdrawal(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\nThe current balance is {0:c}.",newAccount.theBalance); } else Console.WriteLine("An error has occurred."); Console.WriteLine("\n\n"); } } }
file:///D|/1/final/BBL0068.html (25 von 25) [01.12.2007 04:48:54]
Lecture 8: Arrays and Collections
Lecture 8: Arrays and Collections Arrays in C# In your previous course you encountered arrays in C++. The arrays of C# are similar to those found in C++ but there are (as would be expected) several differences. For some similarities: ●
arrays are a fixed number of units of memory arranged sequentially in memory.
●
the number of elements in the array are referred to as the size of the array. (also called the Length which is a readonly property)
●
these units of memory are called elements
●
these elements are accessed by using an integer called the index
●
these elements are represented by the array name followed by [index]
●
the arrays may contain elements that are value types: integers, floats, doubles, structures, strings or any system data type
●
the arrays may contain elements that are references to programmer defined data types
While there are these similarities with C++, there are also differences. In C# arrays are references to objects of the class System.Array. The definition of an array therefore follows a format similar to that of defining an object of a class like the following: dataType[ ] theReference; theReference = new dataType[length];
The first statement above defines theReference but does not define the array. By this is meant that the memory to which theReference is pointing to is not created until the second statement is issued which then defines the associated memory for each of the elements. The above two statements can be put together as in the following statement: dataType[ ] theReference = new dataType[length];
where a reference is being defined to access the elements of the array. This places theReference on the stack and it will contain the address of the first element. The elements of an array that are value types are stored on the stack as in the following graphic:
file:///D|/1/final/BBL0069.html (1 von 3) [01.12.2007 04:48:55]
Lecture 8: Arrays and Collections
While the above graphic shows how arrays of values types are created, it does not show how arrays of reference types are created. That will be discussed in a section below. Each element of the array is initialized upon definition. The value that it is initialized to depends upon the data type. In general the value of each element is initialized to 0 if it is a system numeric data type, it will be initialized to false for Booleans and object types will be initialized to null. For example, it is possible to define an array theCustomerNumber to be an array of the data type int with 1000 elements (the value 1000 is the called the size or length) could be defined as the following: int[ ] theCustomerNumber = new int[1000];
The length of an array can be found by using the Array's public property Length as in: Console.WriteLIne("The length of the array is {0}", theCustomerNumber.Length);
The statement above would return the value of 1000. As with object definition in general, theCustomerNumber is a reference (defined on the stack) to the 1000 elements (since this array is of ints the array elements are defined on the stack) and these units of memory are of data type int. As a result, each element of theCustomerNumber is initialized to 0. See array7.cs. The example above showed an array of integers and an array of doubles but an array may be of any data type including: string[ ] customerName = new string[25]; decimal[ ] unitPrice = new decimal[8]; object[ ] animals = new object[100]; employee[ ] clerks = new employee[13]; invoiceItems[ ] theInvoice = new invoiceItems[33];
where the last three definitions are based upon programmer data types (arrays of reference types to be discussed below.)
file:///D|/1/final/BBL0069.html (2 von 3) [01.12.2007 04:48:55]
Lecture 8: Arrays and Collections
As in C++, the index can only be a non negative integer and the first element begins with 0 for its index. That is theCustomerNumber[0] is the first element of the array. From this it follows that theCustomerNumber[23] is the 24th element and theCustomerNumber[312] is the 313th element of the array theCustomerNumber. Note: The length of a C# array as with C++ may be specified at run time rather than at compile time. For example the following defines a dynamic array: Console.Write ("Enter the number of items to be processed: "); int theNumber = Int32.Parse(Console.ReadLine()); decimal[] itemAmount = new decimal[theNumber];
See array8.cs.
file:///D|/1/final/BBL0069.html (3 von 3) [01.12.2007 04:48:55]
System.Array Class
System.Array Class Introduction to the Fields and Methods of the Array Class Standard C++ has the Standard Template Library to provide a collection of useful classes, functions and pointers. To approximate the utility of the STL, C# has the class System.Array. As stated above, arrays in C# are derived from the System.Array class that provides several methods and data members that can be used when working with arrays. Some of the more common ones are listed below.
Open table as spreadsheet Method/Data Member
Description
BinarySearch()
Public static method that searches a one-dimensional sorted array to find an element value in the array.
Clear()
Public static method that sets a range of elements to zero or null
Clone()
Creates a copy of the array as an array of System.Objects
Copy()
Overloaded public static method that copies the values of the elements of a section of one array to another.
Copy(theArray, otherArray, theNumber)
A static method that copies theNumber of elements of theArray to otherArray.
CopyTo(otherArray,theNumber)
A non-static method that copies theNumber of elements from theArray to otherArray
CreateInstance()
Overloaded public static method that instantiates a new instance of an array.
GetLength()
Returns the length of a given dimension in a square array
IndexOf()
Returns the index of the first occurrence of a value
Length
Gets the number of elements in the specified dimension of the array
Rank
Returns the number of dimensions of the array.
Reverse()
Reverses all of the elements in the array using the ordering system of the array data type.
Sort()
Sorts the elements in an array in terms of the ordering system for the array data type.
For an example to use the attribute: Length see array5.cs.
Copying Arrays When copying one array to another, the array that will receive the element values must be defined prior to the process of copying. That is, if the array theNumbers is being copied to the array numbersCopy, then numbersCopy could be defined as in the following example using the Length data member of the Array class: int[] numbersCopy = new int[theNumbers.Length];
The most common way to copy arrays in C/C++ was to iterate through an array using a for() loop. The same file:///D|/1/final/BBL0070.html (1 von 3) [01.12.2007 04:48:56]
System.Array Class
process could still be used in C# as in the following example: for (int i = 0; i < theNumbers.Length; i++) { numbersCopy[i] = theNumbers[i]; }
However, instead of the above process, the CopyTo() method of the Array class could be used to copy the contents of the original array into another array. The method CopyTo() has two arguments: 1) the name of the array being copied to and 2) the starting index of the original array. For example, the above code could be written as the following: theNumbers.CopyTo(numbersCopy, 0);
See array11.cs. This process could also be accomplished using the System.Array class' static method called Copy(). The arguments include: 1) the original array, 2) the array being copied to and 3) the length of the original array. For example: Array.Copy(theNumbers, numbersCopy, theNumbers.Length);
See array12.cs. Finally, you can use the Clone() method of the Array class to create an array and copy it all in one statement. int[ ] numbersCopy = (int[ ])theNumbers.Clone();
Notice the explicit type conversion in the statement above which is needed to convert the cloned array of System. Object into an array of integers. See array13.cs.
Sorting Arrays Sorting data is one of the most important computing applications. Intense research efforts have gone into finding the fastest, most efficient sorting algorithms. The Bubble Sort uses nested loops to make several passes through the array. Each pass compares successive pairs of elements (0,1), (1,2), (2,3), (3,4). If both elements of the pair have equal values or if the first is less than the second, nothing happens. However if the second value is less than the first, then the values are swapped in the array. The larger values sink to the bottom while the smaller values bubble to the top. For example: public void BubbleSort(int[] arraySort) { for (int pass = 0; pass < arraySort.Length; pass++) { for (int i = 0; i < arraySort.Length - 1; i++) { if (arraySort[i] > arraySort[i + 1]) { Swap(arraySort, i);
file:///D|/1/final/BBL0070.html (2 von 3) [01.12.2007 04:48:56]
System.Array Class
} } } } public void Swap(int[] arraySwap, int index) { int temp; temp = arraySwap[index]; arraySwap[index] = arraySwap[index + 1]; arraySwap[index + 1] = temp; }
The Bubble Sort is easy to code but it runs slow which causes a serious problem when sorting large arrays. The .NET Framework includes a built-in Sort() method that implements a high-speed sort. Instead of writing the BubbleSort() and the Swap() methods, the Array class' static method Sort() can be called and an array can be passed as an argument like in the following. Array.Sort(theArray);
For an example see sort1.cs. In this example, note that there was no need for an explicit type conversion from an array of System.Object to an array of integers to do the sort.
Searching Arrays: Linear Search A linear search will loop through an array until it finds the value being searched for. If you have 100 elements in the array and the value you are looking for is the 98th element, the search will make 98 comparisons. A linear search works well for small or unsorted arrays. See search1.cs.
Searching Arrays: Binary Search A binary search uses a divide and conquers approach. It is an efficient, high-speed technique that works well on large sorted arrays. The binary search eliminates half the array elements being searched after each comparison. Again, if the element you are searching for is the 98th element, the binary search will only need to make 6 comparisons. The .NET Framework includes a built-in BinarySearch() method that implements a high-speed search on sorted arrays. Instead of writing a binary search method, the program should call the Array class' static method BinarySearch(). This method is overloaded. One of the implementations has as one of the arguments the array to be searched and the other argument is the value being searched for. The method returns the position in the array it found the value searched for. If it was not found, then a negative number is returned. As in the following: thePosition = Array.BinarySearch(theSearchedArray,theValuetoFind);
For an example, see: search2.cs. This was an example using an array with numbers as elements. It is also possible to use these same Array methods with arrays of strings. See search3.cs.
file:///D|/1/final/BBL0070.html (3 von 3) [01.12.2007 04:48:56]
Initialization and Assignment of Arrays
Initialization and Assignment of Arrays Initialization of Array Elements The elements of arrays can be assigned values as the program runs as in the following: string[] employeeName = new string[100]; employeeName[0] = "George Washington"; employeeName[1] = "Thomas Jefferson"; employeeName[2] = "John Adams"; employeeName[3] = "Theodore Roosevelt"; employeeName[4] = "Abraham Lincoln"; …
followed by Console.WriteLine("The name of the first US President was {0}.", employeeName[0]);
as was done in the example: search3.cs. Instead arrays can be initialized when used in loops as in the following: decimal[] unitPrice = new decimal[10]; for(int index=0; index < 10;++index) { Console.Write("\nWhat is the unit price of unit {0}? ", index+1); unitPrice[index] = Decimal.Parse(Console.ReadLine()); }
and then these lines could be followed with code like the following: decimal totalPrice = 0.00M; Console.WriteLine("\tItem\tPrice"); for(int index=0; index < unitPrice.Length;++index) { Console.WriteLine("\t{0}\t{1:c} ",index+1, unitPrice[index]); totalPrice += unitPrice[index]; } Console.WriteLine("\n\tTotal\t{0:c}",totalPrice);
See array1.cs
Assignment and Arrays Suppose that two arrays are defined of the string type and the same size as in the following examples: string[] employeeName = new string[5]; file:///D|/1/final/BBL0071.html (1 von 2) [01.12.2007 04:48:56]
Initialization and Assignment of Arrays
string [] employeeName2 = new string[5];
Further assume that the array emploiyeeName is initialized and then the code contains the following statement: employeeeName2 = employeeName;
When this assignment is made all of the values for the elements of employeeName have been assigned to be the values of the elements of the array employeeName2 Next suppose that the elements of the array employeeName2 are changed. The question should be what happens to the values of the elements of the first array. The answer is that the values of the first array are also changed. For example see: employeeName1.cs So the last example had arrays of the string type. The question should then arise as to whether using arrays: employeeNumber and employeeNumber2 to be arrays of the system data types, would this make a difference? The answer is no. That is if non-string array: employeeNumber is assigned to the non-string array employeeNumber2 and the elements of employeeNumber2 are changed, then the elements of the array employeeNumber are changed as well. See employeeNumber1.cs What should be done instead of using assignment is to use the CopyTo() method of the Array class. See employeeNumber2.cs. Notice in this case the elements of the two arrays are different places in memory because if the values of the elements of one array are changed, then the values of the elements of the other array are not changed. Instead of the method: CopyTo() the static method Copy() could be used instead.
file:///D|/1/final/BBL0071.html (2 von 2) [01.12.2007 04:48:56]
List Definition and Initialization of Arrays
List Definition and Initialization of Arrays As in C++ an array may be defined with a list of the element values. However the C# code is slightly different. For example the traditional array definition may be followed by the list as in the following: int[] theUnitNumbers = new int[6] {23, 42, 123, 42, 13, 123};
This definition would define the array referenced by theUnitNumbers that contains the values 23, 42, 123, 42, 12 and 123 respectively. Note: Unlike C++, when a list definition is used, then the size of the array must be the same as the number of values in the list definition or a compiler error occurs. There is another approach to using a list definition. The list may appear without the new statement as in the following: decimal[] thePrices = {34.23m, 532.43m, 335.45m, 625.34m};
This statement would define the array: thePrices with four decimals elements with the values: 34.23, 523.43, 335.45 and 625.34 respectively. The size of the array: thePrices is calculated from the number of elements in the specified list. For an example of each of the definitions above see list1.cs The example above demonstrated list definition using int and decimal arrays. It is also possible to have a string array with a list definition as in the following: string[] employeeName = { "George Washington", "Thomas Jefferson", "John Adams","Theodore Roosevelt", "Abraham Lincoln"};
Link to list3.cs and view this example. The values in a list do not have to be constant values assigned at compile time. That is they may be calculated at run time as in the following definition: Random theValues = new Random(); int[] theNumbers = new int[5] { theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10) };
See list2.cs. The examples so far have shown arrays of system data types. It is possible to create arrays of structures as well. As may be recalled, instances of structures are also value types. Therefore the same rules apply for structures as with the system data types. The interesting feature for structures is that list definitions may use the default
file:///D|/1/final/BBL0072.html (1 von 2) [01.12.2007 04:48:57]
List Definition and Initialization of Arrays
constructor: bankAccount[] theAccount2 = { new bankAccount(), new bankAccount(), new bankAccount() };
or non default constructors bankAccount[] theAccount3 = { new bankAccount("1234", "The first One",100.00m), new bankAccount("1235", "The Second One",200.00m), new bankAccount("1236","The Third One",300.00m)};
See bank9.cs for this example. When observing the output of theAccount2[] array, notice that the balance is 0.00.
file:///D|/1/final/BBL0072.html (2 von 2) [01.12.2007 04:48:57]
Arrays of Class Objects or Structure Instances
Arrays of Class Objects or Structure Instances Arrays of Class Objects In each of the examples above, the arrays contained elements of system data types or structures i.e. arrays of value types. It is also possible to defined arrays of programmer data types. In this case it is necessary to not only instantiate the array reference but also to instantiate each of the elements as well. The elements in this case are references to objects as shown in the following graphic:
For example suppose a program had the following class defined: public class customer { private string name; private decimal amountOwed; public customer() { name = ""; amountOwed=0.00M; } public void setName(string theName) { name = theName; }
file:///D|/1/final/BBL0073.html (1 von 2) [01.12.2007 04:48:57]
Arrays of Class Objects or Structure Instances
public void setAmountOwed(decimal theAmount) { amountOwed = theAmount; } public string getName() { return name; } public decimal getAmountOwed() { return amountOwed; } }
An array myCustomers[] of three objects of type customer could be defined as the following: customer[] myCustomers = new customer[3];
What is different with programmer data types from system data types is that each of the elements of the array myCustomer must be instantiated as in the following statement: myCustomers[index] = new customer();
See array6.cs. In the example above, the fields of a class were a single instance of some system data type. In C# a class may also have arrays as fields as well as simple variables. For example see bank7.cs.
Arrays of Structure Instances The examples above dealt with arrays of class objects. It is also possible to have arrays of structure instances as well. Using the example array6.cs above but changing from a class to a structure as well as eliminating the default constructor, it is possible to have an array of structure instances. See array14.cs
file:///D|/1/final/BBL0073.html (2 von 2) [01.12.2007 04:48:57]
Using foreach() and Enumerated Types with Arrays
Using foreach() and Enumerated Types with Arrays Arrays and the foreach() Loop Previously when C# loops were discussed, the notes mentioned that there was a loop called foreach(). Now that arrays have been introduced, this loop has more meaning. For example the following for() loop that appeared in a previous example: decimal[] unitPrice = new decimal[10]; Console.WriteLine("\tItem\tPrice"); for(int index=0; index < unitPrice.Length; ++index) { Console.WriteLine("\t{0,2} {1,15:c} ",index+1, unitPrice[index]); totalPrice += unitPrice[index]; } Console.WriteLine("\t {0,12}","------------"); Console.WriteLine("\tTotal {0,12:c}",totalPrice); Console.WriteLine("\n\n");
can be rewritten as the following using the foreach() loop: decimal[] unitPrice = new decimal[10]; Console.WriteLine("\tItem\tPrice"); index= 0; foreach(decimal price in unitPrice) { Console.WriteLine("\t{0,}\t{1,15:c} ",index+1, price); totalPrice += price; counter++; } Console.WriteLine("\t {0,12}","------------"); Console.WriteLine("\tTotal {0,12:c}",totalPrice); Console.WriteLine("\n\n");
To see this change, view: array2.cs. When using an array in a foreach() loop, the loop must go from the first element to the last element. If a program needs to iterate from the last to the first, then a for() loop must be used. Further, if the elements are used within the body of the loop, then their values may not be changed. If they need to be changed, then a for() loop must be used.
Arrays and Enumerated Data Types If the program had the following enumerated data type defined, enum Months {January,February,March,April, May,June,July,August,September, October,November,December}
then the code with a loop above could have been written as the following:
file:///D|/1/final/BBL0074.html (1 von 2) [01.12.2007 04:48:58]
Using foreach() and Enumerated Types with Arrays
decimal[] monthlySales = new decimal[12]; for(Months theMonth=Months.January; theMonth<=Months.December; ++theMonth) { Console.Write("\nWhat is the sales for the month {0}? ", theMonth.ToString()); monthlySales[(int)theMonth] = Decimal.Parse(Console.ReadLine()); }
See array3.cs.
file:///D|/1/final/BBL0074.html (2 von 2) [01.12.2007 04:48:58]
Multidimensional Arrays
Multidimensional Arrays As with C++, C# has what are called rectangular multidimensional arrays. An array that consists of a single list or sequence of memory locations is called a single-dimensional array. An array that consists of multiple lists (i.e. multiple sequences of memory locations) is called a multidimensional array. This type of an array has more than one index. Multidimensional arrays of specific sizes are often referred to by the number of the controlling indexes. That is, if there are two controlling indexes, then the array is referred to as a two-dimensional array. If there are three indexes, then it is referred to as a three-dimensional array etc. For example the graphic below depicts a three-dimensional value type array:
Notice in the above definition that the notation for C# multidimensional arrays is different from a C++ multidimensional array. i.e. theReference[1,0] rather than theReference[1][0]. Consider a shelf full of books as a single-dimensional array. The shelf is the array dimension and a book is an element in the array. A bookcase is more like a multidimensional array, with the shelves being one dimension on the array, and the books on each shelf being another dimension. For example, you could refer to the third book on the second shelf. Two-dimensional arrays are often used to display a table of values with one dimension representing the rows and the other dimension representing the columns. Three-dimensional arrays are often used to display a graph with x, y and z coordinates. An array of even greater dimensions might be used to display a set of values, similar to a structure. Regardless of the number of dimensions, the elements are arranged sequentially in memory. When declaring, initializing and accessing elements of a multidimensional array, a comma is used to separate the list of indexes. The following: decimal [,] accountTotals = new decimal[12,100];
file:///D|/1/final/BBL0075.html (1 von 3) [01.12.2007 04:48:59]
Multidimensional Arrays
would define a two-dimensional array of decimals. Note that this definition is different from the C++ definition where a pair of brackets is used. For example a 2-dimensional int array table could be declared and instantiated as in the following example: int[,] table = new int[3,4];
While the above would assign 0 to each element, additional values could be assigned to the multidimensional array table's elements as in the following: table [0, 0] = 1; table [0, 1] = 2; table [0, 2] = 3; table [0, 3] = 4; table [1, 0] = 5; table [1, 1] = 6; table [1, 2] = 7; table [1, 3] = 8; table [2, 0] = 9; table [2, 1] = 10; table [2, 2] = 11; table [2, 3] = 12;
The above statements could be combined into a declaration and a list initialization of the multidimensional array as in the following: int[,] table = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
which would define and initialize a 3 x 3 array of integers. Another example would be the following: int[,] theNumbers = {{23,43,12}, {52.23,43},{53,234,43},{44,23,44}};
which defines a 3 x 4 dimensional int array where each element is initialized. To bring data into this array, the following code could be used: int[,] theNumbers = new int[4,3]; for(int counter1=0;counter1 < 4;++counter1) for(int counter2=0;counter2 < 3; ++counter2) { Console.Write("What is theNumber[{0}][{1}]? ", counter1+1,counter2+1); theNumbers[counter1,counter2] = Int32.Parse(Console.ReadLine()); }
See array4.cs for an example of this use of multidimensional arrays. The Array property Length does not apply to multidimensional arrays since it would not be appropriate to add all of the individual dimensions together. When using a multidimensional array, it would be more appropriate to provide the length of each individual dimension. To accomplish this, the class Array has a method. GetLength() whose argument is the particular dimension. Keeping in mind that arrays are zero-based, the value 0 is used as the argument to define the 1st dimension, the value 1 is used as the argument to define the 2nd dimension etc
file:///D|/1/final/BBL0075.html (2 von 3) [01.12.2007 04:48:59]
Multidimensional Arrays
For example the above multidimensional array: theNumbers[,] could output the data in each element as in the following code: for (int i = 0; i < theNumbers.GetLength(0); i++) { for (int j = 0; j < theNumbers.GetLength(1); j++) { Console.WriteLine(theNumbers[i, j]); } }
See array9.cs.
file:///D|/1/final/BBL0075.html (3 von 3) [01.12.2007 04:48:59]
Jagged Arrays
Jagged Arrays Another contrast with C++ arrays is that C# has what are called Jagged Arrays. A jagged array can be thought of as an array of arrays. In this case, each array can be of a different length. For example, it is possible to declare and instantiate a jagged array of 3 arrays: int[][] array3 = new int[3][];
Values can then be assigned to the jagged array elements by using a list instantiation for each element as in the following (remember that the following format is only one of the three ways to use a list instantiation): array3[0] = new int[] {10, 25}; array3[1] = new int[] {34}; array3[2] = new int[] {42, 53, 65, 7};
The values of this jagged array can be accessed as in the following: for (int i = 0; i < array3.Length; i++) { for (int j = 0; j < array3[i].Length; j++) { Console.Write(" " + array3[i][j] + ""); } Console.WriteLine(); }
See array10.cs.
file:///D|/1/final/BBL0076.html [01.12.2007 04:48:59]
Passing Arrays to Method
Passing Arrays to Method Arrays in C# may be passed to methods in the following three ways: ●
An array element may be passed to the method either by value or by reference using either ref or out.
●
An array reference may be passed to the method.
●
A variable number of elements may be passed to the method by using the keyword: param
Passing an Array Element To pass an array element, specify the name of the array along with the index in brackets in the method call but only specify a variable in the method definition. Array elements are passed by value. Therefore when the value of an array element is changed, only a copy of the element is changed. For example the method definition would be like the following: static void ModifyElement(int number) { string theOutput = new string(); theOutput += " Value received in Modify Element: " + number + "\n"; number *= 2; theOutput += " Value calculated in Modify Element: " + number + "\n"; Console.WriteLine(theOutput); }
while the method call could be like the following: ModifyElement(numbers[3]);
and the 3rd element would be unchanged inside of the method. See arrayMethods1.cs. Notice that the value of the array is unchanged after the method is called. While the array element was not changed by the method, if it had been passed using the ref or out modifiers, then the value of the element passed to the method could have been changed.
Passing an Array Reference The array reference may be passed to the method (In this case the individual elements of the array are not passed to the method but they can be accessed because the reference will point to the location of the elements of the array in memory. This saves processor time and memory space.) To pass the reference, the name of the array appears in the method call without the brackets and in the method definition, the brackets would appear. In this case, when the value of an array element is changed within the method, the value of the element is permanently changed. For example the method definition would be like the following: static void ModifyArray(int[] numberList) { for(int i = 0; i < numberList.Length; i++) { numberList[i] *= 2; } }
file:///D|/1/final/BBL0077.html (1 von 3) [01.12.2007 04:49:00]
Passing Arrays to Method
while the method call would be like the following: ModifyArray(numbers);
See arrayMethods2.cs.
Using params to Pass an Array to a Method A variable number of elements may be passed to the method by using the keyword: params as in the following definition: outputDataType theFunction(params dataType[] theArray) { }
This type of a method is referred to as a variadic method. Using the keyword param, it is possible to define a method as if the argument will be an array but when the method is called, either an array may be passed or a sequence of variables may be listed. For example the static method: theProduct() could be defined as in the following: static int theProduct(params int[] theArray) { int theProduct = 1; foreach(int index in theArray) theProduct *= index; return theProduct; }
A foreach() loop is used in this example because a for() loop would not work in this case. One call to the method could be using an array as in the following array: int[] theNumbers = {4, 24, 43, 53};
In this case the call would be: int theOutput = theProduct(theNumbers);
Or the call could be: int theOutput = theProduct(4,24,43,53);
Both calls would result in the same output. See paramsMethod.cs.
file:///D|/1/final/BBL0077.html (2 von 3) [01.12.2007 04:49:00]
Passing Arrays to Method
file:///D|/1/final/BBL0077.html (3 von 3) [01.12.2007 04:49:00]
Indexers
Indexers Indexers are similar to properties. They enable a program to access a field of a class that is an array as if the object was itself an array. While they are handled like an array, the fields and methods of Array may not be used on an indexer other than the [ ] operator. For example count can not be used with an indexer. The class: bankAccount in the example: bank7.cs contains a data member: private string[] customerName = new string[2];
Using indexers enables the programmer to access this data member using the [ ] operator. This is done by defining an indexer property like the following general form: dataType this [dataType argument] {get; set;}
In this construct the this keyword refers to the object in which it is defined. Therefore adding the following indexer to the class bankAccount: public string this[int index] { get { // The following should be protected by // an exception to prevent exceeding // the number of elements in the array. // return customerName[index]; } set { // The following should be protected by // an exception to prevent exceeding // the number of elements in the array. // ++numberNames; customerName[index] = value; } }
Notice the use of the this above. It will be referring to the object which is using the indexer. Note: While in the definition above the indexer has both a get and a set, it is also possible to have only a get which would make the indexer as read only or just a set which would therefore make the indexer a write only. Note: While properties may be static, indexers can not be made static. Note: Indexers may use a non-numeric index although arrays may not. Note: Indexers may not be used with ref or out although an array element may. Adding the above definition permits changing the following code: file:///D|/1/final/BBL0078.html (1 von 3) [01.12.2007 04:49:01]
Indexers
for(int index = 0; index < 2; ++ index) { Console.Write("\nWhat is the account number {0}'s customer number {1}'s name? ", theAccount.getCustomerID(),index+1); theAccount.setName(Console.ReadLine()); if(theAccount.getNumberNames()>=2) break; Console.Write("\nIs there another name? Y/N "); char theResponse = Char.Parse(Console.ReadLine()); if((theResponse != 'y') && (theResponse != 'Y')) break; }
to the code below: for(int index = 0; index < 2; ++ index) { Console.Write("\nWhat is the account number {0}'s customer number {1}'s name? ", theAccount.getCustomerID(),index+1); theAccount[index] = Console.ReadLine(); if(theAccount.getNumberNames()>=2) break; Console.Write("\nIs there another name? Y/N "); char theResponse = Char.Parse(Console.ReadLine()); if((theResponse != 'y') && (theResponse != 'Y')) break; }
Compare the two statements in red in the two examples above. Further changing the following method: public override string ToString() { string theValue; string theNames = "Customer Names:\n"; for(int index = 0; index < numberNames;++index) theNames += " " + customerName[index] + "\n"; theValue = "Account ID: "+ customerID + "\n" + theNames + "Balance: $" + theBalance + "\n"; return theValue.ToString (); }
to the method: public override string ToString() { string theValue; string theNames = "Customer Names:\n"; for(int index = 0; index < numberNames;++index) theNames += " " + this[index] + "\n"; theValue = "Account ID: "+ customerID + "\n" + file:///D|/1/final/BBL0078.html (2 von 3) [01.12.2007 04:49:01]
Indexers
theNames + "Balance: $" + theBalance + "\n"; return theValue.ToString (); }
Compare the two red statements above. These changes would also implement the use of the indexer there as well. Notice how the class had a field: numberNames which acts like the Array field count. See bank8.cs. It is possible to use indexer in interfaces as well as properties. For example the following could be an interface with an indexer: interface IRawMaterials { bool this [int index] {get; set;} } class Manufactured : IRawMaterials { public bool this [int index] { get{....} set{....} } ....... }
file:///D|/1/final/BBL0078.html (3 von 3) [01.12.2007 04:49:01]
The Collections Interfaces
The Collections Interfaces The System namespace contains the namespace: Collections. To use this namespace requires the following statement: using System.Collections;
This namespace contains several useful interfaces to include:
Open table as spreadsheet Interface
Description
IEnumerable
Enumerates through a collection using a foreach() statement.
ICollection
Implementated by all collections to provide the CopyTo() method as well as the Count, ISReadOnly, ISSynchronized and SyncRoot properties.
IComparer
Compares two objects held in a collection so that the collection can be sorted.
IList
Used by array-indexable collections.
IDictionary
For key/value-based collections such as Hashtable and SortedList.
IDictionaryEnumerator
Allows enumeration with foreach() of a collection that supports IDictionary.
Some of these interfaces and their properties will be used in later discussions. However these lectures do not contain a complete discussion of these topics The next few sections of this lecture addresses the Collections: ●
the ArrayList Class
●
the Hashtable Class
●
the SortedList Class
●
the ADT Queue
●
the ADT Stack
file:///D|/1/final/BBL0079.html [01.12.2007 04:49:01]
The ArrayList
The ArrayList Introduction to ArrayList One of the problems with arrays in C# as in most languages is that the dimension of the array must be specified when the array is instantiated. However C# provides a class called ArrayList that enables the programmer to use this type of an array without knowing before hand how many elements there will be. This class is in the namespace: System.Collections and therefore the statement: using System.Collections;
must be included at the top of the program in order to use this class. While all of the data stored in an ArrayList must be of the same data type, it is possible to continue to add elements without specifying how many will be used during the execution of the program. The ArralyList property: Count keeps track of the number of elements. This amount is less than Capacity which is the maximum number of elements that the ArrayLists may contain. However, as the value of Count reaches Capacity, the value of Capacity is automatically increased. Some of the properties and the methods of ArrayList are listed below:
Open table as spreadsheet Method/Data Member
Description
Capacity
Public property to get or set the number of elements in the ArrayList
Count
Public property to get the number of elements currently in the ArrayList
[]
This operator acts on an ArrayList as it does on an array.
Add()
Public method to add the argument to the end of the ArrayList
BinarySearch()
Method that uses a binary search in terms of an ordering system for the data type to find the argument in a sorted ArrayList
Clear()
Method that removes all elements from the ArrayList
CopyTo()
Method that copies the elements from the ArrayList to a one-dimensional array of the same data type
Insert(location, value)
Method to insert value into position location into an ArrayList
Remove()
Method that removes the first occurrence of the argument in the ArrayList
RemoveAt()
Method that removes an element at a specific index in the ArrayList
Reverse()
Method that reverses the order of the elements currently in the ArrayList using the ordering system of the elements' data type.
Sort()
Method that sorts the elements in the ArrayList using the ordering system of the elements' data type.
ToArray()
Copies the elements of the ArrayList to a new array.
Since ArrayList is a class, the definition of an ArrayList is like the following: ArrayList theCustomers = new ArrayList(); file:///D|/1/final/BBL0080.html (1 von 3) [01.12.2007 04:49:02]
The ArrayList
char theResponse = new char(); string theName; int counter = 0; do { ++counter; Console.Write("\nEnter Customer {0}'s name: ",counter); theName = Console.ReadLine(); theCustomers.Add(theName); Console.Write("\n\nContinue? (Y/N) "); theResponse = Char.Parse(Console.ReadLine()); }while((theResponse=='y') || (theResponse=='Y')); for(int index = 0; index < theCustomers.Count;++index) { Console.WriteLine("\nCustomer number {0} is {1}.", index+1,theCustomers[index]); }
The code above will input any number of names and then output the names using the ArrayList operator [ ] and the property: Count which contains the number of elements in the ArrayList. For example see arraylist1.cs. One of the methods for ArrayList that might be useful for the above program would be: Sort() as in: theCustomers.Sort();
After the ArrayList is sorted, the BinarySearch() method may be used fo find an element of the ArrayList as in the following: theCustomer.BinarySearch(theName);
It is also possible to insert a new element into a specified position: theCustomer.Insert(theLocation,theNewName);
When this is done, all of the elements in the ArrayList from theLocation to the end of the ArrayList are moved one position down the ArrayList and theNewName is inserted into position: theLocation. See arraylist2.cs. As can be seen from the discussion and examples above, an ArrayList is in general a better choice than an array for the following reasons: ●
the number of elements in an ArrayList may be increased during the execution of the program.
●
elements may be removed from an ArrayList.
●
elements may be inserted in an ArrayList at any point including the beginning and the end
Implementing IComparable The data that was stored in the ArrayList defined in the example: arraylist2.cs above contained elements that could be compared and therefore could be sorted. That is the elements were strings. Since strings implement the file:///D|/1/final/BBL0080.html (2 von 3) [01.12.2007 04:49:02]
The ArrayList
method CompareTo(), they may therefore be sorted. However not all data instances may be compared and therefore the Sort() method would not work on that data type. To overcome this difficulty, the class whose objects are to be stored into an ArrayList and then sorted must implement the interface IComparable and implement the method: CompareTo(). For example: public class Employee: IComparable { private string EmployeeID; private string EmployeeName; public string ID { get { return EmployeeID; } set { EmployeeID = value; } } public string Name { get { return EmployeeName; } set { EmployeeName = value; } } public override string ToString() { string theEmployee = "Employee ID: " + ID + "\nEmployee Name: " + Name; return theEmployee; } public int CompareTo(Object theObject) { Employee AnEmployee = (Employee) theObject; return this.EmployeeID.CompareTo(AnEmployee.EmployeeID); } }
See arraylist3.cs.
file:///D|/1/final/BBL0080.html (3 von 3) [01.12.2007 04:49:02]
The Hashtable Class
The Hashtable Class The Hashtable class is similar to the ArrayList class. Both of these classes require that the Collection namespace be included in the program. That is at the top of a program using HashTables must appear the following statement: using System.Collections;
As with the ArrayList, elements may be added to an instance of a Hashtable. The major difference between these two classes is that the index of an ArrayLIst must be an integer while the index of a Hashtable may be any data type. For example the index could be a string. The index is a property called: Key and the property that the Key references to is the property Value of the Hashtable instance. No two elements of a Hashtable instance may have the same Key. Before a Key is submitted to a Hashtable instance, the Hashtable methods ContainsKey() or Contains() should be used to determine whether a Key has already been used. The class Hashtable has several properties and methods some of which are listed in the table below:
Open table as spreadsheet DataMember/Method
Description
Key
Property that permits get and set on the index
Value
Property that permits get and set on the instance.
Add(theKey,theValue)
A method that adds an instance to the Hashtable with a Key of theKey and a Value of theValue.
Contains(theKey) and ContainsKey (theKey)
A method that determines whether the Hashtable instance contains theKey as one of the instance's Keys.
ContainsValue(theValue)
A method that determines whether the Hashtable instance contains theValue as one of the instance's Values.
CopyTo(theArray)
Copies the Hashtable instance to one-dimensional array.
Remove(theKey)
Removes an element from the Hashtable instance whose Key is theKey.
For example suppose that theItem is an instance of Hashtable as in the following statement. In this example, the Key is the string "ID123" and the Value for this Key is "Monarch doors". Then code like the following can be used to add a new element to theItem as in the following example: Hashtable theItem = new Hashtable(); string theID = "ID123"; theItem[theID] = "Monarch Doors"; Console.WriteLine("The key is {0} and the value is {1}", theID, theItem[theID]);
Note that since theItem is an instance of the class Hashtable rather than an array of instances, there is no use of the [ ] operator in the definition of theItem. file:///D|/1/final/BBL0081.html (1 von 2) [01.12.2007 04:49:03]
The Hashtable Class
Using the Hashtable method: Add() the following could also be used to add elements to the Hashtable instance. theID = "ID124"; theItem.Add(theID, "Kitchen Maid Cabinets");
For example see hashtable2.cs. In addition suppose that a program was needed that required the customer ID and the customer name to be related to each other. A foreach() could be used with a Hashtable instance in the following manner: Hashtable theCustomer = new Hashtable(); theCustomer["10021"] = "George Washington"; theCustomer["10022"] = "Thomas Jefferson"; theCustomer["10034"] = "John Adams"; theCustomer["10044"] = "John Quincy Adams"; foreach (DictionaryEntry element in theCustomer) { string ID = (string)element.Key; string theName = (string)element.Value; Console.WriteLine("Customer ID {0} is customer {1}\n", ID, theCustomer[ID]); }
Notice how the class DictionaryEntry was used in the foreach statement to iterate through the Hashtable: theCustomer. Notice further the use of the keywords: Key and Value. See hashtable1.cs.
file:///D|/1/final/BBL0081.html (2 von 2) [01.12.2007 04:49:03]
The SortedList class
The SortedList class Another example of a Collection is the SortedLIst class. This class is similar to the Hashtable class except that as the elements are added to the instance, they are sorted with respect to the Key. In addition the class SortedList also has properties and methods similar to those for the class Hashtable. As with the following example: SortedList theCustomer = new Hashtable(); theCustomer["10021"] = "George Washington"; theCustomer["10044"] = "John Quincy Adams"; theCustomer["10034"] = "John Adams"; theCustomer["10022"] = "Thomas Jefferson"; theCustomer.Add("10040", "Abraham Lincoln"); foreach (DictionaryEntry element in theCustomer) { string ID = (string)element.Key; string theName = (string)element.Value; Console.WriteLine("Customer ID {0} is customer {1}\n", ID, theCustomer[ID]); }
The output will be the following: Customer ID 10021 is customer George Washington Customer ID 10022 is customer Thomas Jefferson Customer ID 10034 is customer JohnAdams Customer ID 10040 is cusotmer Abraham Lincoln Customer ID 10044 is customer John Quincy Adams
See SortedList1.cs.
file:///D|/1/final/BBL0082.html [01.12.2007 04:49:03]
Queues and Stacks
Queues and Stacks In C++ the Standard Template Library contained the definitions of queues, stacks and other ADTs. Since these ADTs are so important to programming, when C# was implemented these ADTs were included as well. The Queue and Stack classes are contained in the namespace: System.Collections and therefore at the top of a program that is going to utilize these classes must include the following statement: using System.Collections;
Queue Class Some of the attributes and methods of the Queue class are:
Open table as spreadsheet Method/ Attribute
Description
Count
Public attribute that gets the number of elements in the Queue.
Clear
Removes all objects from the Queue.
Clone()
Creates a shallow copy
Contains()
Determines if an element is in the Queue
CopyTo()
Copies the Queue elements to an existing one-dimensional array.
Dequeue()
Removes and returns the object at the beginning of the Queue.
Enqueue()
Adds an object to the end of the Queue.
GetEnumerator ()
Returns an enumerator for the Queue.
Peek()
Returns the object at the beginning of the Queue without removing it.
ToArray()
Copies the elements to a new array.
For an example of using the Queue class see: queue1.cs.
Stack Class Some of the attributes and methods of the Stack class are:
Open table as spreadsheet Method/ Attribute
Description
Count
Public attribute that gets the number of elements in the Stack.
Clear
Removes all objects from the Stack.
Clone()
Creates a shallow copy
Contains()
Determines if an element is in the Stack
file:///D|/1/final/BBL0083.html (1 von 2) [01.12.2007 04:49:04]
Queues and Stacks
CopyTo()
Copies the Stack elements to an existing one-dimensional array.
Pop()
Removes and returns the object at the top of the Stack.
Push()
Adds an object to the Stack
GetEnumerator ()
Returns an enumerator for the Stack.
Peek()
Returns the object at the top of the Stack without removing it.
ToArray()
Copies the elements to a new array.
For an example of using the Stack class see: stack1.cs.
file:///D|/1/final/BBL0083.html (2 von 2) [01.12.2007 04:49:04]
Lecture 8 Examples
Lecture 8 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
array1.cs
Demonstrates arrays where the elements are initialized by input from the keyboard.
array2.cs
Demonstrates arrays in a foreach() loop.
array3.cs
Demonstrates enumerated types and arrays.
array4.cs
Demonstrates multidimensional arrays.
array5.cs
Demonstrates how to use of the Array attribute Length.
array6.cs
Demonstrates arrays of class objects.
array7.cs
Demonstrates how the elements of a system data type are initialized.
array8.cs
Demonstrates how the elements of a system data type's elements are initialized.
array9.cs
Demonstrates how to use multidimensional arrays using the GetLength property.
array10.cs
Demonstrates how to use jagged arrays.
array11.cs
Demonstrates how to use the Array method CopyTo() to copy one array to another‥
array12.cs
Demonstrates the static Array method Copy() to copy one array to another.
array13.cs
Demonstrates the Array method Clone() to define the array being copied to and to copy one array to another.
array14.cs
Demonstrates arrays of structure instances.
arraylist1.cs
Demonstrates the use of ArrayList to input and to output data.
arraylist2.cs
Demonstrates the ArrayList method: Sort()
arraylist3.cs
Demonstrates the use of ArrayList on a class derived from the interface: IComparable to sort instances of the class .
arrayMethods1.cs
Demonstrates that if an element of an array is passed to a function then the element is not changed
arrayMethods2.cs
Demonstrates that if an array is passed to a function then its element may be changed.
bank7.cs
Demonstrates a bank account using a class that has a data member which is an array.
bank8.cs
Demonstrates a bank account using a class that has a data member which is an array. In addition nit uses indexers to access the multiple names on the account.
bank9.cs
Demonstrates a bank account using a structure that can have arrays of objects of the structure. One example initializes from the keyboard and the other does a list definition using the default and the non-default constructors.
employeeName1.cs
Demonstrates the assignment of one array to another and how the new array contains the save values for its elements. It further shows that changing the values of the second array also changes the values of the first array.
employeeNumber1. cs
Demonstrates the assignment of one array to another and how the new array contains the save values for its elements. It further shows that changing the values of the second array also changes the values of the first array. This is even true when system data types are used.
employeeNumber2. cs
Demonstrates the method CopyTo() which copies one array to another and how the new array contains the save values for its elements but its elements are different places in memory. It further shows that changing the values of the second array does not change the values of the first array.\This is even true when system data types are used.
hashtable1.cs
Demonstrates the use of Hashtables.
hashtable2.cs
Demonstrates Hashtables using properties ID and Value and the method Add().
list1.cs
Demonstrates two ways for the initialization of arrays in their definition.
list2.cs
Demonstrates the initialization of an array at run time.
file:///D|/1/final/BBL0084.html (1 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
list3.cs
Demonstrates how to a list definition with strings.
paramsMethods.cs
Demonstrates that if params is part of the argument then either an array may be passed or a collection of constants may be passed.
queue1.cs
Demonstrates the use of the class Queue.
search1.cs
Demonstrates how to use a linear search to find an element in an array.
search2.cs
Demonstrates the static Array method BinarySearch() to find an element but the array must be sorted. If the value requested was found, the index was returned. If the value was not found then -1 was returned.
search3.cs
Demonstrates how to use the static Array method BinarySearch() but the array must be sorted. If the value requested was found the index was returned otherwise a -1 was returned. This array contains strings rather than numbers.
sort1.cs
Demonstrates the static Array method Sort() to sort the elements of an array.
sortedlist1.cs
Demonstrates SortedList using the method Add() and thee properties ID and Value.
stack1.cs
Demonstrates the use of the class Stack.
// program_id array1.cs // written_by don voils // date_written 12/18/2006 // description This program iullustrates the use // of arrays in a C# program where the // elements are initialized by input // from the keyboard. // using System; class array1 { static void Main() { decimal[] unitPrice = new decimal[10]; for(int index=0; index < 10;++index) { Console.Write("\nWhat is the unit price of unit {0}? ",index+1); unitPrice[index] = Decimal.Parse(Console.ReadLine()); } Console.Clear(); decimal totalPrice = 0.00M; Console.WriteLine("\tItem\tPrice"); for(int index=0; index < unitPrice.Length; ++index) { Console.WriteLine("\t{0,2} {1,15:c} ",index+1, unitPrice[index]); totalPrice += unitPrice[index]; } Console.WriteLine("\t {0,12}","------------"); Console.WriteLine("\tTotal {0,12:c}",totalPrice); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array2.cs // written_by don voils // date_written 12/18/2006 // description This program iullustrates the use // of arrays in a C# program. It introduces
file:///D|/1/final/BBL0084.html (2 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
// //
the use of the foreach() loop.
using System; class theProgram { static void Main() { decimal[] unitPrice = new decimal[10]; int index; for(index = 0;index < 10; ++index) { Console.Write("\nWhat is the unit price of unit {0}? ",index+1); unitPrice[index] = Decimal.Parse(Console.ReadLine()); } Console.Clear(); decimal totalPrice = 0.00M; Console.WriteLine("\tItem\t\tPrice"); index= 0; foreach(decimal price in unitPrice) { Console.WriteLine("\t{0,2}\t{1,15:c} ",index+1, price); totalPrice += price; index++; } Console.WriteLine("\t\t {0,12}","------------"); Console.WriteLine("\tTotal\t {0,12:c}",totalPrice); Console.ReadKey(); } }
// program_id array3.cs // written_by don voils // date_written 12/18/2006 // description This program iullustrates the use of enumerated types // with arrays in a C# program. // using System; class array1 { enum Months { January,February,March,April, May,June,July,August,September, October,November,December } static void Main() { decimal[] monthlySales = new decimal[12]; for(Months theMonth=Months.January; theMonth<=Months.December; ++theMonth) { Console.Write("\nWhat is the sales for the month {0}? ", theMonth.ToString()); monthlySales[(int)theMonth] = Decimal.Parse(Console.ReadLine()); } file:///D|/1/final/BBL0084.html (3 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
Console.Clear(); decimal totalPrice = 0.00M; Console.WriteLine("\tMonth\t\t\tSales"); for(Months theMonth=Months.January; theMonth<=Months.December; ++theMonth) { Console.WriteLine("\t{0,10}\t{1,15:c} ",theMonth.ToString(), monthlySales[(int)theMonth]); totalPrice += monthlySales[(int)theMonth]; } Console.WriteLine("\t\t\t -----------"); Console.WriteLine("\tTotal\t\t{0,15:c}",totalPrice); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array4.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // multidimensional arrays. using System;
class theProgram { static void Main() { int[,] theNumbers = new int[4, 3]; Console.WriteLine("Enter the elements of the array.\n"); for (int counter1 = 0; counter1 < 4; ++counter1) for (int counter2 = 0; counter2 < 3; ++counter2) { Console.Write("What is theNumber[{0}][{1}]? ", counter1 + 1, counter2 + 1); theNumbers[counter1, counter2] = Int32.Parse(Console.ReadLine()); } Console.Clear(); Console.WriteLine("The elements of the array are:\n"); for (int counter1 = 0; counter1 < 4; ++counter1) for (int counter2 = 0; counter2 < 3; ++counter2) { Console.WriteLine("theNumber[{0}][{1}] = {2,8}", counter1 + 1, counter2 + 1, theNumbers[counter1, counter2]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array5.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use
file:///D|/1/final/BBL0084.html (4 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
//
of the Array attribute Length.
using System; class theProgram { static void Main() { int[] theCustomerNumber = new int[1000]; Console.WriteLine("The length of the array is {0}\n\n",theCustomerNumber.Length); Console.ReadKey(); } }
// program_id array6.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // arrays of class objects. using System;
class theProgram { public class customer { private string name; private decimal amountOwed; public customer() { name = ""; amountOwed=0.00M; } public void setName(string theName) { name = theName; } public void setAmountOwed(decimal theAmount) { amountOwed = theAmount; } public string getName() { return name; } public decimal getAmountOwed() { return amountOwed; } } static void Main() { string theName; decimal theAmount; customer[] myCustomers = new customer[3]; for(int index = 0;index < myCustomers.Length;++index) { myCustomers[index] = new customer(); Console.Write("\nWhat is customer {0}'s name? ",index+1); theName = Console.ReadLine(); Console.Write("How much does customer {0} owe? ",index+1); theAmount = Decimal.Parse(Console.ReadLine()); file:///D|/1/final/BBL0084.html (5 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
myCustomers[index].setName(theName); myCustomers[index].setAmountOwed(theAmount); } Console.Clear(); for(int index = 0;index < myCustomers.Length;++index) { Console.WriteLine("Customer {0}'s name is {1} who owes {2:c}", index+1, myCustomers[index].getName(), myCustomers[index].getAmountOwed()); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array7.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how // the elements of a system data // type elements are initialized // to their default amount at // definition time. using System; class theProgram { static void Main() { int[] intNumbers = new int[4]; Console.WriteLine("The definition of the array was:\n\nint[] intNumbers = new int[4];"); Console.WriteLine("\nThe length of intNumbers[] is {0}\n",intNumbers.Length); Console.WriteLine("\nThe elements of the array: intNumbers[] are initialized to:\n"); for(int index=0;index < 4; ++index) { Console.WriteLine("intNumbers[{0}]= {1}", index,intNumbers[index]); } double[] doubleNumbers = new double[7]; Console.WriteLine("\n\nThe defintion of the array was:\n\ndouble[] doubleNumbers = new double[7];"); Console.WriteLine("\nThe length of doubleNumbers[] is {0}\n",doubleNumbers.Length); Console.WriteLine("\nThe elements of the array: doubleNumbers[] are initialized to:\n"); for(int index=0;index < doubleNumbers.Length; ++index) { Console.WriteLine("doubleNumbers[{0}]= {1:n}", index,doubleNumbers[index]); } Console.WriteLine("\n\n"); Console.ReadKey();
file:///D|/1/final/BBL0084.html (6 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
} }
// program_id array8.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how // the elements of a system data // type elements are initialized // to their default amount at // definition time. using System; class theProgram { static void Main() { Console.Write ("Enter the number of items to be processed: "); int theNumber = Int32.Parse(Console.ReadLine()); decimal[] itemAmount = new decimal[theNumber]; for(int index=0;index < theNumber; ++index) { Console.WriteLine("itemAmount[{0}]= {1:n}", index,itemAmount[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array9.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // multidimensional arrays using the // GetLength property. using System;
class theProgram { static void Main() { int[,] theNumbers = new int[4, 3]; Console.WriteLine("Enter the values of the array.\n"); for (int counter1 = 0; counter1 < theNumbers.GetLength(0); ++counter1) for (int counter2 = 0; counter2 < theNumbers.GetLength(1); ++counter2) { Console.Write("What is theNumber[{0}][{1}]? ", counter1 + 1, counter2 + 1); theNumbers[counter1, counter2] = Int32.Parse(Console.ReadLine()); } Console.Clear(); Console.WriteLine("The values of the elements of the array are:\n"); for (int counter1 = 0; counter1 < theNumbers.GetLength(0); ++counter1) for (int counter2 = 0; counter2 < theNumbers.GetLength(1); ++counter2) file:///D|/1/final/BBL0084.html (7 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
{ Console.WriteLine("theNumber[{0}][{1}] = {2,8}", counter1 + 1, counter2 + 1, theNumbers[counter1, counter2]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array10.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // jagged arrays. // using System;
class theProgram { static void Main() { int[][] array3 = new int[3][]; array3[0] = new int[] {10, 25}; array3[1] = new int[] {34}; array3[2] = new int[] {42, 53, 65, 7}; for (int i = 0; i < array3.Length; i++) { for (int j = 0; j < array3[i].Length; j++) { Console.Write(" " + array3[i][j] + " "); } Console.WriteLine(); } Console.WriteLine("\n\n"); } }
// program_id array11.cs // written?_by don voils // date_written 11/6/2006 // description This program demonstrates how to use // the Array method CopyTo() to copy one // array to another. // using System;
class theProgram { static void Main() { int[] theNumbers = new int[5]; for(int index = 0; index< theNumbers.Length;++index) {
file:///D|/1/final/BBL0084.html (8 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
Console.Write("What is element {0} of the array theNumbers[]? ",index+1); theNumbers[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\n\n"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } int[] numbersCopy = new int[theNumbers.Length]; Console.WriteLine("\nThe values of theNumbers[] are being copied to numbersCopy[]\n\n"); theNumbers.CopyTo(numbersCopy, 0); for(int index = 0; index< numbersCopy.Length;++index) { Console.WriteLine("numbersCopy[{0}] = {1}. ",index+1,numbersCopy[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array12.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // the static Array method Copy() to copy one // array to another. // using System;
class theProgram { static void Main() { int[] theNumbers = new int[5]; for(int index = 0; index< theNumbers.Length;++index) { Console.Write("What is element {0} of the array theNumbers[]? ",index+1); theNumbers[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\n\n"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } int[] numbersCopy = new int[theNumbers.Length]; Console.WriteLine("\nThe values of theNumbers[] are being copied to numbersCopy[]\n\n"); Array.Copy(theNumbers, numbersCopy, theNumbers.Length); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("numbersCopy[{0}] = {1}. ",index+1,numbersCopy[index]);
file:///D|/1/final/BBL0084.html (9 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
} Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array13.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // the Array method Clone() to define the // array being copied to and to copy one // array to another. // using System;
class theProgram { static void Main() { int[] theNumbers = new int[5]; for(int index = 0; index< theNumbers.Length;++index) { Console.Write("What is element {0} of the array theNumbers[]? ",index+1); theNumbers[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\n\n"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } int[] numbersCopy = (int[])theNumbers.Clone(); Console.WriteLine("\nThe values of theNumbers[] are being copied to numbersCopy[]\n\n"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("numbersCopy[{0}] = {1}. ",index+1,numbersCopy[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id array14.cs // written_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // arrays of structure instances. using System;
class theProgram {
file:///D|/1/final/BBL0084.html (10 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
public struct customer { private string name; private decimal amountOwed; public void setName(string theName) { name = theName; } public void setAmountOwed(decimal theAmount) { amountOwed = theAmount; } public string getName() { return name; } public decimal getAmountOwed() { return amountOwed; } } static void Main() { string theName; decimal theAmount; customer[] myCustomers = new customer[3]; for (int index = 0; index < myCustomers.Length; ++index) { myCustomers[index] = new customer(); Console.Write("\nWhat is customer {0}'s name? ", index + 1); theName = Console.ReadLine(); Console.Write("How much does customer {0} owe? ", index + 1); theAmount = Decimal.Parse(Console.ReadLine()); myCustomers[index].setName(theName); myCustomers[index].setAmountOwed(theAmount); } Console.Clear(); for (int index = 0; index < myCustomers.Length; ++index) { Console.WriteLine("Customer {0}'s name is {1} who owes {2:c}", index + 1, myCustomers[index].getName(), myCustomers[index].getAmountOwed()); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id arraylist1.cs // written?_by don voils // date_written 11/7/2006 // description This program demonstrates the use // of ArrayList to input and to output data. // using System; using System.Collections; namespace theProgram file:///D|/1/final/BBL0084.html (11 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
{ class theProgram { static void Main() { ArrayList theCustomers = new ArrayList(); char theResponse = new char(); string theName; int counter = 0; do { ++counter; Console.Write("\nEnter Customer {0}?s name: ",counter); theName = Console.ReadLine(); theCustomers.Add(theName); Console.Write("\n\nContinue? (Y/N) "); theResponse = Char.Parse(Console.ReadLine()); }while((theResponse=='y') || (theResponse=='Y')); for(int index = 0; index < theCustomers.Count;++index) { Console.WriteLine("\nCustomer number {0} is {1}.", index+1,theCustomers[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id arraylist2.cs // written?_by don voils // date_written 11/7/2006 // description This program demonstrates the use // of the ArrayList method: Sort(). // using System; using System.Collections; namespace theProgram { class theProgram { static void Main() { ArrayList theCustomers = new ArrayList(); char theResponse = new char(); string theName; int counter = 0; do { ++counter; Console.Write("\nEnter Customer {0}?s name: ", counter); theName = Console.ReadLine(); theCustomers.Add(theName); Console.Write("\n\nContinue? (Y/N) "); theResponse = Char.Parse(Console.ReadLine()); } while ((theResponse == 'y') || (theResponse == 'Y')); Console.Clear();
file:///D|/1/final/BBL0084.html (12 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
Console.WriteLine("\n\nBefore the sort, the names are:"); for (int index = 0; index < theCustomers.Count; ++index) { Console.WriteLine("\nCustomer number {0} is {1}.", index + 1, theCustomers[index]); } theCustomers.Sort(); Console.WriteLine("\n\nAfter the sort, the names are:"); for (int index = 0; index < theCustomers.Count; ++index) { Console.WriteLine("\nCustomer number {0} is {1}.", index + 1, theCustomers[index]); } Console.Write("\n\nWhat is the name of the customer you want to find? "); theName = Console.ReadLine(); int theLocation = theCustomers.BinarySearch(theName); if (theLocation >= 0) Console.WriteLine("\n\n{0} is in location {1}.",theName,theLocation+1); else Console.WriteLine("\n\n{0} is not in the customer list.", theName); string newName = "Thomas Jefferson"; theCustomers.Insert(2, newName); Console.WriteLine("\n\nAfter inserting {0} into the 3rd position of the ArrayList:", newName); for (int index = 0; index < theCustomers.Count; ++index) { Console.WriteLine("\nCustomer number {0} is {1}.", index + 1, theCustomers[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id arraylist3.cs // written?_by don voils // date_written 11/7/2006 // description This program demonstrates the use // of ArrayList on a class that is // derived from the interface: IComparable. // As a result of this extension, an ArrayList // of instances of this class may be sorted. // using System; using System.Collections; namespace theProgram { public class Employee: IComparable { file:///D|/1/final/BBL0084.html (13 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
private string EmployeeID; private string EmployeeName; public string ID { get { return EmployeeID; } set { EmployeeID = value; } } public string Name { get { return EmployeeName; } set { EmployeeName = value; } } public override string ToString() { string theEmployee = "Employee ID: " + ID + "\nEmployee Name: " + Name; return theEmployee; } public int CompareTo(Object theObject) { Employee AnEmployee = (Employee) theObject; return this.EmployeeID.CompareTo(AnEmployee.EmployeeID); } } class theProgram { static void Main() { ArrayList OurEmployees = new ArrayList(); char theResponse = new char(); int counter = 0; do { Employee theEmployee = new Employee(); ++counter; Console.Write("\nEnter Employee {0}'s ID: ",counter); theEmployee.ID = Console.ReadLine(); Console.Write("\nEnter Employee {0}'s name: ",counter); theEmployee.Name = Console.ReadLine(); OurEmployees.Add(theEmployee); Console.Write("\n\nContinue? (Y/N) "); theResponse = Char.Parse(Console.ReadLine()); }while((theResponse=='y') || (theResponse=='Y'));
Console.WriteLine("\n\nBefore the sort, the employees are:"); for(int index = 0; index < OurEmployees.Count;++index) { Console.WriteLine("\nEmployee number {0} is:\n{1}.",index+1,OurEmployees[index]); }
file:///D|/1/final/BBL0084.html (14 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
OurEmployees.Sort(); Console.WriteLine("\n\nAfter the sort, the employees are:"); for(int index = 0; index < OurEmployees.Count;++index) { Console.WriteLine("\nEmployee number {0} is:\n{1}.",index+1,OurEmployees[index]); } Console.WriteLine("\n\n"); } } }
// program_id arrayMethods1.cs // written?_by don voils // date_written 11/6/2006 // description This program demonstrates that if an // element of an array is passed to a function // then the element is not changed. // using System;
class theProgram { static void Main() { int[] theNumbers = new int[5]; for(int index = 0; index< theNumbers.Length;++index) { Console.Write("What is element {0} of the array theNumbers[]? ",index+1); theNumbers[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\nThe array before the call is:"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } ModifyElement(theNumbers[3]); Console.WriteLine("The array after the call is:"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } Console.WriteLine("\n\n"); } static void ModifyElement(int number) { string theOutput = ""; theOutput += "\nValue received in ModifyElement(): " + number + "\n"; number *= 2; theOutput += "Value calculated in ModifyElement(): " + number + "\n"; Console.WriteLine(theOutput); } file:///D|/1/final/BBL0084.html (15 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
}
// program_id arrayMethods2.cs // written?_by don voils // date_written 11/6/2006 // description This program demonstrates that if an // array is passed to a function // then its element may be changed. // using System;
class theProgram { static void Main() { int[] theNumbers = new int[5]; for(int index = 0; index< theNumbers.Length;++index) { Console.Write("What is element {0} of the array theNumbers[]? ",index+1); theNumbers[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\nThe array before the call is:"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } ModifyArray(theNumbers); Console.WriteLine("\n\n"); Console.WriteLine("The array after the call is:"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } Console.WriteLine("\n\n"); } static void ModifyArray(int[] numberList) { for(int i = 0; i < numberList.Length; i++) { numberList[i] *= 2; } } }
// program_id bank7.cpp // author don voils // date written 11/6/2006 // // description This program simulates a bank // account using a class that // has a data member which is an array. //
file:///D|/1/final/BBL0084.html (16 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
using System; class theProgram { class bankAccount { private int numberNames; private string customerID; private string[] customerName = new string[2]; private decimal theBalance; public bankAccount() { theBalance = 0.00m; numberNames = 0; } public int getNumberNames() { return numberNames; } public void setCustomerID(string ID) { customerID = ID; } public string getCustomerID() { return customerID; } public void setName(string theName) { if (numberNames < 2) { customerName[numberNames] = theName; ++numberNames; } else Console.WriteLine("No name was added.\n" + "The number of names for this account has already" + " reached the maximum."); } public void depositSlip(decimal deposit) { theBalance += deposit; } public void withdrawalSlip(decimal amount) { theBalance -= amount; } public decimal getBalance() { return theBalance; } string showCustomersName(int index) { if ((index == 2) || (index == 1)) return customerName[index - 1]; file:///D|/1/final/BBL0084.html (17 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
else return ""; } public override string ToString() { string theValue; string theNames = "Customer Names:\n"; for (int index = 0; index < numberNames; ++index) theNames += " " + customerName[index] + "\n"; theValue = string.Format("Account ID: {0}\n", customerID) + theNames + string.Format("Balance: {0:c}\n",theBalance); return theValue.ToString(); } } static void Main() { bankAccount theAccount = new bankAccount(); Console.Write("What is the customer's ID? "); theAccount.setCustomerID(Console.ReadLine()); for (int index = 0; index < 2; ++index) { Console.Write("\nWhat is the account number {0}'s customer number " + "{1}'s name? ", theAccount.getCustomerID(), index + 1); theAccount.setName(Console.ReadLine()); if (theAccount.getNumberNames() >= 2) break; Console.Write("\nIs there another name? Y/N "); char theResponse = Char.Parse(Console.ReadLine()); if ((theResponse != 'y') && (theResponse != 'Y')) break; } Console.Write("\nHow much did account number {0} start the checking account with? " , theAccount.getCustomerID()); theAccount.depositSlip(Decimal.Parse(Console.ReadLine())); Console.Write("\nHow much did account number {0} deposit in the checking account? ", theAccount.getCustomerID()); theAccount.depositSlip(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat was the amount of the check account number {0}\n" + "wrote against the checking account? ", theAccount.getCustomerID()); theAccount.withdrawalSlip(Decimal.Parse(Console.ReadLine())); Console.Clear(); Console.WriteLine("\n\n{0}\n\n", theAccount.ToString()); Console.ReadKey(); } }
// program_id bank8.cpp // author don voils // date written 11/6/2006 // // description This program simulates a bank // account using a class that // has a data member which is an array.
file:///D|/1/final/BBL0084.html (18 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
// // // //
In addition it uses indexers to access the multiple names on the account.
using System; class theProgram { class bankAccount { private int numberNames; private string customerID; private string[] customerName = new string[2]; private decimal theBalance; public bankAccount() { theBalance = 0.00m; numberNames = 0; } public int getNumberNames() { return numberNames; } public void setCustomerID(string ID) { customerID = ID; } public string getCustomerID() { return customerID; } public void setName(string theName) { if(numberNames < 2) { customerName[numberNames] = theName; ++numberNames; } else Console.WriteLine("No name was added.\nThe number of names " + "for this account has already reached the maximum."); } public void depositSlip(decimal deposit) { theBalance += deposit; } public void withdrawalSlip(decimal amount) { theBalance -= amount; } public decimal getBalance() { return theBalance; }
file:///D|/1/final/BBL0084.html (19 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
string showCustomersName(int index) { if((index == 2) || (index == 1)) return customerName[index-1]; else return ""; } public override string ToString() { string theValue; string theNames = "Customer Names:\n"; for(int index = 0; index < numberNames;++index) theNames += " " + this[index] + "\n"; theValue = "Account ID: "+ customerID + "\n" + theNames + "Balance: $" + theBalance + "\n"; return theValue.ToString (); } public string this[int index] { get { // The following should be protected by // an exception to prevent exceeding // the number of elements in the array. // return customerName[index]; } set { // The following should be protected by // an exception to prevent exceeding // the number of elements in the array. // ++numberNames; customerName[index] = value; } } }
static void Main() { bankAccount theAccount = new bankAccount(); Console.Write("What is the customer's ID? "); theAccount.setCustomerID(Console.ReadLine()); for(int index = 0; index < 2; ++ index) { Console.Write("\nWhat is the account number {0}'s customer " + "number {1}'s name? ", theAccount.getCustomerID(),index+1); theAccount[index] = Console.ReadLine(); if(theAccount.getNumberNames()>=2) break; Console.Write("\nIs there another name? Y/N "); char theResponse = Char.Parse(Console.ReadLine()); if((theResponse != 'y') && (theResponse != 'Y')) break; }
file:///D|/1/final/BBL0084.html (20 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
Console.Write("\nHow much did account number {0} start the checking account with?", theAccount.getCustomerID()); theAccount.depositSlip(Decimal.Parse(Console.ReadLine())); Console.Write("\nHow much did account number {0} deposit in the checking account?", theAccount.getCustomerID()); theAccount.depositSlip(Decimal.Parse(Console.ReadLine())); Console.Write("\nWhat was the amount of the check account number {0}\nwrote against the" + "checking account? ",theAccount.getCustomerID()); theAccount.withdrawalSlip(Decimal.Parse(Console.ReadLine())); Console.WriteLine("\n\n{0}",theAccount.ToString()); Console.WriteLine("\n\n"); } }
// program_id bank9.cpp // author don voils // date written 11/6/2006 // // description This program simulates a bank // account using a structure that // can have arrays of objects of the structure. // One example initializes from the keyboard // and the other does a list definition using // the default and the non-default constructors. // using System; class theProgram { struct bankAccount { private string customerName; private string customerID; private decimal customerBalance; public string theName { get { return customerName; } set { customerName = value; } } public string theID { get { creturn customerID; } set { customerID = value; file:///D|/1/final/BBL0084.html (21 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
} } public decimal theBalance { get { return customerBalance; } set { customerBalance = value; } } public bankAccount(string anID, string aName, decimal aBalance) { customerID = anID; customerName = aName; customerBalance = aBalance; } public void depositSlip(decimal theDeposit) { theBalance += theDeposit; } public void withdrawalSlip(decimal theWithdrawal) { theBalance -= theWithdrawal; } public override string ToString() { string theValue; theValue = string.Format("Customer ID: {0}\n", theID) + string.Format("Customer Name:{0}\n",theName) + string.Format("Balance: {0:c}\n",theBalance); return theValue.ToString(); } } static void Main() { bankAccount[] theAccount = new bankAccount[3]; for (int index = 0; index < 3; ++index) { Console.Write("\n\nWhat is the customer's ID? "); theAccount[index].theID = Console.ReadLine(); Console.Write("\nWhat is the custoner's name? "); theAccount[index].theName = Console.ReadLine(); Console.Write("\nWhat is the customer's balance? "); theAccount[index].theBalance = decimal.Parse(Console.ReadLine()); } Console.Clear(); Console.WriteLine("The customers that were initialized \nfrom the keyboard.\n"); for (int index = 0; index < 3; ++index) Console.WriteLine("Customer ID {0}\nCustomer Name {1}\nCustomer Balance {2:c}\n\n", theAccount[index].theID, theAccount[index].theName, theAccount[index].theBalance); bankAccount[] theAccount2 = { new bankAccount(), new bankAccount(), new bankAccount() };
file:///D|/1/final/BBL0084.html (22 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
Console.WriteLine("\nThe customers that were list definition \ninitialized from the default constructor.\n"); for (int index = 0; index < 3; ++index) Console.WriteLine("Customer ID {0}\nCustomer Name {1}\nCustomer Balance {2:c}\n\n", theAccount2[index].theID, theAccount2[index].theName, theAccount2[index].theBalance); bankAccount[] theAccount3 = { new bankAccount("1234","The first One",100.00m), new bankAccount("1235","The Second One",200.00m), new bankAccount("1236","The Third One",300.00m)}; Console.WriteLine("\nThe customers that were list definition \ninitialized from the nondefault constructor.\n"); for (int index = 0; index < 3; ++index) Console.WriteLine("Customer ID {0}\nCustomer Name {1}\nCustomer Balance {2:c}\n\n", theAccount3[index].theID, theAccount3[index].theName, theAccount3[index].theBalance); Console.ReadKey(); } }
// program_id employeeName1.cs // written_by don voils // date_written 11/6/2006 // description This program demonstrates the assignment // of one array to another and how the new // array contains the save values for its // elements. It further shows that changing // the values of the second array also // changes the values of the first array. // using System; class theProgram { static void Main() { string[] employeeName = new string[5]; string[] employeeName2 = new string[5]; employeeName[0] = "George Washington"; employeeName[1] = "Thomas Jefferson"; employeeName[2] = "John Adams"; employeeName[3] = "Theodore Roosevelt"; employeeName[4] = "Abraham Lincoln"; Console.WriteLine("Using the array: employeeName[]\n"); for (int index = 0; index < employeeName.Length; ++index) { Console.WriteLine("employeeName[{0}] is {1}.", index + 1, employeeName[index]); } Console.WriteLine("\n\n"); employeeName2 = employeeName; Console.WriteLine("The array employeeName[] has been assigned to employeeName2[] \nwhose elements are now:\n"); for (int index = 0; index < employeeName2.Length; ++index) { Console.WriteLine("employeeName2[{0}] = {1}. ", index + 1, employeeName2[index]); } Console.WriteLine("\nUsing the array: employeeName2[] enter new elements\n"); for (int index = 0; index < 5; ++index) file:///D|/1/final/BBL0084.html (23 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
{ Console.Write("\nWhat is employeeName2[{0}]'s name? ", index + 1); employeeName2[index] = Console.ReadLine(); } Console.WriteLine("\nUsing the array: employeeName[]"); for(int index=0; index<5;++index) { Console.WriteLine(" employeeName[{0}] = {1} ",index+1,employeeName[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id employeeNumber1.cs // written_by don voils // date_written 11/6/2006 // description This program demonstrates the assignment // of one array to another and how the new // array contains the save values for its // elements. It further shows that changing // the values of the second array also // changes the values of the first array. // This is even true when system data types are // used. // using System; class theProgram { static void Main() { int[] employeeNumber = new int[5]; int[] employeeNumber2 = new int[5]; employeeNumber[0] = 100; employeeNumber[1] = 200; employeeNumber[2] = 300; employeeNumber[3] = 400; employeeNumber[4] = 500; Console.WriteLine("Using the array: employeeNumber[]\n"); for (int index = 0; index < employeeNumber.Length; ++index) { Console.WriteLine("employeeNumber[{0}] is {1}.", index + 1, employeeNumber[index]); } Console.WriteLine("\n\n"); employeeNumber2 = employeeNumber; Console.WriteLine("The array employeeNumber[] has been assigned to employeeNumber2[] \nwhose elements are now:\n"); for (int index = 0; index < employeeNumber2.Length; ++index) { Console.WriteLine("employeeNumber2[{0}] = {1}. ", index + 1, employeeNumber2[index]); } Console.WriteLine("\nUsing the array: employeeNumber2[] enter new elements\n"); for (int index = 0; index < 5; ++index) {
file:///D|/1/final/BBL0084.html (24 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
Console.Write("\nWhat is employeeNumber2[{0}]'s value? ", index + 1); employeeNumber2[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\nUsing the array: employeeNumber[]"); for(int index=0; index<5;++index) { Console.WriteLine(" employeeNumber[{0}] = {1} ", index + 1, employeeNumber[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id employeeNumber2.cs // written_by don voils // date_written 11/6/2006 // description This program demonstrates the method CopyTo() // which copies one array to another and how the new // array contains the save values for its // elements but its elements are different places // in memory. It further shows that changing // the values of the second array does not // change the values of the first array. // This is even true when system data types are // used. // using System; class theProgram { static void Main() { int[] employeeNumber = new int[5]; int[] employeeNumber2 = new int[5]; employeeNumber[0] = 100; employeeNumber[1] = 200; employeeNumber[2] = 300; employeeNumber[3] = 400; employeeNumber[4] = 500; Console.WriteLine("Using the array: employeeNumber[]\n"); for (int index = 0; index < employeeNumber.Length; ++index) { Console.WriteLine(" employeeNumber[{0}] is {1}.", index + 1, employeeNumber[index]); } Console.WriteLine("\n\n"); employeeNumber.CopyTo(employeeNumber2,0); Console.WriteLine("The array employeeNumber[] has been copied to employeeNumber2[] \nwhose elements are now:\n"); for (int index = 0; index < employeeNumber2.Length; ++index) { Console.WriteLine(" employeeNumber2[{0}] = {1}. ", index + 1, employeeNumber2[index]); } Console.WriteLine("\nUsing the array: employeeNumber2[] enter new elements\n"); for (int index = 0; index < 5; ++index) { file:///D|/1/final/BBL0084.html (25 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
Console.Write("\nWhat is employeeNumber2[{0}]'s value? ", index + 1); employeeNumber2[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\nAfter the assignment of new values to employeeNumber2[]:\n"); for (int index = 0; index < employeeNumber2.Length; ++index) { Console.WriteLine(" employeeNumber2[{0}] = {1}. ", index + 1, employeeNumber2[index]); } Console.WriteLine("\nWhile the array: employeeNumber[] now contains:\n"); for (int index = 0; index < 5; ++index) { Console.WriteLine(" employeeNumber[{0}] = {1} ", index + 1, employeeNumber[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id hashtable1.cs // written?_by don voils // date_written 8/12/2006 // description This program demonstrates the use // of Hashtables. // using System; using System.Collections; namespace theProgram { class theProgram { static void Main() { Hashtable theCustomer = new Hashtable(); theCustomer["10021"] = "George Washington"; theCustomer["10022"] = "Thomas Jefferson"; theCustomer["10034"] = "John Adams"; theCustomer["10044"] = "John Quincy Adams"; foreach (DictionaryEntry element in theCustomer) { string ID = (string)element.Key; string theName = (string)element.Value; Console.WriteLine("Customer ID {0} is customer {1}\n", ID, theCustomer[ID]); } Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id hashtable2.cs // written?_by don voils // date_written 8/12/2006 // description This program demonstrates the use // of Hashtables using the properties // ID and Value and the method Add(). //
file:///D|/1/final/BBL0084.html (26 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
using System; using System.Collections; namespace theProgram { class theProgram { static void Main() { Hashtable theItem = new Hashtable(); string theID = "ID123"; theItem[theID] = "Monarch Doors"; Console.WriteLine("The Key is {0} and the Value is {1}\n", theID, theItem[theID]); theID = "ID124"; theItem.Add(theID, "Kitchen Maid Cabinets"); Console.WriteLine("The Key is {0} and the Value is {1}\n", theID, theItem[theID]); Console.ReadKey(); } } }
// program_id list1.cs // written_by don voils // date_written 11/6/2006 // description This program iullustrates two ways for the initialization // of arrays in their definition. // using System; class array1 { static void Main() { int[] theUnitNumbers = new int[6] {23, 42, 123, 42, 13, 123}; for(int index=0; index < theUnitNumbers.Length;++index) { Console.WriteLine("theUnitNumbers[{0}] = {1,3} ",index+1, theUnitNumbers[index]); } Console.WriteLine("\n"); decimal[] thePrices = {34.23m, 532.43m, 335.45m, 625.34m}; for(int index=0; index < thePrices.Length; ++index) { Console.WriteLine("thePrices[{0}] = {1,7:c}",index+1, thePrices[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id list2.cs // written_by don voils // date_written 11/6/2006 // description This program iullustrates the initialization // of an array at run time. //
file:///D|/1/final/BBL0084.html (27 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
using System; class array1 { static void Main() { Random theValues = new Random(); int[] theNumbers = new int[5] { theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10) }; for(int index=0; index < theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1,3} ",index+1, theNumbers[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); }
// program_id list3.cs // written?_by don voils // date_written 11/6/2006 // description This program demonstrates how to a list // definition with strings. // using System; class theProgram { static void Main() { string[] employeeName = { "George Washington","Thomas Jefferson","John Adams", "Theodore Roosevelt","Abraham Lincoln"}; for (int index = 0; index < employeeName.Length; ++index) { Console.WriteLine("The element {0} of the array employeeName[] is {1}.", index + 1, employeeName[index]); }
Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id paramsMethods.cs // written?_by don voils // date_written 11/6/2006 // description This program demonstrates that if the // keyword params is part of the argument // then either an array may be passed or
file:///D|/1/final/BBL0084.html (28 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
// //
a collection of contants may be passed.
using System;
class theProgram { static void Main() { int[] theNumbers = {4, 24, 43, 53}; int theOutput; Console.WriteLine("\nThe array before the call is:"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } theOutput = theProduct(theNumbers); Console.WriteLine("\nThe output the first time was {0}.",theOutput); Console.WriteLine("\n\n"); Console.WriteLine("The array after the first call is:"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } theOutput = theProduct(4,24,43,53); Console.WriteLine("\nThe output the second time was {0}.",theOutput); Console.WriteLine("\n\n"); } static int theProduct(params int[] theArray) { int theProduct = 1; foreach(int index in theArray) theProduct *= index; return theProduct; } }
// program_id queue1.cs // written_by don voils // date_written 11/7/2006 // description This program demonstrates the use // of the class Queue. // using System; using System.Collections; namespace theProgram { class theProgram { static void Main() file:///D|/1/final/BBL0084.html (29 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
{ char which; char resp; long item; Queue theQueue = new Queue(); do { Console.Clear(); Console.WriteLine("Select an option:\n"); Console.WriteLine(" 1. Add to the queue."); Console.WriteLine(" 2. Is the queue empty?"); Console.WriteLine(" 3. How many elements are in the queue?"); Console.WriteLine(" 4. What is the top element in the queue?"); Console.WriteLine(" 5. Pop the top element of the queue.\n"); Console.WriteLine(" 6. Exit the program.\n"); Console.Write("\nWhich option? "); which = char.Parse(Console.ReadLine()); switch(which) { case '1': Console.Clear(); Console.Write("Enter a long to add to the queue: "); item = long.Parse(Console.ReadLine()); theQueue.Enqueue(item); break; case '2': Console.Clear(); if(theQueue.Count==0) Console.WriteLine("The queue is empty."); else Console.WriteLine("The queue is not empty."); Console.Write("\n\nContinue? (Y/N) "); resp = char.Parse(Console.ReadLine()); break; case '3': Console.Clear(); if(theQueue.Count==0) Console.WriteLine("The queue is empty."); else Console.WriteLine("The number of elements in the queue is {0}.", theQueue.Count); Console.Write("\n\nContinue? (Y/N) "); resp = char.Parse(Console.ReadLine()); break; case '4': Console.Clear(); if(theQueue.Count==0) Console.WriteLine("The queue is empty."); else Console.WriteLine("The top element of the queue is: {0}. ", theQueue.Peek()); Console.Write("\n\nContinue? (Y/N) "); resp = char.Parse(Console.ReadLine()); break; case '5': Console.Clear(); if(theQueue.Count==0) Console.WriteLine("The queue is empty."); else { item = (long)theQueue.Dequeue(); Console.WriteLine("The top element {0} has been removed. ",
file:///D|/1/final/BBL0084.html (30 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
item); } Console.Write("\n\nContinue? (Y/N) "); resp = char.Parse(Console.ReadLine()); break; case '6': break; default: break; } }while(which != '6'); Console.Clear(); } } }
// program_id search1.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // a linear search to find an element in // an array. // using System;
class theProgram { static void Main() { int[] theNumbers = new int[5]; for(int index = 0; index< theNumbers.Length;++index) { Console.Write("What is element {0} of the array theNumbers[]? ",index+1); theNumbers[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\n\n"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } Console.Write("\nWhat is the number you are looking for? "); int theNumber = Int32.Parse(Console.ReadLine()); bool foundit = new bool(); int theElement = new int(); for(int index = 0;index
Lecture 8 Examples
Console.WriteLine("\nThe number {0} is in position {1}.",theNumber,theElement); else Console.WriteLine("\nThe number {0} was not found.",theNumber); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id search2.cs // written?_by don voils // date_written 11/6/2006 // description This program demonstrates how to use // the static Array method BinarySearch() // to find an element in an array. However // before it can be used, the array must be // sorted. If the value requested was // the index was returned. If the value was // not found then -1 was returned. // using System;
class theProgram { static void Main() { int[] theNumbers = new int[5]; for(int index = 0; index< theNumbers.Length;++index) { Console.Write("What is element {0} of the array theNumbers[]? ",index+1); theNumbers[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\n\n"); Array.Sort(theNumbers); Console.WriteLine("The array after the sort is:\n\n"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } Console.Write("\nWhat is the number you are looking for? "); int theNumber = Int32.Parse(Console.ReadLine()); int theElement = new int(); theElement = Array.BinarySearch(theNumbers,theNumber); Console.WriteLine("\nThe number {0} is in position {1}.",theNumber,theElement+1); Console.WriteLine("\n\n"); Console.ReadKey(); } }
file:///D|/1/final/BBL0084.html (32 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
// program_id search3.cs // written?_by don voils // date_written 11/6/2006 // description This program demonstrates how to use // the static Array method BinarySearch() // to find an element in an array. However // before it can be used, the array must be // sorted. If the value requested was // the index was returned. If the value was // not found then -1 was returned. This array // contains strings rather than numbers as in // the previous examples. // using System; class theProgram { static void Main() { string[] employeeName = new string[5]; employeeName[0] = "George Washington"; employeeName[1] = "Thomas Jefferson"; employeeName[2] = "John Adams"; employeeName[3] = "Theodore Roosevelt"; employeeName[4] = "Abraham Lincoln"; for (int index = 0; index < employeeName.Length; ++index) { Console.WriteLine("The element {0} of the array employeeName[] is {1}.", index + 1, employeeName[index]); } Console.WriteLine("\n\n"); Array.Sort(employeeName); Console.WriteLine("The array after the sort is:\n\n"); for (int index = 0; index < employeeName.Length; ++index) { Console.WriteLine("employeeName[{0}] = {1}. ", index + 1, employeeName[index]); } Console.Write("\nWhat is the string you are looking for? "); string theString = Console.ReadLine(); int theElement = new int(); theElement = Array.BinarySearch(employeeName, theString); if (theElement >= 0) Console.WriteLine("\nThe string {0} is in position {1}.", theString, theElement + 1); else Console.WriteLine("\nThat string is not in the array."); Console.WriteLine("\n\n"); Console.ReadKey(); } }
file:///D|/1/final/BBL0084.html (33 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
// program_id sort1.cs // written?_by don voils // date_written 12/11/2006 // description This program demonstrates how to use // the static Array method Sort() to sort // the elements of an array. // using System;
class theProgram { static void Main() { int[] theNumbers = new int[5]; for(int index = 0; index< theNumbers.Length;++index) { Console.Write("What is element {0} of the array theNumbers[]? ",index+1); theNumbers[index] = Int32.Parse(Console.ReadLine()); } Console.WriteLine("\n\n"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } Array.Sort(theNumbers); int[] numbersCopy = (int[])theNumbers.Clone(); Console.WriteLine("\nThe values of theNumbers[] have been sorted.\n\n"); for(int index = 0; index< theNumbers.Length;++index) { Console.WriteLine("theNumbers[{0}] = {1}. ",index+1,theNumbers[index]); } Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id sortedlist1.cs // written_by don voils // date_written 8/12/2006 // description This program demonstrates the use // of the class SortedList using the properties // ID and Value and the method Add(). // using System; using System.Collections; namespace theProgram { class theProgram { static void Main()
file:///D|/1/final/BBL0084.html (34 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
{ SortedList theCustomer = new SortedList(); theCustomer["10021"] = "George Washington"; theCustomer["10044"] = "John Quincy Adams"; theCustomer["10034"] = "John Adams"; theCustomer["10022"] = "Thomas Jefferson"; theCustomer.Add("10040", "Abraham Lincoln"); foreach (DictionaryEntry element in theCustomer) { Console.WriteLine("Customer ID {0} is customer {1}\n", element.Key, element.Value); } Console.ReadKey(); } } }
// program_id stack1.cs // written_by don voils // date_written 11/7/2006 // description This program demonstrates the use // of the class Stack. // using System; using System.Collections; namespace theProgram { class theProgram { static void Main() { char which; char resp; long item; Stack theStack = new Stack(); do { Console.Clear(); Console.WriteLine("Select an option:\n"); Console.WriteLine(" 1. Add to the stack"); Console.WriteLine(" 2. Is the stack empty?"); Console.WriteLine(" 3. How many elements are in the stack?"); Console.WriteLine(" 4. What is the top element in the stack?"); Console.WriteLine(" 5. Pop the top element of the stack.\n"); Console.WriteLine(" 6. Exit the program.\n"); Console.Write("\nWhich option? "); which = char.Parse(Console.ReadLine()); switch(which) { case '1': Console.Clear(); Console.Write("Enter a long to add to the stack: "); item = long.Parse(Console.ReadLine()); theStack.Push(item); file:///D|/1/final/BBL0084.html (35 von 36) [01.12.2007 04:49:08]
Lecture 8 Examples
break; case '2': Console.Clear(); if(theStack.Count==0) Console.WriteLine("The stack is empty."); else Console.WriteLine("The stack is not empty."); Console.Write("\n\nContinue? (Y/N) "); resp = char.Parse(Console.ReadLine()); break; case '3': Console.Clear(); Console.WriteLine("The number of elements in the stack is {0}.", theStack.Count); Console.Write("\n\nContinue? (Y/N) "); resp = char.Parse(Console.ReadLine()); break; case '4': Console.Clear(); if(theStack.Count==0) Console.WriteLine("The stack is empty."); else Console.WriteLine("The top element of the stack is: {0}. ", theStack.Peek()); Console.Write("\n\nContinue? (Y/N) "); resp = char.Parse(Console.ReadLine()); break; case '5': Console.Clear(); if(theStack.Count==0) Console.WriteLine("The stack is empty."); else { item = (long)theStack.Pop(); Console.WriteLine("The top element {0} has been removed. ", item); } Console.Write("\n\nContinue? (Y/N) "); resp = char.Parse(Console.ReadLine()); break; case '6': break; default: break; } }while(which != '6'); Console.Clear(); } } }
file:///D|/1/final/BBL0084.html (36 von 36) [01.12.2007 04:49:08]
Lecture 9: String, String Builder, Char and Regex Classes
Lecture 9: String, String Builder, Char and Regex Classes The String Class Another one of the data types that is included in System is String. Its name is therefore System.String. In addition to this name, string may also be used. The definition header of this data type is: public sealed class String: IComparable, IClonable, IConvertible
From this definition it can be seen that no class can be derived from String since it is sealed. The class String also implements the interfaces: IComparable, IClonable and IConvertible. Since the class String is derived from IComparable, its instances may be compared and ordered. Since it is derived from IClonable, its instances may be cloned into another string instance. To be derived from IConvertible means that this class provides methods to convert its instances to instances of other data types using methods such as: ToInt32(), ToDouble(), ToDecimal etc. Strings are immutable meaning that they can not be changed. The next section of this lecture considers StringBuilder another class that overcomes this problem and may therefore be a better tool to use than objects of the class String. String literals are a collection of characters enclosed in double quotation marks. A string variable may be defined and initialized as in the following: string theString = "This is a test.";
Additional definitions of instances could be created using one of the following constructors:
Open table as spreadsheet Constructor
Description
String(char,int)
Initializes a new instance of the System.String class to the value indicated by a specified Unicode character repeated a specified number ot times.
String(char[ ])
Initializes a new instance of the System.String class to the value indicated by an array of Unicode characters.
String(char[ ],int,int)
Initializes a new instance of the System.String class to the value indicated by an array of Unicode characters, a string character position within that array and a length.
String(sbyte*)
Initializes a new instance of the System.String class to the value indicated by a pointer to an array of 8-bit signed integers.
String(sbyte*,int,int)
Initializes a new instance of the System.String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting character position within that array, and a length.
file:///D|/1/final/BBL0085.html (1 von 4) [01.12.2007 04:49:09]
Lecture 9: String, String Builder, Char and Regex Classes
String(sbyte*,int,int, System.Text. Encoding)
Initializes a new instance of the System.String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting character position wihtin that array, a length, and a System.Text. ** Encoding [ ] object.
String(char*)
Initializes a new instance of the System.String class ot the value indicated by a specified pointer to an array of Unicode characters.
String(char*,int,int)
Initializes a new instance of the System.String class to the value indicated by the specified ponter to an array of Unicode characters, a starting character * position within that array, and a length [ ].
[**]A
System.Text.Encoding object specifies how the array is referenced before the value is encoded (i.e. Unicode,ASCII, etc)
[*]Length
refers to the number of characters within the value to use.
For example using one of the constructors above, the following is possible: char[ ] theArray = {'T', 'o', ' ', 'B', 'e', ' ', 'O', 'r', ' ', 'N', 'o', 't', ' ', 'T', 'o', ' ', 'B', 'e'};
would store into theArray the following: "To Be Or Not To Be"
and then the following definition: string theString = new string(theArray);
would store the contents of theArray into theString. The following: string anotherString = new string(theArray,9,3);
would store: "Not" into anotherString. See string1.cs. When strings are defined, they represent different places in memory. That is in the following code theFirst and theSecond represent different places in memory. Therefore: theFirst = "This is a test.";
followed by:
file:///D|/1/final/BBL0085.html (2 von 4) [01.12.2007 04:49:09]
Lecture 9: String, String Builder, Char and Regex Classes
theSecond = theFirst;
would place "This is a test" into theSecond. However if theSecond = "Another test";
then theFirst still contains: "This is a test." while theSecond now contains "Another test". See equalstrings.cs. The String class has the public attribute: Length which contains the length of the calling string. The following table lists some of the methods of the String class:
Open table as spreadsheet Method
Description
CompareTo(String1,String2)
This is a static method that compares two strings: String1 and String2. If they are the same, then the method returns a 0. It returns a negative value if String1 is less than String2. It returns a positive value if String2 is less than String1.
CopyTo(start, anArray[ ], begin, theNumber)
Beginning at the start position in the anArray[ ], the characters in the calling string starting at position begin and going theNumber of characters into the string will be stored into anArray[ ].
Equals(anotherString)
Returns a boolean that indicates whether the calling string is equivalent to anotherString The equivalent operator == may be used as well.
Format(theSpecification)
returns a string that format the calling string using a format theSpecification.
Insert(theString,theLocation)
returns a string created by inserting theString into the calling string at theLocation.
PadLeft()
returns a string which left aligns the calling string and pads spaces or a specified character for a specified total length of the new string.
PadRight()
returns a string which is similar to PadLeft() except the string is padded right.
Remove()
deletes the specified number of characters from the string startinig at a specified index.
Split()
splits up the string into an array of strings using a supplied delimiter.
ToString(theValue)
returns a string that contains theValue.
ToCharArray()
returns a char array
Trim()
removes the specified characters (or spaces) from the start and the end of the calling string.
TrimEnd()
removes the specified characters (or spaces) from the end of the calling string.
TrimStart()
removes the specified characters (or spaces) from the start of the calling string.
file:///D|/1/final/BBL0085.html (3 von 4) [01.12.2007 04:49:09]
Lecture 9: String, String Builder, Char and Regex Classes
StartsWith(anotherString)
returns true if calling string begins with anotherString and false otherwise.
EndsWith(anotherString)
returns true if calling string begins with anotherString and false otherwise.
IndexOfAny()
is the same as IndexOf( ) except it searches character arrays rather than strings.
LastIndexOfAny()
is the same as LastIndexOf( ) except it searches character arrays rather than strings.
Substring(theStart)
returns a string that begins at theStart. in the calling string.
Substring(theStart,theLength)
returns a string that begins at theStart and includes those characters and continues theLength in the calling string.
Concat(firstString, secondString)
a static method that places the firstString followed by the secondString into the another string.
+(aString)
this operator adds aString to the calling string.
Replace(firstCharacter, secondCharacter)
replaces each occurance of firstCharcter with secondCharacter in the calling string.
ToUpper()
returns all characters in the calling string with upper case.
ToLower()
returns all characters in the calling string with lower case.
For some examples utilizing the string methods listed above, see the following ●
string2.cs
●
compareStrings.cs
●
copyStrings.cs
●
concatStrings.cs
●
removeStrings.cs
●
insertStrings.cs
file:///D|/1/final/BBL0085.html (4 von 4) [01.12.2007 04:49:09]
The String Builder Class
The String Builder Class There is a problem with the String class. String class objects are immutable. When any of the string methods add content to the original string, they create a reference to a new string and assign this new content to the calling string. This will create additional strings in memory. If a program performs several of these processes within a short time significant amounts of memory may be used before the GC eliminates the unreferenced memory. To avoid this problem, the class StringBuilder can be used. Its object is mutable. That is if they are changed, the result is the same object with the new contents. The class: StringBuilder is contained in the System namespace Text. Therefore when using this class, the following must be added to the top of the program: using System.Text;
The class StringBuilder has the following constructors:
Open table as spreadsheet Constructor
Description
StringBuilder( )
Returns a reference to the string created
StringBuilder(theSize)
Returns a reference to a string with initial Capacity of theSize
StringBuilder (theString)
Returns a reference to the string created, with a Capacity of the size of theString and contains the contents of theString.
For example see: stringbuilder1.cs. The objects of StringBuilder have a public attribute Capacity that stores the number of characters the string may contain. Exceeding the Capacity will cause an increase in the size of the string to accommodate the additional characters. The class StringBuilder has the following public attributes:
Open table as spreadsheet Attribute
Description
Indexer
Is used to access the elements of the string like an index for a C++ array.
Length
Contains the current size.and can be used to change the length
Capacity
Contains the maximum size without change and will be automatically updated when data is added to the string.
The following is a list of some of the public methods of the class: StringBuilder:
Open table as spreadsheet Method
Description
EnsureCapacity(theNumber)
This method allows the progrm to specify a capacity that reduces the number of times that the capacity might be automatically increased. EnsureCapacity() doubles the current capacity. If after being doubles, the capacity is greater than what the program requires, then that double value becomes the new capacity. Otherwise the capacity of the calling object becomes theNumber+1.
file:///D|/1/final/BBL0086.html (1 von 2) [01.12.2007 04:49:10]
The String Builder Class
Append()
There are 19 different Append( ) methods. These methods permit the appending of each the data types, strings, character arrays and other objects to the calling object.
AppendFormat()
Converts a string to a specified format and then appends it to the StringBuilder calling object.
Equals()
specifies whether the StringBuilder calling object is equal to the specified object.
GetType()
returns the data type of the calling object.
Insert()
There are 18 overloaded Insert() methods that permits the insertion of the system data type at a particular position into the calling object.
Remove(theStart, theNumber)
This method deletes theNumber of characters from the calling object beginning at theStart.
Replace()
There are several overloaded Replace() methods which searches for a specified string or character within the calling object and replaces it with another string or character.
ToString()
returns a string that from the StringBuilder calling object.
For an example using some of these methods see: stringbuilder2.cs.
file:///D|/1/final/BBL0086.html (2 von 2) [01.12.2007 04:49:10]
The Char Class
The Char Class An instance of the Char class is any Unicode instance. A Char literal can be any Unicode character enclosed in single quotes like 'a'.
Escape Sequence Characters In C# there are special character literals called escape sequence characters and they are the same ones as in C+ +. The escape sequence characters are:
Open table as spreadsheet Escape Sequence Character
Name Given to Character
\a
Bell
\b
Backspace
\f
Form feed
\n
Newline (linefeed/return depending on the system)
\r
Return
\t
Tab
\\
Backslash
\'
Single quotation mark
\"
●
Double quotation mark
These escape sequences may be used where ever a character is used. They are the same as those from C ++. (It is not necessary for you to memorize this table either.)
The escape sequence \b will cause the cursor to move to the left one position. The escape sequence \t will force a tab. The escape sequence \n will force a newline to appear below the current one. Sometimes it will be necessary to use a \r together with \n. The \r is a carriage return and the \n is a new line character. Together they would send the cursor to the next line and to the left margin. Recall that escape sequence characters may be used to format strings. For example to have a string to output a double quote like: ", the string to be output needs to have the escape character \". See format1.cs.
The Char Class Methods The Char class has the following static methods:
Open table as spreadsheet Method
Description
IsDigit()
returns true if the character argument is a letter and otherwise it returns false
IsLetter()
returns true if the character argument is a letter and otherwise it returns false
IsLetterOrDigit ()
returns true if the character argument is letter or a digit and otherwise it returns false
IsLower()
returns true if the character argument is in lower case and otherwise it returns false
IsUpper()
returns true if the character argument is in upper case and otherwise it returns false
file:///D|/1/final/BBL0087.html (1 von 2) [01.12.2007 04:49:11]
The Char Class
ToUpper()
converts the character argument to upper case
ToLower()
converts the character argument to lower case
IsPunctuation()
returns true if the character argument is a punctuation symbol and other wise it returns false
IsSymbol()
returns true if the character argument is a symbol and otherwise it returns false
IsWhiteSpace()
return true if the character argument is a whiltespace and otherwise it returns false
For an example of some of the Char methods see char1.cs.
file:///D|/1/final/BBL0087.html (2 von 2) [01.12.2007 04:49:11]
Regular Expressions and the Regex Class
Regular Expressions and the Regex Class While the study of the topic of regular expressions and the class Regex are beyond these lectures, it is recommended that if programming in C# and Visual Studio .NET are in your future, then you need to study this topic. Below are listed some of the properties and methods of the class: Regex
Open table as spreadsheet Method or Property
Description
Regex()
One of several constructors
Options
Property that returns the options passed in to the constructor
IsMatch()
Method that indicates whether a match is found in the input string.
Match
Searches an input string and returns a match fora regular expression
Matches
Searches an input string and returns all successful matches for a regular expression
Replace
Replaces all occurences of a pattern with a replacement string
Split
Splits an input string into an array of substrings based on a regular expression.
As an example of using regular expressions observe the following code: string theEmailAddress = "@fau.edu"; string theMatchPerson = "dvoils"; Console.Write("Enter an e-mail address "); string theEmail = Console.ReadLine(); bool addressMatch = Regex.IsMatch(theEmail,theEmailAddress); bool nameMatch = Regex.IsMatch(theEmail, theMatchPerson); if (addressMatch) { Console.WriteLine("\nEmail address is valid."); if (nameMatch) Console.WriteLine("\nEmail user name is valid.\n\n"); else Console.WriteLine("\nThat was not a valid user name.\n\n "); } else Console.WriteLine("\nThat was not a valid email address.\n\n");
When this program runs, if the email does not include: @fau.edu, the program outputs an error message and then ends. If the email address is correct, then it outputs a statement confirming that the correct email address was entered into the program. If the correct email address has been entered, it next checks to see if the user name is: dvoils. If it is, then the program would output a confirmation statement. However if not, then the program would output a user name error message. View regularExpressions1.cs. to see how regular expressions may be used. This coverage of regular expressions was only a very brief introduction. It is advisable that this topic be studied in file:///D|/1/final/BBL0088.html (1 von 2) [01.12.2007 04:49:11]
Regular Expressions and the Regex Class
more depth, if one is going to write code for the Internet.
file:///D|/1/final/BBL0088.html (2 von 2) [01.12.2007 04:49:11]
Lecture 9 Examples
Lecture 9 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
char1.cs
Demonstrates some of the static methods of the class Char.
compareStrings.cs
Demonstrates the static string method Compare() and the equivalent operator.
concatStrings.cs
Demonstrates static string method Concat() and the + operator.
copyStrings.cs
Demonstrates static string method Copy().
equalstrings.cs
Demonstrates setting two strings to be equal does not mean that they are pointing to the same place in memory.
format1.cs
Demonstrates how to use some of the escape sequences
insertStrings.cs
Demonstrates the string method insert().
regularExpressions1. cs
Demonstrates how to use regular expressions to validate input.
removeStrings.cs
Demonstrates the string method remove() and the [ ] operator.
string1.cs
Demonstrates some of the constructors for the string class.
string2.cs
Demonstrates methods of the string class.
stringbuilder1.cs
Demonstrates constructors of the StringBuilder class.
stringbuilder2.cs
Demonstrates methods of StringBuilder.
// program_id char1.cs // author don voils // date written 11/8/2006 // // description This program demonstrates // some of the static methods of // the class Char. // using System; class theProgram { static void Main() { char[] array1 = new char[10]; for (int index = 0; index < 10; ++index) { Console.Write("\nWhat is character {0}? ", index + 1); char theChar = Char.Parse(Console.ReadLine()); array1[index] = theChar; if (Char.IsDigit(theChar)) Console.WriteLine("That was a digit."); else if (Char.IsLetter(theChar)) Console.WriteLine("That was a letter.");
file:///D|/1/final/BBL0089.html (1 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
else if (Char.IsPunctuation(theChar)) Console.WriteLine("That was a punctuation mark."); else if(Char.IsWhiteSpace(theChar)) Console.WriteLine("That was a whitespace."); else Console.WriteLine("\nI have no idea what that was."); } Console.Write("\nThe array entered is: "); Console.WriteLine(array1); Console.WriteLine("\n\n"); } }
// program_id compareStrings.cs // author don voils // date written 11/15/2006 // // description This program demonstrates // the static string method // Compare() and the equivalent // operator. // using System; class theProgram { static void Main() { char again; string theString1; string theString2; do { Console.Clear(); Console.Write("What is theString1? "); theString1 = Console.ReadLine(); Console.Write("\nWhat is theString2? "); theString2 = Console.ReadLine(); Console.WriteLine("\ntheString1 = " + theString1); Console.WriteLine("\ntheString2 = " + theString2); int theResult = string.Compare(theString1, theString2); Console.WriteLine("\nint theResult = string.Compare(theString1, theString2);"); Console.WriteLine("\nThe value of theResult is " + theResult); Console.Write("\nTherefore: "); if (theResult < 0)
file:///D|/1/final/BBL0089.html (2 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
Console.WriteLine("theString1 is less than theString2"); else if (theResult == 0) Console.WriteLine("theString1 is the same as theString2"); else Console.WriteLine("theString1 is greater than theString2"); Console.WriteLine("\nDoes theString1 equal theString2? {0}\n", theString1 == theString2); Console.Write("\nDo another example? (Y/N) "); again = char.Parse(Console.ReadLine()); } while ((again == 'y') | (again == 'Y')); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id concatStrings.cs // author don voils // date written 11/15/2006 // // description This program demonstrates // the static string method // Concat() and the + operator. // using System; class theProgram { static void Main() { char again; string theString1; string theString2; string theString3; string theString4; do { Console.Clear(); Console.Write("What is theString1? "); theString1 = Console.ReadLine(); Console.Write("\nWhat is theString2? "); theString2 = Console.ReadLine(); Console.WriteLine("\ntheString1 = " + theString1); Console.WriteLine("theString2 = " + theString2); Console.WriteLine("\nAfter: theString3 = string.Concat(theString1, theString2);"); theString3 = string.Concat(theString1, theString2); Console.WriteLine("\ntheString3 = {0}", theString3);
file:///D|/1/final/BBL0089.html (3 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
theString4 = theString1 + theString2; Console.WriteLine("\nAfter: theString4 = theString1 + theString2:"); Console.WriteLine("\ntheString4 = {0}", theString4); Console.Write("\nContinue? (Y/N) "); again = char.Parse(Console.ReadLine()); } while ((again == 'y') | (again == 'Y')); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id copyStrings.cs // author don voils // date written 11/15/2006 // // description This program demonstrates // the static string method // Copy(). // using System; class theProgram { static void Main() { char again; string theString1; string theString2; do { Console.Clear(); Console.Write("What is theString1? "); theString1 = Console.ReadLine(); Console.Write("\nWhat is theString2? "); theString2 = Console.ReadLine(); Console.WriteLine("\nBefore the copy they are:"); Console.WriteLine("\ntheString1 = " + theString1); Console.WriteLine("theString2 = " + theString2); Console.WriteLine("\ntheString2 = string.Copy(theString1);"); theString2 = string.Copy(theString1); Console.WriteLine("\nAfter the copy they are:"); Console.WriteLine("\ntheString1 = " + theString1); Console.WriteLine("theString2 = " + theString2);
file:///D|/1/final/BBL0089.html (4 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
Console.Write("\nDo another example? (Y/N)"); again = char.Parse(Console.ReadLine()); } while ((again == 'y') | (again == 'Y')); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id equalstrings.cs // author don voils // date written 11/8/2006 // // description This program demonstrates // that setting two strings // to be equal does not mean // that they are pointing to // the same place in memory. // using System; class theProgram { static void Main() { string theFirst = "This is a test."; string theSecond = theFirst; Console.WriteLine("theFirst = \"This is a test.\""); Console.WriteLine("theSecond = theFirst\n"); Console.WriteLine("theFirst is \"{0}\" and theSecond is \"{1}\"\n", theFirst, theSecond);
theSecond = "Another test"; Console.WriteLine("theSecond = \"Another test\"\n"); Console.WriteLine("theFirst is \"{0}\" and theSecond is \"{1}\"\n", theFirst, theSecond); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id format1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use some of the escape sequences.
file:///D|/1/final/BBL0089.html (5 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
// using System;
class theProgram { static void Main() { Console.WriteLine("This is\na quotations:\t \"To be or not to be\"\n\n"); Console.ReadKey(); } }
// program_id insertStrings.cs // author don voils // date written 11/15/2006 // // description This program demonstrates // the string method insert(). // // using System; class theProgram { static void Main() { char again; string theString1; string theString2; string theString3; int startWhere; do { Console.Clear(); Console.Write("What is the value for theString1? "); theString1 = Console.ReadLine(); Console.Write("What is the value for theString2? "); theString2 = Console.ReadLine(); Console.WriteLine("\ntheString1 is \"{0}\"", theString1); Console.WriteLine("\ntheString2 is \"{0}\"", theString2); Console.Write("\nAfter what position do you want to insert theString1? "); startWhere = Int32.Parse(Console.ReadLine()); theString3 = theString2.Insert(startWhere,theString1); Console.WriteLine("\ntheString3 = theString2.Insert(startWhere,theString1);"); Console.WriteLine("\ntheString1 is \"{0}\"", theString1); Console.WriteLine("\ntheString2 is \"{0}\"", theString2); Console.WriteLine("\ntheString3 is \"{0}\"", theString3); Console.Write("\nContinue? (Y/N) ");
file:///D|/1/final/BBL0089.html (6 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
again = char.Parse(Console.ReadLine()); } while ((again == 'y') | (again == 'Y')); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id regularExpressions1.cs // written_by don voils // date_written 8/14/2006 // description This program demonstrates how // to use regular expressions to // validate input. // using System; using System.Text.RegularExpressions;
class theProgram { static void Main() { string thePattern = "@fau.edu"; Console.Write("Enter an e-mail address "); string theEmail = Console.ReadLine(); bool addressMatch = Regex.IsMatch(theEmail,thePattern); if (addressMatch) Console.WriteLine("\nEmail address is valid."); else Console.WriteLine("\nThat was not a valid email address."); string theMatchPerson = "dvoils"; bool nameMatch = Regex.IsMatch(theEmail, theMatchPerson); if (nameMatch) Console.WriteLine("\nEmail user name is valid.\n\n"); else Console.WriteLine("\nThat was not a valid user name.\n\n"); Console.ReadKey(); } }
// program_id
removeStrings.cs
file:///D|/1/final/BBL0089.html (7 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
// author don voils // date written 11/15/2006 // // description This program demonstrates // the string method remove() // and the [] operator. // using System; class theProgram { static void Main() { char again; string theString1; string theString2; int startWhere; do { Console.Clear(); Console.Write("What is the value for theString1? "); theString1 = Console.ReadLine(); Console.WriteLine("\ntheString1 has {0} characters", theString1.Length); Console.Write("\nAt what position do you want to begin the removal? "); startWhere = Int32.Parse(Console.ReadLine()); theString2 = theString1.Remove(startWhere); Console.WriteLine("\ntheString2 = theString1.Remove({0})",startWhere); Console.WriteLine("\nTherefore theString1 = \"" + theString1+"\""); Console.WriteLine("\nand theString2 = \"" + theString2 +"\""); Console.Write("\nWhich character in \"{0}\" to you want to see? ",theString1); startWhere = Int32.Parse(Console.ReadLine()); Console.WriteLine("\nThe {0}th character of theString1 is \'{1}\'", startWhere, theString1[startWhere-1]); Console.Write("\nContinue? (Y/N) "); again = char.Parse(Console.ReadLine()); } while ((again == 'y') | (again == 'Y'));
Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id string1.cs // author don voils // date written 11/8/2006 //
file:///D|/1/final/BBL0089.html (8 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
// description This program demonstrates // some of the constructors for // the string class. // using System; class theProgram { static void Main() { char[ ] theArray = {'t','o',' ','b', 'e',' ','o','r',' ','n','o','t',' ','t','o',' ','b','e'}; Console.WriteLine(theArray); string theString = new string(theArray); Console.WriteLine("theString is: " + theString); string anotherString = new string(theArray,9,3); Console.WriteLine("anotherString is: " + anotherString); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id string2.cs // author don voils // date written 11/8/2006 // // description This program demonstrates // some of the methods of the // string class. // using System; class theProgram { static void Main() { char[] theArray = {'T','o',' ','B','e',' ','O','r',' ','N','o','t',' ','T','o',' ','B','e'}; int startAt = 9; int theLength = 3; Console.Write("The array is: "); Console.WriteLine(theArray); string theString = new string(theArray); Console.WriteLine("\ntheString is: " + theString);
file:///D|/1/final/BBL0089.html (9 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
Console.WriteLine("\ntheString in lower case is: " + theString.ToLower()); Console.WriteLine("\ntheString in upper case is: " + theString.ToUpper()); Console.WriteLine("\nThe substring starting at: {0} and going: {1} into theString is: {2}", startAt, theLength, theString.Substring(startAt, theLength)); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id stringbuilder1.cs // author don voils // date written 11/8/2006 // // description This program demonstrates // some of the constructors of // the StringBuilder class. // using System; using System.Text; class theProgram { static void Main() { char[ ] theArray = {'T','o',' ','B', 'e',' ','O','r',' ','N','o','t',' ','T','o',' ','B','e'}; StringBuilder Builder1 = new StringBuilder(); Console.WriteLine("The capacity of the empty Builder1 is: {0}.", Builder1.Capacity); string theString = new string(theArray); Console.WriteLine("\nThe string: \"{0}\" of Length {1} was used to create Builder2.", theString,theString.Length); StringBuilder Builder2 = new StringBuilder(theString); Console.WriteLine("\nBuilder2 is: \"{0}\" and its capacity is {1}.", Builder2,Builder2.Capacity); Console.WriteLine("\n\n"); Console.ReadKey(); } }
file:///D|/1/final/BBL0089.html (10 von 11) [01.12.2007 04:49:13]
Lecture 9 Examples
// program_id stringbuilder2.cs // author don voils // date written 11/8/2006 // // description This program demonstrates // some of the methods of // the StringBuilder class. // using System; using System.Text; class theProgram { static void Main() { char[ ] array1 = {'T','o',' ','B', 'e',' ','O','r',' ','N','o','t',' ','T','o',' ','B','e'}; string string1 = new string(array1); char[] array2 = {' ','T','h','a','t',' ','i','s',' ','t','h','e',' ','q','u','e','s','t','i','o','n'}; StringBuilder Builder1 = new StringBuilder(string1); Console.WriteLine("\nBuilder1 is:\n{0}\nand its capacity: {1}.",Builder1,Builder1.Capacity); Builder1.Append(array2); Console.WriteLine("\nBuilder1 is:\n{0}\nafter the append and its capacity is: {1}.",Builder1,Builder1.Capacity); StringBuilder Builder2 = new StringBuilder(string1); Console.WriteLine("\nBuilder2 is:\n{0}\nand its capacity: {1}.",Builder2,Builder2.Capacity); Builder2.Remove(12,6); Console.WriteLine("\nBuilder2 is:\n{0}\nafter the removal and its capacity is: {1}.",Builder2,Builder2.Capacity); Console.WriteLine("\n\n"); Console.ReadKey(); } }
file:///D|/1/final/BBL0089.html (11 von 11) [01.12.2007 04:49:13]
Lecture 10: Handling Exceptions
Lecture 10: Handling Exceptions Introduction to Error Handling Each program that you write should be designed to handle errors. One way is to let the program terminate without handling the error. This is in general an unacceptable approach. The error should be handled so that if the program must terminate, it terminates in an orderly manner. There are several ways to handle errors and the approach depends on the type of error. This lecture will only be an introduction to error handling with a brief introduction to the topic of exception handling of errors. Some of the examples previously presented in these lectures contained exception handling. The purpose of this lecture is to discuss the general concepts of exception handling used in those examples. By exception handling is meant handing runtime errors caused by abnormal conditions. With exception handling, general errors are taken care of in a general way. These errors are not taken care of at the location where they occur. In addition, exception handling is not design to handle all errors. Some of the types of errors that exception handling does not handle are: ●
asynchronous events
●
disk I/O completions
●
network messages
●
mouse clicks
●
keystrokes
●
most importantly it does not handle errors that require the program to stay at the location in the code where the error occurred.
Some of the types of errors that are handled by exceptions are: ●
out of memory errors
●
arrays that are out of bounds
●
arithmetic overflow errors
●
division by zero errors
●
invalid function parameters
●
file I/O errors
●
an attempt to use a null reference
●
an attempt to use some type of operation that is not permitted by some kind of security property.
●
most importantly it handles errors that permit the program to leave the location in the code where the error occurred.
The exception features of C# are based upon the exception features of C++. However, in C# instead of basing the exceptions on system data types and programmer data type, exceptions are handled by objects of classes. These classes are all derived from the class: Exception. The following table contains some of the members of the class Exception.
file:///D|/1/final/BBL0090.html (1 von 5) [01.12.2007 04:49:13]
Lecture 10: Handling Exceptions
Open table as spreadsheet Member
Description
Exception()
Creates an instance of the class Exception with an optional string and an optional inner exception
Exception(string); Exception(string, Exception) HelpLink
Used to link to a help file
InnerException
Returns the Exception that caused the current exception
Message
Gets a string message that describes the current exception
StackTrace
Gets a string representation of the stack frame when the exception was thrown
TargetSite
Gets the method that throws the current exception
GetBaseException()
When overridden in a derived class, this returns the exception that is the root cause of one or more of the subsequent exceptions
ToString()
Creates and returns a string representation of the current exception including much of the other available information
The following table lists some of the exception classes, a brief description of each class and a list of some of the subclasses of the Exception class:
Open table as spreadsheet Exception Class
Thrown
ApplicationException
Permits the programmer to derive excepton classes.
ArgumentException
Some of the arguments of a method are not valid
Subclasses
ArgumentNullException ArgumentOutOfRangeException DuplicateWaitObjectException
ArithmeticException
Errors occurred in an arithmetic operation
DivideByZeroException NotFiniteNumberException OverflowException
ArrayTypeMismatchException
Attempt of the wrong data type being stored in an array
BadImageFormatException
File image is incorrect
Configuration
An error when setting the configuration
ConfigurationException ContextMarshalException
An attempt to marshal an object across a boundary fails
FormatException
The format of an argument does not meet the specifications
Net.CookieException Reflection.CustomAttribute FormatException
file:///D|/1/final/BBL0090.html (2 von 5) [01.12.2007 04:49:13]
Lecture 10: Handling Exceptions
IndexOutofRangeException
An attempt to access an element of an array outside of the array limits
InvalidCastException
Invalid casting
IO. InternalBufferOverflowException
The buffer overflowed
IO.IOException
An I/O error occurred.
IO. DirectoryNotFoundExceptioni IO.EndOfStreamException IO.FileLoadException IO.FileNotFoundException IO.PathTooLongException
NullReferenceException
An attempt to dereference a null reference
OutOfMemoryException
Insufficient memory to complete the requested operation
RankException
An array with the wrong number of dimensions is attempted to be passed to a function
Resources.MissingManifest
Main assembly does not include the resources required
ResourceException SystemException
These are runtime errors
StackOverflowException
Overflow of execution stack because of too many calls to the function
To get a feeling of some of the exceptions that are built into Visual Studio .NET 2005, click on the Debug menu option as noted in the following graphic:
file:///D|/1/final/BBL0090.html (3 von 5) [01.12.2007 04:49:13]
Lecture 10: Handling Exceptions
Click on the Exceptions… option and you will see the following:
Experiment by clicking on the + mark. For example click on the + opposite the Common Language Runtime Exceptions and you will see the following options:
file:///D|/1/final/BBL0090.html (4 von 5) [01.12.2007 04:49:13]
Lecture 10: Handling Exceptions
In addition to the classes listed above that are built into the Visual Studio .NET 2005, it is also possible for the programmer to create classes derived from the Exception classes that are included in C# as will be noted in an example later in this lecture. Exception handing permits development teams to create sub teams who will work solely on error handling by using a better and more organized approach. While error handling is an important feature that needs to be considered, the programmer must be careful not to overburden the program with an excessive amounts of error handling. Where that line is between excessive and just right will only come with experience. It will also depend on the type of programs written. Hopefully those who write programs for atomic power plants, heart monitors, aircraft guidance systems, corporate accounting systems and other critical software will have an excessive amount of error checking.
file:///D|/1/final/BBL0090.html (5 von 5) [01.12.2007 04:49:13]
Basics of Exception Handling
Basics of Exception Handling C# exception handling is based on the following constructs: ●
try{ } - a block that encloses one or more functions or statements to be tested containing either the throw statement, a function call that contains a throw statement or some action that will call an exception. Any variables defined in this block are released from memory when the throw statement executes.
●
throw - an operator that throws an object of an exception class.
●
catch( ){ } - a construct that carries out an action for a particular exception argument (i.e. the exception value thrown). The argument may be an object of an exception class and the name of its exception class or just the name of the exception class.
●
finally{ } - a construct that carries out an action regardless of previous actions by catch( ) statements or the try { } block. It must immediately follow the try{ } block if there are no catch( ) statements. If there are catch( ) statements, then it must follow the last catch( ) statement.
The abstract forms of the try{ }, the catch( ), and the finally( ) blocks are: Try { // try block to be tested. } catch(exceptionclass1 arg1) { // body of action for argument arg1 of data type: // exceptionclass1 } catch(exceptionclass2 arg2) { // body of actions for argument arg2 of data type: // exceptionclass2 } ..... catch(exceptionclassn argn) { // catch functional body with argument argn of data type: // exceptionclassn ... } finally { ... }
Notice that there may be any number of catch() blocks associated with a particular try{ } block. They almost appear to be like a switch() where each catch() is the case of the switch(). Take particular note of the fact that each catch() has only one argument. In addition that the argument must be an object of an Exception derived class. The finally{ } will activate regardless of which catch( ) activates or if a catch( ) is activated at all. In the example above, the catch() statements are listed immediately after the try() block. However, the catch() could be in an entirely different part of the code as long as when the exception occurs, the program may be able to get access to the appropriate catch(). The finally{ } block is frequently used to force some action like closing a file. Therefore it is
file:///D|/1/final/BBL0091.html (1 von 2) [01.12.2007 04:49:14]
Basics of Exception Handling
always a good idea to use a finally{ } block with a try{ } block especially if it is necessary to release resources obtained by the code in the try{ } block. The arrangement of the try{ } block, the catch( ) blocks and the finally{ } block must be listed sequentially where only whitespace is permitted between them but no code. The abstract form of a throw is: throw exception;
where exception is an object of the Exception class or one of the classes derived from it. (As you will note in examples below, it is also possible for a throw to have no exception (provided it can rethrow an exception thrown from another throw statement.) The point at which a throw is executed is called the throw point. When an exception is thrown, the try{ } block is exited and the program does not (directly) return to the block with the throw point. Upon exiting the try{ } block as a result of an exception, the program searches the following listed catch( ) statements to find one that matches the argument of the catch( ) statement listed with the item thrown. If there is a match, the statements within the catch( ) body are carried out and the program does not abort. Once the catch( ) is carried out, the program jumps to the next statement after the last catch( ) (which could be a finally{ } block) and continues to execute the lines that follow. If no catch( ) is found, the system calls the terminate handler. The call of the terminate handler will result in an abnormal ending of the program. The goal of a properly written set of error handling statements is to prevent the program from ever having an abnormal termination. For example: Exception1.cs Run the program and notice that it has as output the following statements: This is the start Got into the try block The program threw the exception message: System.Exception: Error occurred at Exception1.theProgram.Main(String[], args) .... The program is in the finally block. The program will now end without aborting.
Notice within the try block that the statement after the throw is never reached. However the message inside of the catch() and the finally{ } statements are reached. Notice in the commented out statement the use of the Exception field: Message. What happens if the exception thrown does not match the argument of a catch( )? For an example of this type of occurrence see Exception1d.cs. Notice that the finally{ } statement acts but when the program terminates the last statement does not act.
file:///D|/1/final/BBL0091.html (2 von 2) [01.12.2007 04:49:14]
Throwing and Catching Exceptions
Throwing and Catching Exceptions The catch( ) does not need an argument only the exception class name is required. For example see Exception1a. cs. This action is similar to the C++ catch(…) block (or a switch()'s default case). While a catch() does not require a specific argument, it must have an argument of some type. If no argument is provided a catch( ), then the program will not compile. See Exception1e.cs. While the last program did not compile, if the parentheses are both removed, then the program will compile and then any exception that is thrown will be caught. See Exception1f.cs. This action is also similar to the C++ catch (…) block (or a switch( )'s default case). While this is possible, it is recommended not to code this way because, using this technique, it is not possible to determine the cause of the exception. If a program contains more than one catch( ) as well as a catch( ) with no argument except the exception data type, then the catch( ) with no argument must be last and of a different exception class or there will be a syntax error. For example see Exception1c.cs. The previous program: Exception1a.cs only had the try{ }, the throw and the catch( ). Now run the program Exception1b.cs which in addition, it contains a finally{ } block at the end of the catch( ) blocks. It is also possible to have a program with a try{ } and a finally{ } but with no catch( ). For an example of this type of program see: Exception2b.cs. If there had been an exception thrown within the try{ } block in this program, it would have aborted. While there may be no catch{ } blocks, then there must be a finally{ } after the try{ } block or a syntax error will occur. That is, if you comment out the finally{ } in this program, it will not compile. What happens if there is no catch( ) that has an argument that matches the exception thrown? In this case you would get an abnormal program termination. To see this case run: Exception2.CS. The output of this program will be: This is the start Got into the try block
After this program gets to the last line, it aborts. In the program Exception1.cs, an object of an exception class was defined and then the explicit object was thrown. However, it is also possible to throw the constructor of an exception class (which of course is the same as throwing an exception object). See Exception3.cs. A program does not require a throw statement to implement exception handling. This may be accomplished by some action of the program throwing an exception e.g. by exceeding the size of an array. In addition regardless of the type of the exception, using the Exception class in the catch( ), it would catch the object of any exception class. See Exception3a.cs. In the examples above, all of the try, throw and catch( ) statements were in Main(). It is also possible for all of these statements to be in a function called by Main( ). See Exception4.cs. While Exception4.cs called a function from Main() that contained the try{ }, throw and catch( ), it is also possible to call several functions. See Exception4a.cs In the previous example the try{ }, the throw and the catch( ) are in the same function. However it is also possible to place the try{ } and catch( ) in one function while the throw is in a function called from inside of the try{ } block. See Exception4c.cs. See Exception4b.cs which is the same as Exception4.cs except there is only one catch() which has the
file:///D|/1/final/BBL0092.html (1 von 2) [01.12.2007 04:49:15]
Throwing and Catching Exceptions
argument of the Exception class and as a result it will catch all exceptions. As in C++, it is possible in C# to do a rethrow from one try{ } block to another. See Exception4d.cs. See Exception5.cs that is similar to Exception4.cs except it uses an array of exceptions. Note: The exact statements that will appear when a program terminates abnormally will depend on the exception classes called by the program. Note: As seen in Exception3a.cs the throw statement is not the only thing that may throw an exception. It is also true that some functions or actions in C# also throw exceptions. For example functions like: Convert.ToInt32( ) can also throw an exception, if it is used incorrectly. See Exception7.cs. In addition if a program performs division by zero, the action may throw the exception: DivideByZeroException. For an example of this type of exception see Exception8.cs. These are only two of the many additional cases where it is possible for different actions of a program to throw an exception without an explicit throw statement. Each of these may need to be enclosed in a try { } block and have catch( ) statements available to catch the exception. Note: In one of the examples above, the program displayed a message of the exception. There are other fields that may be used in addition to Message for example the following could also be used in a program: Console.WriteLine("Member name: {0}", e.TargetSite); Console.WriteLine("Class defining member: {0}", e.TargetSite.DeclaringType); Console.WriteLine("Member type: {0}", e.TargetSite.MemberType); Console.WriteLine("Message: {0}", e.Message); Console.WriteLine("Source: {0}", e.Source); Console.WriteLine("For help contact: {0}", e.HelpLink);
For an example of a Console program that uses these fields see Exception10.cs. This is only a very brief introduction to these features. For a further study of this topic, it is recommended that more professional C# textbooks be read. For an additional example to show that it is not necessary to have a throw statement in a try{ } block see ReadingRandomAccess.cs along with the file: NewCustomer.cs Notice there is a try{ } block and a catch( ) block but no throw enclosed in the try{ } block. This is program is a Console program. Create a Console project and place these two files into the project. Compile and run it. Notice an exception is thrown. Why? (Note: This program uses some concepts that will be discussed in a later lecture.) For another example check the following program: Expenses.cs and notice the try{ } blocks and the catch( ) blocks inside of the event handlers for the buttons do not have explicit throw statements. Notice that try{ } blocks and catch() blocks are also used in an ADO .NET program. (Note: This program uses some concepts that will be discussed in a later lecture.)
file:///D|/1/final/BBL0092.html (2 von 2) [01.12.2007 04:49:15]
Programmer Defined Exception Classes
Programmer Defined Exception Classes It is possible to have a programmer defined exception class that is appropriate for actions in a program which are not covered by the class Exception or the other C# derived exception subclasses. This may be achieved by deriving a programmer exception class from one of the C# exception classes. It is recommended that the base class of such a derived class be ApplicationException. An example of where this might be needed would be for a program that requires the square root of a value. However the program should be written so that the application would not permit the handling of the square root of a negative number. Therefore exception classes could be designed to handle cases like this occurrence. For example, suppose a program was to be designed that would simulate an ATM withdrawal kiosk. Suppose that the user must enter their customer ID and then make a withdrawal. The program needs to be written so that if the user attempts to withdraw an amount that would leave a negative balance, then an exception would be thrown. This would provide a message indicating the problem. This could be done by defining the following exception class BalanceException to be derived from the exception class: ApplicationException as in the following definition: public class BalanceException :ApplicationException { private decimal balance; public BalanceException(string message, decimal theBalance):base(message) { balance = theBalance; } public decimal Balance { get { return balance; } } }
This exception class could then be used to throw an object of this exception class when the withdrawal amount exceeds the current balance as in the following class: public class Account { private string accountID; private decimal yourBalance; public void deposit(decimal theAmount) { yourBalance += theAmount; } public void withdrawal(decimal theAmount) { if(yourBalance - theAmount < 0.00m) throw new BalanceException("The withdrawal is " + "too large. The balance can not be negative.",theAmount); else yourBalance -= theAmount; } public string ID {
file:///D|/1/final/BBL0093.html (1 von 3) [01.12.2007 04:49:16]
Programmer Defined Exception Classes
get { return accountID; } set { accountID = value; } } public decimal Balance { get { return yourBalance; } set { yourBalance = value; } } }
Now what is needed is the try{ } and the catch{ } blocks to complete the implementation. For this, see the following: Private void btnWithdraw_Click(object sender, System.EventArgs e) { decimal withdrawal = decimal.Parse(txtWithdrawal.Text); try { yourAccount.withdrawal(decimal.Parse(txtWithdrawal.Text)); MessageBox.Show("Here is your money.", "Withdrew amount requested"); } catch(BalanceException f) { MessageBox.Show(String.Format("Your withdrawal of " + "{0:c} exceeds your balance. ",f.Balance),"Error"); } finally { txtWithdrawal.Visible=false; btnWithdraw.Visible=false; lblWithdraw.Visible=false; txtWithdrawal.Clear(); lblID.Visible=true; btnEnterID.Visible=true; txtAccountID.Visible=true; txtAccountID.Focus(); } }
For an example of this programmer defined exception class in action see: theATM.cs and Account.cs. Create a Windows project. Since this program was written for .NET 2003, remove the code from Form1.cs and Form1. Designer.cs and copy theATM.cs into the file: Program.cs. Add a class for Account.cs Compile and run this program. The program above was written as a test case, so there is only one sample account whose ID is: "12345". This file:///D|/1/final/BBL0093.html (2 von 3) [01.12.2007 04:49:16]
Programmer Defined Exception Classes
account has a balance of $454.43. If this program was to be used for real, then there would need to be a file which contained the ID and the balance so that any customer could use the ATM kiosk. Note: If you define several different exceptions, you must guard against the order in which the catches used are listed. That is a catch for a derived class needs to be listed before a catch which uses its base class' exceptions.
file:///D|/1/final/BBL0093.html (3 von 3) [01.12.2007 04:49:16]
Lecture 10 Examples
Lecture 10 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
Account.cs
Simulates an ATM with theATM.cs illustrating a specific exception class.
Exception1.cs
Demonstrates a try, throw and catch.
Exception1a.cs
Demonstrates a try, throw and catch work. Notice that the catch has no argument only the name of the Exception class.
Exception1b.cs
Demonstrates try, throw, catch and finally.
Exception1c.cs
Demonstrates a catch with only an exception class may not precede a catch with an object argument will not compile.
Exception1d.cs
A try, throw and catch works when the exception thrown does not match the catch.
Exception1e.cs
A catch with no argument will not compile
Exception1f.cs
Demonstrates that a while a catch with no argument will not compile, a program with a catch with no argument and no parenthesis will compile and run properly.
Exception2.cs
Demonstrates how throwing an exception object of one exception class and then attempting to catch it with another exception class will cause the program to abort.
Exception2b.cs
Demonstrates a finally may be used with a try without using any catch blocks. If an exception had been thrown, then an error would have occurred.
Exception3.cs
Demonstrates a constructor of an exception class may be used rather than an object of the exception class.
Exception3a.cs
Demonstrates that since the Exception class is the base for all exceptions classes, an object of any of these class may be caught by a catch whose argument is of the Exception data type. In addition notice that there was no throw. Using an index beyond the size of the array threw the exception.
Exception4.cs
Demonstrates an exception does not need to be in Main() but can be thrown from another function.
Exception4a.cs
Demonstrates an exception does not need to be in Main() but can be thrown from another function.
Exception4b.cs
Demonstrates that an exception thrown any type can be caught by an argument of the Exception class.
Exception4c.cs
Demonstrates how the exception does not need to be in Main() but instead can be thrown in one function and the try and catch are in another function.
Exception4d.cs
Demonstrates that an exception does not need to be in Main() but instead be thrown in one function which can be rethrown.
Exception5.cs
Demonstrates that an exception does not need to be in Main().
Exception6.cs
Demonstrates that an exception does not need to be in Main().
Exception7.cs
Demonstrates that the action of the program may throw an exception instead of a throw.
Exception8.cs
Demonstrates that the action of the program may throw an exception instead of a throw.
Exception10.cs
Demonstrates how information can be obtained from an exception.
Expenses.cs
Along with Form3.cs and a Data Form accesses the database: Expenses.mdb.
Form3.cs
Along with Expenses.cs uses a Data Form to access the database: Expenses.mdb.
NewCustomers.cs
Contains the definition of the class NewCustomer which is use for random file access both input and output.
ReadingRandomAccess. cs
Demonstrates the reading of random access files. It uses objects from the class NewCustomer from the file: NewCustomer.cs.
theATM.cs
Illustrates how a programmer may create a program specific exception class.
// program_id Account.cs // written_by don voils // date_written 11/14/2006 // description This program simulates an ATM. Along with the program // theATM.cs, it illustrates how a programmer may create // a program specific exception class. // using System; namespace theATM { /// <summary> /// Summary description for Accounts. /// public class Account
file:///D|/1/final/BBL0094.html (1 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
{ private string accountID; private decimal yourBalance; public void deposit(decimal theAmount) { yourBalance += theAmount; } public void withdrawal(decimal theAmount) { if(yourBalance - theAmount < 0.00m) throw new BalanceException("The withdrawal is too large. The balance can not be negative.", theAmount); else yourBalance -= theAmount; } public string ID { get { return accountID; } set { accountID = value; } } public decimal Balance { get { return yourBalance; } set { yourBalance = value; } } } public class BalanceException :ApplicationException { private decimal balance; public BalanceException(string message, decimal theBalance):base(message) { balance = theBalance; } public decimal Balance { get { return balance; } } } }
// program_id Exception1.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how a simple // try, throw, catch and finally work. using System; namespace Exception1 { class theProgram { static Exception theError = new Exception("Error occurred\n"); static void Main(string[] args) { Console.WriteLine("This is the start.\n");
file:///D|/1/final/BBL0094.html (2 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
try { Console.WriteLine("Got into the try block.\n"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch(Exception e) { // Run the program with the following statement and then // comment it out. Follow this with uncommenting the second statement. // Console.WriteLine("The program threw the exception message: {0}", e); // Console.WriteLine("The program threw the exception message: {0}", e.Message); } finally { Console.WriteLine("\nThe program is in the finally block.\n"); } Console.WriteLine("\nThe program will now end without aborting.\n"); } } }
// program_id Exception1a.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how a simple // try, throw and catch work. Notice that // the catch has no arguement only the name // of the Exception class. // using System; namespace Exception1a { class theProgram { static void Main(string[] args) { Console.WriteLine("This is the start.\n"); try { Console.WriteLine("Got into the try block.\n"); Exception theError = new Exception("Error occurred\n"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch(Exception) { Console.WriteLine("The program threw an exception."); } Console.WriteLine("\nThe program will now end without aborting.\n"); } } }
// program_id Exception1b.cs // written_by don voils // date_written 11/8/2006
file:///D|/1/final/BBL0094.html (3 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// description This program demonstrates how a simple // try, throw, catch and the finally work. using System; namespace Exception1b { class theProgram { static void Main(string[] args) { Console.WriteLine("This is the start.\n"); try { Console.WriteLine("Got into the try block.\n"); Exception theError = new Exception("Error occurred"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch(Exception e) { Console.WriteLine("The program threw the exception message: {0}",e); } finally { Console.WriteLine("\nThe program got to the finally with no the exception message"); } Console.WriteLine("\nThe program will now end without aborting.\n"); } } }
// program_id Exception1c.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates that a catch() // with no argument except an exception class // may not preceed a catch() with an object // argument or it will not compile. // using System; namespace Exception1c { class theProgram { static void Main(string[] args) { Console.WriteLine("This is the start.\n"); try { Console.WriteLine("Got into the try block.\n"); Exception theError = new Exception("Error occurred\n"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch(Exception) { Console.WriteLine("The program threw an exception."); }
file:///D|/1/final/BBL0094.html (4 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
catch(Exception anObject) { Console.WriteLine("This is the second catch() block."); } Console.WriteLine("\nThe program will now end without aborting.\n"); } } }
// program_id Exception1d.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how a simple // try, throw and catch works when the // exception thrown does not match // the catch. // using System; namespace Exception1 { class theProgram { static Exception theError = new Exception("Error occurred\n"); static void Main(string[] args) { Console.WriteLine("This is the start.\n"); try { Console.WriteLine("Got into the try block.\n"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch(OutOfMemoryException e) { Console.WriteLine("The program threw the exception message: {0}",e); } finally { Console.WriteLine("\nThe program is in the finally block.\n"); } Console.WriteLine("\nThe program will now end without aborting.\n"); } } }
// program_id Exception1e.cs // written_by don voils // date_written 11/13/2006 // description This program demonstrates that a catch() // with no argument will not compile. // using System; namespace Exception1e { class theProgram { static void Main(string[] args) { Console.WriteLine("This is the start.\n");
file:///D|/1/final/BBL0094.html (5 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
try { Console.WriteLine("Got into the try block.\n"); Exception theError = new Exception("Error occurred\n"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch() { Console.WriteLine("The program threw an exception."); } Console.WriteLine("\nThe program will now end without aborting.\n"); } } }
// program_id Exception1f.cs // written_by don voils // date_written 11/13/2006 // description This program demonstrates that a while a catch() // with no argument will not compile, a program with // a catch with no argument and no parenthesis will // compile and run properly actually catching the // exception. // using System; namespace Exception1f { class theProgram { static void Main(string[] args) { Console.WriteLine("This is the start.\n"); try { Console.WriteLine("Got into the try block.\n"); Exception theError = new Exception("Error occurred\n"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch { Console.WriteLine("The program threw an exception."); } Console.WriteLine("\nThe program will now end without aborting.\n"); } } }
// program_id Exception2.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how throwing // an exception object of one exception // class and then attempting to catch it // with another exception class will cause
file:///D|/1/final/BBL0094.html (6 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// //
the program to abort.
using System; namespace Exception2 { class theProgram { static void Main(string[] args) { Console.WriteLine("This is the start.\n"); try { Console.WriteLine("\nGot into the try block."); FormatException theError = new FormatException("Error occurred\n"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch(ArithmeticException e) { Console.WriteLine("The program threw the exception message: {0}",e); } Console.WriteLine("\nThe program will now end without aborting"); } } }
// program_id Exception2b.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates the finally // block may be used with a try block without // using any catch blocks. If an exception had // been thrown then an error would have occurred. // using System; namespace Exception2b { class theProgram { static void Main(string[] args) { Console.WriteLine("This is the start.\n"); try { Console.WriteLine("\nGot into the try block."); } finally { Console.WriteLine("\nGot into the finally block."); } Console.WriteLine("\nThe program will now end without aborting.\n"); } } }
// program_id Exception3.cs // written_by don voils
file:///D|/1/final/BBL0094.html (7 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// date_written 11/8/2006 // description This program demonstrates how the // constructor of an exception class // may be used rather than an object // of the exception class. using System; namespace Exception3 { class theProgram { static void Main(string[] args) { Console.WriteLine("This is the start."); try { Console.WriteLine("Got into the try block."); throw new Exception(); // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch(Exception e) { Console.WriteLine("The program threw the exception message: {0}",e); } Console.WriteLine("The program will now end without aborting"); } } }
// program_id Exception3a.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates that since // the Exception class is the base for // all exceptions classes, an object of // any of these class may be caught by a // catch whose argument is of the Exception // data type. In addition notice that there // was no throw. Using an index beyond the // size of the array threw the exception. // using System; namespace Exception3a { class theProgram { static IndexOutOfRangeException theObject = new IndexOutOfRangeException("The index out of range exception\n"); static void Main(string[] args) { Console.WriteLine("Start of Main()\n"); decimal[] theArray = new decimal[5]; try { Console.WriteLine("The value is {0}",theArray[5]); } catch(Exception Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } Console.WriteLine("\nThe successful end of Main()\n");
file:///D|/1/final/BBL0094.html (8 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
} } }
// program_id Exception4.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how the // exception does not need to be in Main(). // Instead it can be thrown in another function. // Notice that each type of exception is identified. // using System; namespace Exception4 { class theProgram { static Exception e1 = new Exception("The general exception.\n"); static ArithmeticException e2 = new ArithmeticException("The arithmetic exception.\n"); static OutOfMemoryException e3 = new OutOfMemoryException("The out of memory exception.\n"); static IndexOutOfRangeException e4 = new IndexOutOfRangeException("The index out of range exception\n"); static void Main(string[] args) { Console.WriteLine("Start of Main()\n"); MYTEST(e4); MYTEST(e3); MYTEST(e2); MYTEST(e1); Console.WriteLine("\nThe successful end of Main()\n"); } static void MYTEST(Exception theValue) { try { throw theValue; } catch(IndexOutOfRangeException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(OutOfMemoryException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(ArithmeticException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(Exception Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } } } }
// program_id Exception4a.cs // written_by don voils
file:///D|/1/final/BBL0094.html (9 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// date_written 11/8/2006 // description This program demonstrates how the // exception does not need to be in Main(). // Instead it can be thrown in another function. // Notice that each type of exception is identified. // using System; namespace Exception4a { class theProgram { static Exception e1 = new Exception("The general exception.\n"); static ArithmeticException e2 = new ArithmeticException("The arithmetic exception.\n"); static OutOfMemoryException e3 = new OutOfMemoryException("The out of memory exception.\n"); static IndexOutOfRangeException e4 = new IndexOutOfRangeException("The index out of range exception\n"); static void Main(string[] args) { Console.WriteLine("Start of Main()\n"); MYTEST1(e4); Console.WriteLine("Back into Main()\n"); MYTEST1(e3); Console.WriteLine("Back into Main()\n"); MYTEST1(e2); Console.WriteLine("Back into Main()\n"); MYTEST1(e1); Console.WriteLine("\nThe successful end of Main()\n"); } static void MYTEST1(Exception theValue) { Console.WriteLine("Got into the function MYTEST1()\n"); MYTEST2(theValue); } static void MYTEST2(Exception theValue) { Console.WriteLine("Got into the function MYTEST2()\n"); try { throw theValue; } catch(IndexOutOfRangeException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(OutOfMemoryException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(ArithmeticException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(Exception Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } } } }
file:///D|/1/final/BBL0094.html (10 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// program_id Exception4b.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how the // exception thrown can be of any type // and that if the catch() argument is // of the Exception class, it will catch // any exception thrown. // using System; namespace Exception4b { class theProgram { static Exception e1 = new Exception("The general exception.\n"); static ArithmeticException e2 = new ArithmeticException("The arithmetic exception.\n"); static OutOfMemoryException e3 = new OutOfMemoryException("The out of memory exception.\n"); static IndexOutOfRangeException e4 = new IndexOutOfRangeException("The index out of range exception\n"); static void Main(string[] args) { Console.WriteLine("Start of Main()\n"); MYTEST(e4); MYTEST(e3); MYTEST(e2); MYTEST(e1); Console.WriteLine("\nThe successful end of Main()\n"); } static void MYTEST(Exception theValue) { try { throw theValue; } catch(Exception Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } } } }
// program_id Exception4c.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how the // exception does not need to be in Main(). // Instead it can have a throw in one function // while the try and catch are in another function. // using System; namespace Exception4c { class theProgram
file:///D|/1/final/BBL0094.html (11 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
{ static Exception e1 = new Exception("The general exception.\n"); static ArithmeticException e2 = new ArithmeticException("The arithmetic exception.\n"); static OutOfMemoryException e3 = new OutOfMemoryException("The out of memory exception.\n"); static IndexOutOfRangeException e4 = new IndexOutOfRangeException("The index out of range exception\n"); static void Main(string[] args) { Console.WriteLine("Start of Main()\n"); MYTEST1(e4); Console.WriteLine("Back into Main()\n"); MYTEST1(e3); Console.WriteLine("Back into Main()\n"); MYTEST1(e2); Console.WriteLine("Back into Main()\n"); MYTEST1(e1); Console.WriteLine("\nThe successful end of Main()\n"); } static void MYTEST1(Exception theValue) { Console.WriteLine("Got into the function MYTEST1()\n"); try { MYTEST2(theValue); } catch(IndexOutOfRangeException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(OutOfMemoryException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(ArithmeticException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(Exception Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } } static void MYTEST2(Exception theValue) { Console.WriteLine("Got into the function MYTEST2()\n"); throw theValue; } } }
// program_id Exception4d.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how the // exception does not need to be in Main(). // Instead it can have a throw in one function // which can the be rethrown into another function. //
file:///D|/1/final/BBL0094.html (12 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
using System; namespace Exception4d { class theProgram { static Exception e1 = new Exception("The general exception.\n"); static ArithmeticException e2 = new ArithmeticException("The arithmetic exception.\n"); static OutOfMemoryException e3 = new OutOfMemoryException("The out of memory exception.\n"); static IndexOutOfRangeException e4 = new IndexOutOfRangeException("The index out of range exception\n"); static void Main(string[] args) { Console.WriteLine("Start of Main()\n"); MYTEST1(e4); Console.WriteLine("Back into Main()\n"); MYTEST1(e3); Console.WriteLine("Back into Main()\n"); MYTEST1(e2); Console.WriteLine("Back into Main()\n"); MYTEST1(e1); Console.WriteLine("\nThe successful end of Main()\n"); } static void MYTEST1(Exception theValue) { Console.WriteLine("Got into the function MYTEST1()\n"); try { MYTEST2(theValue); } catch(IndexOutOfRangeException Avalue) { Console.WriteLine("\nInside of MYTEST1() caught the: {0}",Avalue); } catch(OutOfMemoryException Avalue) { Console.WriteLine("\nInside of MYTEST1() caught the: {0}",Avalue); } catch(ArithmeticException Avalue) { Console.WriteLine("\nInside of MYTEST1() caught the: {0}",Avalue); } catch(Exception Avalue) { Console.WriteLine("\nInside of MYTEST1() caught the: {0}",Avalue); } } static void MYTEST2(Exception theValue) { Console.WriteLine("Got into the function MYTEST2()\n"); try { throw theValue; } catch(IndexOutOfRangeException Avalue) { Console.WriteLine("\nInside of MYTEST2() caught the: {0}",Avalue); } catch(OutOfMemoryException Avalue) { Console.WriteLine("\nInside of MYTEST2() caught the: {0}",Avalue);
file:///D|/1/final/BBL0094.html (13 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
} catch(ArithmeticException Avalue) { Console.WriteLine("\nInside of MYTEST2() caught the: {0}",Avalue); } catch(Exception Avalue) { Console.WriteLine("\nInside of MYTEST2() caught the: {0}",Avalue); } } } }
// program_id Exception5.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how the // exception does not need to be in Main(). // Instead it can be thrown in another function. // Notice that each type of exception is identified. // This program is similar to Exception4.cs except // it uses an array of exceptions. // using System; namespace Exception5 { class theProgram { static Exception e1 = new Exception("The general exception.\n"); static ArithmeticException e2 = new ArithmeticException("The arithmetic exception.\n"); static OutOfMemoryException e3 = new OutOfMemoryException("The out of memory exception.\n"); static IndexOutOfRangeException e4 = new IndexOutOfRangeException("The index out of range exception\n"); static void Main(string[] args) { Console.WriteLine("Start of Main()\n"); Exception[] theException = new Exception[4] {e4, e3, e2, e1}; foreach(Exception theOne in theException) { MYTEST(theOne); } Console.WriteLine("\nThe successful end of Main()\n"); } static void MYTEST(Exception theValue) { try { throw theValue; } catch(IndexOutOfRangeException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(OutOfMemoryException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(ArithmeticException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(Exception Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue);
file:///D|/1/final/BBL0094.html (14 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
} } } }
// program_id Exception6.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how the // exception does not need to be in Main(). // Instead it can be thrown in another function. // Notice that each type of exception is identified. // This program is similar to Exception4.cs except // it uses an array of exceptions. // using System; namespace Exception6 { class theProgram { static Exception e1 = new Exception("The general exception.\n"); static ArithmeticException e2 = new ArithmeticException("The arithmetic exception.\n"); static OutOfMemoryException e3 = new OutOfMemoryException("The out of memory exception.\n"); static IndexOutOfRangeException e4 = new IndexOutOfRangeException("The index out of range exception\n"); static void Main(string[] args) { Console.WriteLine("Start of Main()\n"); Exception[] theException = new Exception[4] {e4, e3, e2, e1};
// // // // // // // { // // } // // // //
// // try
foreach(Exception theOne in theException) { [ int a = 5; //
MYTEST(theOne);
} finally() int b = 6; catch(IndexOutOfRangeException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); }
// // // // // // / // // // // // //
catch(OutOfMemoryException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(ArithmeticException Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } catch(Exception Avalue) { Console.WriteLine("\nCaught the: {0}",Avalue); } }
//
Console.WriteLine("\nThe successful end of Main()\n"); }
// // // // //
static void MYTEST(Exception theValue) { Console.WriteLine("Inside of MYTEST()."; throw theValue; } }
}
file:///D|/1/final/BBL0094.html (15 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// program_id Exception7.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how the // exception does not need to be a thrown // by a throw but by the action of the program. // // using System; namespace Exception7 { class theProgram { static void Main(string[] args) { int intNumber; string stringNumber; char theAnswer = 'Y'; while((theAnswer=='Y') || (theAnswer=='y')) { Console.Write("What is the number? "); stringNumber = Console.ReadLine(); try { intNumber = Convert.ToInt32(stringNumber); Console.WriteLine("\nThe number is {0}",intNumber); } catch(Exception e) { Console.WriteLine("\nThe Exception message is {0}",e.Message); } Console.Write("\nContinue? Y/N "); theAnswer = char.Parse(Console.ReadLine()); Console.WriteLine("\n"); } } } }
// program_id Exception8.cs // written_by don voils // date_written 11/8/2006 // description This program demonstrates how the // exception does not need to be a thrown // by a throw but by the action of the program. // // using System; namespace Exception8 { class theProgram { static void Main(string[] args) { int firstNumber, secondNumber, thirdNumber; string stringNumber; char theAnswer = 'Y'; while((theAnswer=='Y') || (theAnswer=='y')) { try {
file:///D|/1/final/BBL0094.html (16 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
Console.Write("\nWhat is the first number? "); stringNumber = Console.ReadLine(); firstNumber = Convert.ToInt16(stringNumber); Console.Write("\nWhat is the second number? "); stringNumber = Console.ReadLine(); secondNumber = Convert.ToInt16(stringNumber); thirdNumber = firstNumber/secondNumber; Console.WriteLine("\n{0}/{1} = {2}\n", firstNumber,secondNumber,thirdNumber); Console.Write("\nContinue? Y/N "); theAnswer = char.Parse(Console.ReadLine()); Console.Clear(); } catch(Exception e) { Console.WriteLine("\nThe Exception message is {0}",e.Message); } } } } }
// program_id Exception10.cs // written_by don voils // date_written 11/12/2006 // description This program demonstrates some of the // possible information that is possible // to obtain in an exception. This approach // should normally only be used for debugging. // using System; namespace Exception1 { class theProgram { static Exception theError = new Exception("Error occurred"); static void Main(string[] args) { theError.HelpLink = "http://mat.com"; Console.WriteLine("This is the start.\n"); try { Console.WriteLine("Got into the try block.\n"); throw theError; // Notice the warning error for this line which says // that this line will never be reached. // Console.WriteLine("This line of code is not reached."); } catch (Exception e) { Console.WriteLine("Member name: {0}", e.TargetSite); Console.WriteLine("Class defining member: {0}", e.TargetSite.DeclaringType); Console.WriteLine("Member type: {0}", e.TargetSite.MemberType); Console.WriteLine("Message: {0}", e.Message); Console.WriteLine("Source: {0}", e.Source); Console.WriteLine("For help contact: {0}", e.HelpLink); } finally { Console.WriteLine("\nThe program is in the finally block.\n"); } Console.WriteLine("\nThe program will now end without aborting.\n");
file:///D|/1/final/BBL0094.html (17 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
} } }
// program_id Expenses.cs // written_by don voils // date_written 3/12/2006 // description This program along with Form3.cs uses // a Data Form to create access to the // database: Expenses.mdb. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace PostingExpenses { /// <summary> /// Summary description for Expenses. /// public class Expenses : System.Windows.Forms.Form { private System.Data.OleDb.OleDbCommand oleDbSelectCommand1; private System.Data.OleDb.OleDbCommand oleDbInsertCommand1; private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1; private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1; private System.Data.OleDb.OleDbCommand oleDbSelectCommand2; private System.Data.OleDb.OleDbCommand oleDbInsertCommand2; private System.Data.OleDb.OleDbCommand oleDbUpdateCommand2; private System.Data.OleDb.OleDbCommand oleDbDeleteCommand2; private System.Data.OleDb.OleDbConnection oleDbConnection1; private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1; private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter2; private PostingExpenses.TheExpenses objTheExpenses; private System.Windows.Forms.Button btnLoad; private System.Windows.Forms.Button btnUpdate; private System.Windows.Forms.Button btnCancelAll; private System.Windows.Forms.Label lblGL_Account_Name; private System.Windows.Forms.TextBox editGL_Account_Name; private System.Windows.Forms.Label lblGL_Account_Number; private System.Windows.Forms.TextBox editGL_Account_Number; private System.Windows.Forms.Button btnNavFirst; private System.Windows.Forms.Button btnNavPrev; private System.Windows.Forms.Label lblNavLocation; private System.Windows.Forms.Button btnNavNext; private System.Windows.Forms.Button btnLast; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.DataGrid grdChecks; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.ToolTip toolTip2; private System.ComponentModel.IContainer components; public Expenses() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose( bool disposing )
file:///D|/1/final/BBL0094.html (18 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
{ if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection(); this.oleDbInsertCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbUpdateCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbDeleteCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbSelectCommand2 = new System.Data.OleDb.OleDbCommand(); this.oleDbInsertCommand2 = new System.Data.OleDb.OleDbCommand(); this.oleDbUpdateCommand2 = new System.Data.OleDb.OleDbCommand(); this.oleDbDeleteCommand2 = new System.Data.OleDb.OleDbCommand(); this.oleDbDataAdapter1 = new System.Data.OleDb.OleDbDataAdapter(); this.oleDbDataAdapter2 = new System.Data.OleDb.OleDbDataAdapter(); this.objTheExpenses = new PostingExpenses.TheExpenses(); this.btnLoad = new System.Windows.Forms.Button(); this.btnUpdate = new System.Windows.Forms.Button(); this.btnCancelAll = new System.Windows.Forms.Button(); this.lblGL_Account_Name = new System.Windows.Forms.Label(); this.editGL_Account_Name = new System.Windows.Forms.TextBox(); this.lblGL_Account_Number = new System.Windows.Forms.Label(); this.editGL_Account_Number = new System.Windows.Forms.TextBox(); this.btnNavFirst = new System.Windows.Forms.Button(); this.btnNavPrev = new System.Windows.Forms.Button(); this.lblNavLocation = new System.Windows.Forms.Label(); this.btnNavNext = new System.Windows.Forms.Button(); this.btnLast = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.grdChecks = new System.Windows.Forms.DataGrid(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.toolTip2 = new System.Windows.Forms.ToolTip(this.components); ((System.ComponentModel.ISupportInitialize)(this.objTheExpenses)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.grdChecks)).BeginInit(); this.SuspendLayout(); // // oleDbSelectCommand1 // this.oleDbSelectCommand1.CommandText = "SELECT [GL Account Name], [GL Account Number] FROM [GL Accounts]"; this.oleDbSelectCommand1.Connection = this.oleDbConnection1; // // oleDbConnection1 // this.oleDbConnection1.ConnectionString = @"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Data Source=""C:\Documents and Settings\Don Voils\My Documents\Visual Studio Projects\Expenses.mdb"";Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Mode=Share Deny None;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False"; // // oleDbInsertCommand1 // this.oleDbInsertCommand1.CommandText = "INSERT INTO [GL Accounts] ([GL Account Name], [GL Account Number]) VALUES (?, ?)"; this.oleDbInsertCommand1.Connection = this.oleDbConnection1; this.oleDbInsertCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("GL_Account_Name", System.Data.OleDb. OleDbType.VarWChar, 50, "GL Account Name")); this.oleDbInsertCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("GL_Account_Number", System.Data.OleDb. OleDbType.Integer, 0, "GL Account Number")); // // oleDbUpdateCommand1 //
file:///D|/1/final/BBL0094.html (19 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
this.oleDbUpdateCommand1.CommandText = "UPDATE [GL Accounts] SET [GL Account Name] = ?, [GL Account Number] = ? WHERE ([G" + "L Account Number] = ?) AND ([GL Account Name] = ?)"; this.oleDbUpdateCommand1.Connection = this.oleDbConnection1; this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("GL_Account_Name", System.Data.OleDb. OleDbType.VarWChar, 50, "GL Account Name")); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("GL_Account_Number", System.Data.OleDb. OleDbType.Integer, 0, "GL Account Number")); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_GL_Account_Number", System.Data. OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "GL Account Number", System. Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_GL_Account_Name", System.Data.OleDb. OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "GL Account Name", System.Data. DataRowVersion.Original, null)); // // oleDbDeleteCommand1 // this.oleDbDeleteCommand1.CommandText = "DELETE FROM [GL Accounts] WHERE ([GL Account Number] = ?) AND ([GL Account Name] "+ "= ?)"; this.oleDbDeleteCommand1.Connection = this.oleDbConnection1; this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_GL_Account_Number", System.Data. OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "GL Account Number", System. Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_GL_Account_Name", System.Data.OleDb. OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "GL Account Name", System.Data. DataRowVersion.Original, null)); // // oleDbSelectCommand2 // this.oleDbSelectCommand2.CommandText = "SELECT [Check Amount], [Check Date], [Check Number], [GL Account Number], [Payee " + "Name] FROM Checks"; this.oleDbSelectCommand2.Connection = this.oleDbConnection1; // // oleDbInsertCommand2 // this.oleDbInsertCommand2.CommandText = "INSERT INTO Checks([Check Amount], [Check Date], [Check Number], [GL Account Numb" + "er], [Payee Name]) VALUES (?, ?, ?, ?, ?)"; this.oleDbInsertCommand2.Connection = this.oleDbConnection1; this.oleDbInsertCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Check_Amount", System.Data.OleDb.OleDbType. Currency, 0, "Check Amount")); this.oleDbInsertCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Check_Date", System.Data.OleDb.OleDbType. DBDate, 0, "Check Date")); this.oleDbInsertCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Check_Number", System.Data.OleDb.OleDbType. Integer, 0, "Check Number")); this.oleDbInsertCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("GL_Account_Number", System.Data.OleDb. OleDbType.Integer, 0, "GL Account Number")); this.oleDbInsertCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Payee_Name", System.Data.OleDb.OleDbType. VarWChar, 20, "Payee Name")); // // oleDbUpdateCommand2 // this.oleDbUpdateCommand2.CommandText = @"UPDATE Checks SET [Check Amount] = ?, [Check Date] = ?, [Check Number] = ?, [GL Account Number] = ?, [Payee Name] = ? WHERE ([Check Number] = ?) AND ([Check Amount] = ?) AND ([Check Date] = ? OR ? IS NULL AND [Check Date] IS NULL) AND ([GL Account Number] = ? OR ? IS NULL AND [GL Account Number] IS NULL) AND ([Payee Name] = ?)"; this.oleDbUpdateCommand2.Connection = this.oleDbConnection1; this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Check_Amount", System.Data.OleDb.OleDbType. Currency, 0, "Check Amount")); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Check_Date", System.Data.OleDb.OleDbType. DBDate, 0, "Check Date")); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Check_Number", System.Data.OleDb.OleDbType. Integer, 0, "Check Number")); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("GL_Account_Number", System.Data.OleDb. OleDbType.Integer, 0, "GL Account Number")); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Payee_Name", System.Data.OleDb.OleDbType. VarWChar, 20, "Payee Name")); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Check_Number", System.Data.OleDb. OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Check Number", System.Data. DataRowVersion.Original, null)); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Check_Amount", System.Data.OleDb. OleDbType.Currency, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Check Amount", System.Data. DataRowVersion.Original, null)); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Check_Date", System.Data.OleDb. OleDbType.DBDate, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Check Date", System.Data. DataRowVersion.Original, null)); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Check_Date1", System.Data.OleDb.
file:///D|/1/final/BBL0094.html (20 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
OleDbType.DBDate, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Check Date", System.Data. DataRowVersion.Original, null)); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_GL_Account_Number", System.Data. OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "GL Account Number", System. Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_GL_Account_Number1", System.Data. OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false,s ((System.Byte)(0)), ((System.Byte)(0)), "GL Account Number", System. Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Payee_Name", System.Data.OleDb. OleDbType.VarWChar, 20, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Payee Name", System.Data. DataRowVersion.Original, null)); // // oleDbDeleteCommand2 // this.oleDbDeleteCommand2.CommandText = "DELETE FROM Checks WHERE ([Check Number] = ?) AND ([Check Amount] = ?) AND ([Chec" + "k Date] = ? OR ? IS NULL AND [Check Date] IS NULL) AND ([GL Account Number] = ? " + "OR ? IS NULL AND [GL Account Number] IS NULL) AND ([Payee Name] = ?)"; this.oleDbDeleteCommand2.Connection = this.oleDbConnection1; this.oleDbDeleteCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Check_Number", System.Data.OleDb.OleDbType. Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Check Number", System.Data.DataRowVersion. Original, null)); this.oleDbDeleteCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Check_Amount", System.Data.OleDb. OleDbType.Currency, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Check Amount", System.Data. DataRowVersion.Original, null)); this.oleDbDeleteCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Check_Date", System.Data.OleDb. OleDbType.DBDate, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Check Date", System.Data. DataRowVersion.Original, null)); this.oleDbDeleteCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Check_Date1", System.Data.OleDb. OleDbType.DBDate, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Check Date", System.Data. DataRowVersion.Original, null)); this.oleDbDeleteCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_GL_Account_Number", System.Data. OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "GL Account Number", System. Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_GL_Account_Number1", System.Data. OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "GL Account Number", System. Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_Payee_Name", System.Data.OleDb. OleDbType.VarWChar, 20, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "Payee Name", System.Data. DataRowVersion.Original, null)); // // oleDbDataAdapter1 // this.oleDbDataAdapter1.DeleteCommand = this.oleDbDeleteCommand1; this.oleDbDataAdapter1.InsertCommand = this.oleDbInsertCommand1; this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1; this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] { new System.Data.Common.DataTableMapping("Table", "GL Accounts", new System.Data.Common.DataColumnMapping[] { new System.Data.Common.DataColumnMapping("GL Account Name", "GL Account Name"), new System.Data.Common.DataColumnMapping("GL Account Number", "GL Account Number")})}); this.oleDbDataAdapter1.UpdateCommand = this.oleDbUpdateCommand1; // // oleDbDataAdapter2 // this.oleDbDataAdapter2.DeleteCommand = this.oleDbDeleteCommand2; this.oleDbDataAdapter2.InsertCommand = this.oleDbInsertCommand2; this.oleDbDataAdapter2.SelectCommand = this.oleDbSelectCommand2; this.oleDbDataAdapter2.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] { new System.Data.Common.DataTableMapping("Table", "Checks", new System. Data.Common.DataColumnMapping[] { new System.Data.Common. DataColumnMapping("Check Amount", "Check Amount"), new System.Data.Common. DataColumnMapping("Check Date", "Check Date"), new System.Data.Common. DataColumnMapping("Check Number", "Check Number"), new System.Data.Common. DataColumnMapping("GL Account Number", "GL Account Number"), new System.Data.Common. DataColumnMapping("Payee Name", "Payee Name")})}); this.oleDbDataAdapter2.UpdateCommand = this.oleDbUpdateCommand2; // // objTheExpenses //
file:///D|/1/final/BBL0094.html (21 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
this.objTheExpenses.DataSetName = "TheExpenses"; this.objTheExpenses.Locale = new System.Globalization.CultureInfo("en-US"); // // btnLoad // this.btnLoad.Location = new System.Drawing.Point(10, 10); this.btnLoad.Name = "btnLoad"; this.btnLoad.TabIndex = 0; this.btnLoad.Text = "&Load"; this.toolTip1.SetToolTip(this.btnLoad, "Loads records from both tables"); this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // btnUpdate // this.btnUpdate.Location = new System.Drawing.Point(365, 10); this.btnUpdate.Name = "btnUpdate"; this.btnUpdate.TabIndex = 1; this.btnUpdate.Text = "&Update"; this.toolTip1.SetToolTip(this.btnUpdate, "Updates data in database"); this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click); // // btnCancelAll // this.btnCancelAll.Location = new System.Drawing.Point(365, 43); this.btnCancelAll.Name = "btnCancelAll"; this.btnCancelAll.TabIndex = 2; this.btnCancelAll.Text = "Ca&ncel All"; this.toolTip1.SetToolTip(this.btnCancelAll, "Cancels All current changes"); this.btnCancelAll.Click += new System.EventHandler(this.btnCancelAll_Click); // // lblGL_Account_Name // this.lblGL_Account_Name.Location = new System.Drawing.Point(10, 76); this.lblGL_Account_Name.Name = "lblGL_Account_Name"; this.lblGL_Account_Name.TabIndex = 3; this.lblGL_Account_Name.Text = "GL Account Name"; // // editGL_Account_Name // this.editGL_Account_Name.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.objTheExpenses, "GL Accounts.GL Account Name")); this.editGL_Account_Name.Location = new System.Drawing.Point(120, 76); this.editGL_Account_Name.Name = "editGL_Account_Name"; this.editGL_Account_Name.ReadOnly = true; this.editGL_Account_Name.TabIndex = 4; this.editGL_Account_Name.Text = ""; // // lblGL_Account_Number // this.lblGL_Account_Number.Location = new System.Drawing.Point(230, 76); this.lblGL_Account_Number.Name = "lblGL_Account_Number"; this.lblGL_Account_Number.TabIndex = 5; this.lblGL_Account_Number.Text = "GL Account Number"; // // editGL_Account_Number // this.editGL_Account_Number.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.objTheExpenses, "GL Accounts.GL Account Number")); this.editGL_Account_Number.Location = new System.Drawing.Point(340, 76); this.editGL_Account_Number.Name = "editGL_Account_Number"; this.editGL_Account_Number.ReadOnly = true; this.editGL_Account_Number.TabIndex = 6; this.editGL_Account_Number.Text = ""; // // btnNavFirst // this.btnNavFirst.Location = new System.Drawing.Point(195, 109); this.btnNavFirst.Name = "btnNavFirst"; this.btnNavFirst.Size = new System.Drawing.Size(40, 23); this.btnNavFirst.TabIndex = 7; this.btnNavFirst.Text = "<<"; this.btnNavFirst.Click += new System.EventHandler(this.btnNavFirst_Click); // // btnNavPrev // this.btnNavPrev.Location = new System.Drawing.Point(235, 109); this.btnNavPrev.Name = "btnNavPrev";
file:///D|/1/final/BBL0094.html (22 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
this.btnNavPrev.Size = new System.Drawing.Size(35, 23); this.btnNavPrev.TabIndex = 8; this.btnNavPrev.Text = "<"; this.btnNavPrev.Click += new System.EventHandler(this.btnNavPrev_Click); // // lblNavLocation // this.lblNavLocation.BackColor = System.Drawing.Color.White; this.lblNavLocation.Location = new System.Drawing.Point(270, 109); this.lblNavLocation.Name = "lblNavLocation"; this.lblNavLocation.Size = new System.Drawing.Size(95, 23); this.lblNavLocation.TabIndex = 9; this.lblNavLocation.Text = "No Records"; this.lblNavLocation.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btnNavNext // this.btnNavNext.Location = new System.Drawing.Point(365, 109); this.btnNavNext.Name = "btnNavNext"; this.btnNavNext.Size = new System.Drawing.Size(35, 23); this.btnNavNext.TabIndex = 10; this.btnNavNext.Text = ">"; this.btnNavNext.Click += new System.EventHandler(this.btnNavNext_Click); // // btnLast // this.btnLast.Location = new System.Drawing.Point(400, 109); this.btnLast.Name = "btnLast"; this.btnLast.Size = new System.Drawing.Size(40, 23); this.btnLast.TabIndex = 11; this.btnLast.Text = ">>"; this.btnLast.Click += new System.EventHandler(this.btnLast_Click); // // btnAdd // this.btnAdd.Location = new System.Drawing.Point(195, 142); this.btnAdd.Name = "btnAdd"; this.btnAdd.TabIndex = 12; this.btnAdd.Text = "&Add"; this.toolTip1.SetToolTip(this.btnAdd, "Adds new GL records"); this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(280, 142); this.btnDelete.Name = "btnDelete"; this.btnDelete.TabIndex = 13; this.btnDelete.Text = "&Delete"; this.toolTip1.SetToolTip(this.btnDelete, "Deletes current records of both tables"); this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(365, 142); this.btnCancel.Name = "btnCancel"; this.btnCancel.TabIndex = 14; this.btnCancel.Text = "&Cancel"; this.toolTip1.SetToolTip(this.btnCancel, "Cancels the current changes"); this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // grdChecks // this.grdChecks.AllowNavigation = false; this.grdChecks.DataMember = "GL Accounts.Expenses"; this.grdChecks.DataSource = this.objTheExpenses; this.grdChecks.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.grdChecks.Location = new System.Drawing.Point(10, 175); this.grdChecks.Name = "grdChecks"; this.grdChecks.Size = new System.Drawing.Size(478, 292); this.grdChecks.TabIndex = 15; // // Expenses // this.AutoScaleBaseSize = new System.Drawing.Size(6, 13); this.ClientSize = new System.Drawing.Size(497, 442); this.Controls.Add(this.btnLoad);
file:///D|/1/final/BBL0094.html (23 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
this.Controls.Add(this.btnUpdate); this.Controls.Add(this.btnCancelAll); this.Controls.Add(this.lblGL_Account_Name); this.Controls.Add(this.editGL_Account_Name); this.Controls.Add(this.lblGL_Account_Number); this.Controls.Add(this.editGL_Account_Number); this.Controls.Add(this.btnNavFirst); this.Controls.Add(this.btnNavPrev); this.Controls.Add(this.lblNavLocation); this.Controls.Add(this.btnNavNext); this.Controls.Add(this.btnLast); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnCancel); this.Controls.Add(this.grdChecks); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Name = "Expenses"; this.Text = "Expenses"; ((System.ComponentModel.ISupportInitialize)(this.objTheExpenses)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.grdChecks)).EndInit(); this.ResumeLayout(false); } #endregion public void FillDataSet(PostingExpenses.TheExpenses dataSet) { // Turn off constraint checking before the dataset is filled. // This allows the adapters to fill the dataset without concern // for dependencies between the tables. dataSet.EnforceConstraints = false; try { // Open the connection. this.oleDbConnection1.Open(); // Attempt to fill the dataset through the OleDbDataAdapter1. this.oleDbDataAdapter1.Fill(dataSet); this.oleDbDataAdapter2.Fill(dataSet); } catch (System.Exception fillException) { // Add your error handling code here. throw fillException; } finally { // Turn constraint checking back on. dataSet.EnforceConstraints = true; // Close the connection whether or not the exception was thrown. this.oleDbConnection1.Close(); } } public void UpdateDataSource(PostingExpenses.TheExpenses ChangedRows) { try { // The data source only needs to be updated if there are changes pending. if ((ChangedRows != null)) { // Open the connection. this.oleDbConnection1.Open(); // Attempt to update the data source. oleDbDataAdapter1.Update(ChangedRows); oleDbDataAdapter2.Update(ChangedRows); } } catch (System.Exception updateException) { // Add your error handling code here. throw updateException; } finally { // Close the connection whether or not the exception was thrown.
file:///D|/1/final/BBL0094.html (24 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
this.oleDbConnection1.Close(); } } public void LoadDataSet() { // Create a new dataset to hold the records returned from the call to FillDataSet. // A temporary dataset is used because filling the existing dataset would // require the databindings to be rebound. PostingExpenses.TheExpenses objDataSetTemp; objDataSetTemp = new PostingExpenses.TheExpenses(); try { // Attempt to fill the temporary dataset. this.FillDataSet(objDataSetTemp); } catch (System.Exception eFillDataSet) { // Add your error handling code here. throw eFillDataSet; } try { grdChecks.DataSource = null; // Empty the old records from the dataset. objTheExpenses.Clear(); // Merge the records into the main dataset. objTheExpenses.Merge(objDataSetTemp); grdChecks.SetDataBinding(objTheExpenses, "GL Accounts.Expenses"); } catch (System.Exception eLoadMerge) { // Add your error handling code here. throw eLoadMerge; } } public void UpdateDataSet() { // Create a new dataset to hold the changes that have been made to the main dataset. PostingExpenses.TheExpenses objDataSetChanges = new PostingExpenses.TheExpenses(); // Stop any current edits. this.BindingContext[objTheExpenses,"GL Accounts"].EndCurrentEdit(); this.BindingContext[objTheExpenses,"Checks"].EndCurrentEdit(); // Get the changes that have been made to the main dataset. objDataSetChanges = ((PostingExpenses.TheExpenses)(objTheExpenses.GetChanges())); // Check to see if any changes have been made. if ((objDataSetChanges != null)) { try { // There are changes that need to be made, so attempt to update the datasource by // calling the update method and passing the dataset and any parameters. this.UpdateDataSource(objDataSetChanges); objTheExpenses.Merge(objDataSetChanges); objTheExpenses.AcceptChanges(); } catch (System.Exception eUpdate) { // Add your error handling code here. throw eUpdate; } // Add your code to check the returned dataset for any errors that may have been // pushed into the row object's error. } } private void btnCancelAll_Click(object sender, System.EventArgs e) { if(MessageBox.Show("Do you want to cancel all of the changed records?","Warning",MessageBoxButtons.YesNo,MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2)==DialogResult.Yes) { this.objTheExpenses.RejectChanges(); }
file:///D|/1/final/BBL0094.html (25 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
} private void objTheExpenses_PositionChanged() { this.lblNavLocation.Text = ((((this.BindingContext[objTheExpenses,"GL Accounts"].Position + 1)).ToString() + " of ") + this.BindingContext[objTheExpenses,"GL Accounts"].Count.ToString()); } private void btnNavNext_Click(object sender, System.EventArgs e) { this.BindingContext[objTheExpenses,"GL Accounts"].Position = (this.BindingContext[objTheExpenses,"GL Accounts"].Position + 1); this.objTheExpenses_PositionChanged(); } private void btnNavPrev_Click(object sender, System.EventArgs e) { this.BindingContext[objTheExpenses,"GL Accounts"].Position = (this.BindingContext[objTheExpenses,"GL Accounts"].Position - 1); this.objTheExpenses_PositionChanged(); } private void btnLast_Click(object sender, System.EventArgs e) { this.BindingContext[objTheExpenses,"GL Accounts"].Position = (this.objTheExpenses.Tables["GL Accounts"].Rows.Count - 1); this.objTheExpenses_PositionChanged(); } private void btnNavFirst_Click(object sender, System.EventArgs e) { this.BindingContext[objTheExpenses,"GL Accounts"].Position = 0; this.objTheExpenses_PositionChanged(); } private void btnLoad_Click(object sender, System.EventArgs e) { try { // Attempt to load the dataset. this.LoadDataSet(); } catch (System.Exception eLoad) { // Add your error handling code here. // Display error message, if any. System.Windows.Forms.MessageBox.Show(eLoad.Message); } this.objTheExpenses_PositionChanged(); } private void btnUpdate_Click(object sender, System.EventArgs e) { if(MessageBox.Show("Do you want to update the database records?","Warning",MessageBoxButtons.YesNo,MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2)==DialogResult.Yes) { try { // Attempt to update the datasource. this.UpdateDataSet(); } catch (System.Exception eUpdate) { // Add your error handling code here. // Display error message, if any. System.Windows.Forms.MessageBox.Show(eUpdate.Message); } this.objTheExpenses_PositionChanged(); } } private void btnAdd_Click(object sender, System.EventArgs e)
file:///D|/1/final/BBL0094.html (26 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
{ if(MessageBox.Show("Do you want to add a GL Account record?","Warning",MessageBoxButtons.YesNo,MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2)==DialogResult.Yes) { try { // Clear out the current edits this.BindingContext[objTheExpenses,"GL Accounts"].EndCurrentEdit(); this.BindingContext[objTheExpenses,"GL Accounts"].AddNew(); } catch (System.Exception eEndEdit) { System.Windows.Forms.MessageBox.Show(eEndEdit.Message); } this.objTheExpenses_PositionChanged(); } } private void btnDelete_Click(object sender, System.EventArgs e) { if(MessageBox.Show("Do you want to delete both the GL Account record and the Check record?","Warning",MessageBoxButtons.YesNo, MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2)==DialogResult.Yes) { if ((this.BindingContext[objTheExpenses,"GL Accounts"].Count > 0)) { this.BindingContext[objTheExpenses,"GL Accounts"].RemoveAt(this.BindingContext[objTheExpenses,"GL Accounts"].Position); this.objTheExpenses_PositionChanged(); } } } private void btnCancel_Click(object sender, System.EventArgs e) { if(MessageBox.Show("Do you want to cancel the last change to the records?","Warning",MessageBoxButtons.YesNo,MessageBoxIcon. Warning,MessageBoxDefaultButton.Button2)==DialogResult.Yes) { this.BindingContext[objTheExpenses,"GL Accounts"].CancelCurrentEdit(); this.objTheExpenses_PositionChanged(); } } } }
// program_id Form3.cs // written_by don voils // date_written 3/12/2006 // description This program along with Expenses.cs uses // a Data Form to create access to the // database: Expenses.mdb. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace PostingExpenses { /// <summary> /// Summary description for Form1. /// public class Form3 : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form3() { //
file:///D|/1/final/BBL0094.html (27 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if(disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { // // Form3 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 262); this.Name = "Form3"; this.Text = "Form4"; } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Expenses()); } } }
// program_id NewCustomers.cs // written_by don voils // date_written 10/06/2006 // description This file contains the definition of the // class NewCustomer which is use for random // file access both input and output. // using System; namespace NewCustomers { public class NewCustomer { private const int CHAR_ARRAY_LENGTH = 15; private const int SIZE_OF_CHAR = 2; private const int SIZE_OF_INT32 = 4; private const int SIZE_OF_DECIMAL = 8; private const int Size = 2 * (SIZE_OF_CHAR + CHAR_ARRAY_LENGTH) + SIZE_OF_INT32 + SIZE_OF_DECIMAL; private char[] first = new char[CHAR_ARRAY_LENGTH]; private char[] last = new char[CHAR_ARRAY_LENGTH]; private int ID;
file:///D|/1/final/BBL0094.html (28 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
private decimal Due; static public int theSize { get { return Size; } } public int customerID { get { return ID; } set { ID = value; } } public string firstName { get { return new string(first); } set { int stringSize = value.Length; string firstNameString = value; if(CHAR_ARRAY_LENGTH >= stringSize) { firstNameString = value + new string(' ',CHAR_ARRAY_LENGTH - stringSize); } else { firstNameString = value.Substring(0,CHAR_ARRAY_LENGTH); } first = firstNameString.ToCharArray(); } } public string lastName { get { return new string(last); } set { int stringSize = value.Length; string lastNameString = value; if(CHAR_ARRAY_LENGTH >= stringSize) { lastNameString = value + new string(' ',CHAR_ARRAY_LENGTH - stringSize); } else { lastNameString = value.Substring(0,CHAR_ARRAY_LENGTH); } last = lastNameString.ToCharArray(); } } public decimal balanceDue { get {
file:///D|/1/final/BBL0094.html (29 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
return Due; } set { Due = value; } } public NewCustomer() { customerID = 0; firstName = ""; lastName = ""; balanceDue = 0.00m; } public NewCustomer(int ID,string FirstName,string LastName,decimal BalanceDue) { customerID = ID; firstName = FirstName; lastName = LastName; balanceDue = BalanceDue; } } }
// program_id ReadingRandomAccess.cs // written_by don voils // date_written 12/06/2006 // description This file demonstrates the reading of // random access files. It uses objects from // the class NewCustomer from the file: // NewCustomer.cs // using System; using System.IO; using NewCustomers; namespace ReadingRandomAccessFiles { class ReadingRandomAccess { static FileStream fileInput; static BinaryReader binaryInput; static string randomAccessFile = "randomAccess.dat"; static void Main(string[] args) { char moreData = 'N'; Console.Clear(); NewCustomer theCustomer = new NewCustomer(); if (fileInput != null) fileInput.Close(); // If the file has never been created, then the following will throw an exception // try { fileInput = new FileStream(randomAccessFile, FileMode.Open, FileAccess.Read); } // If the file did not exist before this run of the program then the follow catch // executes informs the user that there is no data in the customer file. // catch (FileNotFoundException) { Console.WriteLine("There is no data in the customer file. To end press the Enter key."); Console.ReadLine(); return;
file:///D|/1/final/BBL0094.html (30 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
} binaryInput = new BinaryReader(fileInput); do { int theID; Console.Write("\n\nWhat is the customer ID you are looking for? "); theID = int.Parse(Console.ReadLine()); try { fileInput.Seek(NewCustomer.theSize * (theID - 1), 0); theCustomer.customerID = binaryInput.ReadInt32(); } catch (IOException) { Console.WriteLine("\n\nThat customer ID was not on record!\n"); moreData = 'Y'; } if (moreData != 'Y') { if (theCustomer.customerID == theID) { theCustomer.firstName = binaryInput.ReadString(); theCustomer.lastName = binaryInput.ReadString(); theCustomer.balanceDue = binaryInput.ReadDecimal(); Console.WriteLine("\nCustomer ID: " + theCustomer.customerID); Console.WriteLine("Customer Name: " + theCustomer.firstName + " " + theCustomer.lastName); Console.WriteLine(String.Format("Balance due: {0:c}\n\n", theCustomer.balanceDue)); } else { Console.WriteLine("\n\nThat customer ID was not on record!\n"); } } Console.Write("\n\nProcess another customer? (Y/N). "); moreData = Char.Parse(Console.ReadLine()); Console.Clear(); } while ((moreData == 'Y') || (moreData == 'y')); Console.WriteLine("\n"); } } }
// program_id theATM.cs // written_by don voils // date_written 11/14/2006 // description This program simulates an ATM. Along with the program // Account.cs, it illustrates how a programmer may create // a program specific exception class. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace theATM { public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox txtAccountID; private System.Windows.Forms.TextBox txtWithdrawal; private System.Windows.Forms.Button btnWithdraw; private Account yourAccount = new Account(); private System.Windows.Forms.Button btnEnterID; private System.Windows.Forms.Label lblWithdraw;
file:///D|/1/final/BBL0094.html (31 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
private System.Windows.Forms.Label lblID; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // yourAccount.ID = "12345"; yourAccount.Balance=454.43m; } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if(disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.lblID = new System.Windows.Forms.Label(); this.txtAccountID = new System.Windows.Forms.TextBox(); this.btnEnterID = new System.Windows.Forms.Button(); this.lblWithdraw = new System.Windows.Forms.Label(); this.txtWithdrawal = new System.Windows.Forms.TextBox(); this.btnWithdraw = new System.Windows.Forms.Button(); this.SuspendLayout(); // // lblID // this.lblID.Location = new System.Drawing.Point(50, 40); this.lblID.Name = "lblID"; this.lblID.Size = new System.Drawing.Size(120, 23); this.lblID.TabIndex = 0; this.lblID.Text = "Account ID"; // // txtAccountID // this.txtAccountID.Location = new System.Drawing.Point(170, 40); this.txtAccountID.Name = "txtAccountID"; this.txtAccountID.TabIndex = 1; this.txtAccountID.Text = ""; // // btnEnterID // this.btnEnterID.Location = new System.Drawing.Point(160, 80); this.btnEnterID.Name = "btnEnterID"; this.btnEnterID.Size = new System.Drawing.Size(128, 23); this.btnEnterID.TabIndex = 2; this.btnEnterID.Text = "Press to Enter ID"; this.btnEnterID.Click += new System.EventHandler(this.btnEnterID_Click); // // lblWithdraw
file:///D|/1/final/BBL0094.html (32 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// this.lblWithdraw.Location = new System.Drawing.Point(20, 150); this.lblWithdraw.Name = "lblWithdraw"; this.lblWithdraw.Size = new System.Drawing.Size(150, 23); this.lblWithdraw.TabIndex = 3; this.lblWithdraw.Text = "Withdrawal Amount"; this.lblWithdraw.Visible = false; // // txtWithdrawal // this.txtWithdrawal.Location = new System.Drawing.Point(170, 150); this.txtWithdrawal.Name = "txtWithdrawal"; this.txtWithdrawal.TabIndex = 4; this.txtWithdrawal.Text = ""; this.txtWithdrawal.Visible = false; // // btnWithdraw // this.btnWithdraw.Location = new System.Drawing.Point(160, 192); this.btnWithdraw.Name = "btnWithdraw"; this.btnWithdraw.Size = new System.Drawing.Size(136, 23); this.btnWithdraw.TabIndex = 5; this.btnWithdraw.Text = "Press to Withdraw"; this.btnWithdraw.Visible = false; this.btnWithdraw.Click += new System.EventHandler(this.btnWithdraw_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(7, 15); this.ClientSize = new System.Drawing.Size(496, 262); this.Controls.Add(this.btnWithdraw); this.Controls.Add(this.txtWithdrawal); this.Controls.Add(this.lblWithdraw); this.Controls.Add(this.btnEnterID); this.Controls.Add(this.txtAccountID); this.Controls.Add(this.lblID); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Name = "Form1"; this.Text = "The ATM"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void btnEnterID_Click(object sender, System.EventArgs e) { if((yourAccount.ID).Equals(txtAccountID.Text)) { txtWithdrawal.Visible=true; btnWithdraw.Visible=true; lblWithdraw.Visible=true; txtAccountID.Clear(); txtAccountID.Visible=false; lblID.Visible=false; btnEnterID.Visible=false; txtWithdrawal.Focus(); } else { MessageBox.Show("You are not a customer","Error"); txtAccountID.Focus(); txtAccountID.Clear(); } } private void btnWithdraw_Click(object sender, System.EventArgs e)
file:///D|/1/final/BBL0094.html (33 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
{ decimal withdrawal = decimal.Parse(txtWithdrawal.Text); try { yourAccount.withdrawal(decimal.Parse(txtWithdrawal.Text)); MessageBox.Show("Here is your money.","Withdrew amount requested"); } catch(BalanceException f) { MessageBox.Show(String.Format("Your withdrawal of {0:c} exceeds your balance. ",f.Balance),"Error"); } finally { txtWithdrawal.Visible=false; btnWithdraw.Visible=false; lblWithdraw.Visible=false; txtWithdrawal.Clear(); lblID.Visible=true; btnEnterID.Visible=true; txtAccountID.Visible=true; txtAccountID.Focus(); } } } }
file:///D|/1/final/BBL0094.html (34 von 34) [01.12.2007 04:49:21]
Lecture 11: Generics in C#
Lecture 11: Generics in C# Introduction to C# Generics The language C++ has a construct called: templates (also known as generics). C++ has two types of templates: template functions and template classes.
Template Functions in C++ By template functions is meant that a function may be defined in such a way that the functional definition does not specify the data types of some of the variables involved in the function. For example a C++ function MAX( ) could have the following definition: template T MAX(T value1, T value2) { return ((value1
Notice in this definition that there is the unspecified data type T. This function may then have any of the following calls: Int theIntNumber = Max(10, 25);
or double theDoubleNumber = Max(43.33,23.43);
or Date theDate = Max(firstDate,secondDate);
where Date is a class on which the relational operators are overloaded. See MAXIMUM.CPP In the example above, the template function has two unknown arguments all of the same type. However it is also possible to have a template function which has some of the arguments (or variables involved in the definition) which are specified. For example: template T MAX(char *word,T value1, T value2) { cout << word << endl; return ((value1
This function could then have the following call:
file:///D|/1/final/BBL0095.html (1 von 3) [01.12.2007 04:49:22]
Lecture 11: Generics in C#
char *theStatement = "You have received the largest amount"; theDouble = Max(theStatement, 34.33, 65.44);
In this call theDouble would contain 65.44 and on the screen would be the statement: You have received the largest amount. See MAXIMUM2.CPP
Template Class in C++ In C++ classes may be defined so that some of the data types involved in the class' definition are unknown until at call time for example: class theClass { private: T theAttribute; public: void settheAttribute(T theValue) { theAttribute = theValue; } T gettheAttribute() { return theAttribute; } };
An object of theClass could then be defined as in the following statement: theClass theObject;
Notice that in the definition of theObject, the data type of the attribute is specified. In the template class above, there was only one unknown data type. As with the template functions discussed above, template classes may have both several known and several unknown data types for the attributes and methods. Additional properties of template classes are they may be derived from either template and non-template classes.
Generics in C# When .NET 1.0 was created, C# generics were not included. There was significant criticism about the lack of these tools. Therefore when .NET 2.0 was created, generics were added to the tools of C#. As will be demonstrated in this lecture, C# now has generic methods, generic classes, generic structures and generic interfaces. But in addition, it also has generic delegates but they will not be discussed in this lecture. In C++ each template function call and each template class object definition is "rewritten" at compile time to implement the unknown data types. This feature is also different in C# in that this conversion is performed at runtime rather than at compile time. The question might arise as to why it was desirable to introduce generics in C#. One reason is that creating data structures like Stacks, Queues, ArrayLists, Hashtables and SortLIsts requires boxing and unboxing of data because these constructs are defined in terms of the object data type. Therefore when other data types are used in
file:///D|/1/final/BBL0095.html (2 von 3) [01.12.2007 04:49:22]
Lecture 11: Generics in C#
these data structure, it is necessary to use type conversion, i.e. boxing and unboxing. One of the problems with this process is that if these actions are preformed a large number of times, then they can use a large amount of clock time doing these processes. Further if the boxing and unboxing is performed incorrectly, then errors can occur. However the errors are usually runtime errors rather than compile time errors making it therefore more difficult to find and to correct. Generics in C# reduce the need for boxing and unboxing. As a result, the clock time requirements are reduced. In addition, if there are any errors in using the data, they may be more easily found at compile time rather than at run time making the program much more type safe.
file:///D|/1/final/BBL0095.html (3 von 3) [01.12.2007 04:49:22]
Builtin Generic Interfaces and Generic Classes
Builtin Generic Interfaces and Generic Classes As was discussed in the previous section of this lecture, C# has generic interfaces. The namespace: System. Collections.Generic contains several useful interfaces. Because of the frequency of the expected use of generics in C# programs, the following using appears by default above program created by the IDE: using System.Collections.Generic;
The following table lists some of the generic interfaces that are included in this namespace:
ICollection IComparable IComparer IDictionary IEnumerable IEnumerator IList
Note: T is frequently used for the unknown data type, K is used for the unknown key type and V is used for the unknown value type. If more than one unknown is required, then the letters: R and S are used. Several of the generic interfaces listed above have non-generic interface counter parts that were discussed earlier in the lectures. In addition to the generic interfaces listed above, C# has several generic classes built in as well. These classes are also included in the namespace: System.Collections.Generic. The following table lists some of these builtin generic classes as well as their non-generic counterparts:
Open table as spreadsheet Generic Class
NonGeneric Conterpart in System. Collection
Collection
CollectionBase
Comparer
Comparer
Dictionary
HashTable
List
ArrayList
LinkedList Queue
Queue
SortedDictionary
SortedList
Stack
Stack
file:///D|/1/final/BBL0096.html (1 von 2) [01.12.2007 04:49:23]
Builtin Generic Interfaces and Generic Classes
For example the generic class List above could be used to manage a list of any data type. Some of the methods for this class are:
Open table as spreadsheet Method
Purpose
Add()
Adds elements to the list
BinarySearch ()
Locates a particular element in the list returning a position
Contains()
Determine if an element is in the list returning a bool
Remove()
Removes an element and returns a bool to indicate whether it was removed.
this[int index]
An indexer with {get; set;}
Suppose that you wanted to create a list of objects for the class: People. Using List, this could be done by the following definition: List theCustomers = new List();
This List could therefore be managed as in the console program: CustomersList.cs. Notice how this program works similar to using an ArrayList.
file:///D|/1/final/BBL0096.html (2 von 2) [01.12.2007 04:49:23]
Generic Methods
Generic Methods Whenever programs are going to use generic methods, the namespace: System.Collections.Generic needs to be added to the project. Therefore above the C# code should include the following: using System.Collections.Generic;
Since Generic methods may be used in most programs now, this using statement is automatically added to the top of a C# program by the IDE. As indicated above, C# may use generic methods. As will be seen from the examples below, they are similar to the template functions used in C++. For example, look at the following generic method: MAX(): static T MAX(T theFirst, T theSecond) where T:IComparable { T theMax = theSecond; ; if (theFirst.CompareTo(theMax)>0) theMax = theFirst; else theMax = theSecond; return theMax; }
Create a C# console project and call it; theMaximum. Open the following C# program file: theMaximum.cs and copy it into the project just created. Compile and run this C# console program. The program will ask for two integers and display the value of the largest. Next it will ask for two doubles and display the value of the largest as well. These maximum values will both be found by using the MAX() method defined above. As you look at the code above, notice how this program is similar to and how it is different from the C++ programs considered in a previous section of this lecture. The first thing to note is that the template header does not appear above the function's definition as it did in C++. Second notice appears just after the method's name rather than in the header as in the C++ template functions. This tells the compiler that this method is a generic method and that T will stand for the unknown data type. Next look in the body of MAX() and notice the method: CompareTo() that is used instead of a relational operator. The reason for this is that the C# compiler will not allow a relational operator to be used here. The reason for this is that compiler can not be sure that if this method is used, whether the data type T will have the relational operators defined on the data type. Instead, the data type: T used for the arguments must be derived from the generic interface IComparable. Notice to the right of the method's header the code: where T:IComparable
This code tells the compiler that the data type: T is derived from IComparable which is a generic interface. The interface IComparable is similar to IComparable except that it is a generic interface while IComparable is not. The arguments used in this method in the previous example use T and it was an int or a double data type. Both of these data types are structures that are derived from the interface: IComparable and therefore these data types may be used with this method. So the question now should be, is it possible to have a non-generic method in the same program with a generic method each of which have the same name? For example suppose the following non-generic method: MAX() was in the program along with the generic method: MAX() above:
file:///D|/1/final/BBL0097.html (1 von 2) [01.12.2007 04:49:23]
Generic Methods
static int MAX(int theFirst, int theSecond) { Console.WriteLine("\n\nThe non-generic MAX()was used\n\n"); int theMax = theSecond; if (theFirst > theMax) theMax = theFirst; else theMax = theSecond; return theMax; }
The answer is that it is possible and the two methods overload each other. For example see: theMaximum2.CS. Create a C# console project named: MAXIMUM2.CS and copy this file into the project. First, notice that the program compiles. Next notice that when the integers are entered this time, the non-generic MAX() is called and when the doubles are entered, the generic MAX() is called. The next question that should arise is whether it is possible for two generic methods to be in the same program and have the same name but different signatures. For example suppose the following method was added to the first example above: static T MAX(string theMessage, T theFirst, T theSecond) where T : IComparable { Console.WriteLine("\nThe generic MAX() with " + "three arguments was called \n" + "and the message was: {0}",theMessage); T theMax = theSecond; ; if (theFirst.CompareTo(theMax) > 0) theMax = theFirst; else theMax = theSecond; return theMax; }
The answer is that it is possible for a program to have both of these methods overload each other. For example see: theMaximum3.CS. Create a console project: Maximum3.CS. Copy the code in this file into the project. Compile and run it. Notice that it works similarly to the example in the C++ programs.
file:///D|/1/final/BBL0097.html (2 von 2) [01.12.2007 04:49:23]
Generic Classes
Generic Classes Defining Generic Classes As with C++, C# may have generic classes (the following discussion is also true for structures). The general form of the generic class definition is like the following: class firstGenericClass { ..... }
The example above only has one unknown type: T. As with C++, it is also possible to have generic classes in which there may be more than one unknown data type as in the following general form: class secondGenericClass { ..... }
Again having three unknowns is not a restriction. That is there may be more or less unknown data types than these three. Using the first example: firstGenericClass could be defined as the following: class firstGenericClass { private T theField; public T TheField { get { return theField; } set { theField = value; } } }
Using this class' definition, a program with code like the following could be written: firstGenericClass theIntObject = new firstGenericClass(); Console.Write("What is the value of the int field? "); theIntObject.TheField = Int32.Parse(Console.ReadLine()); Console.WriteLine("\n\nYou said the value of the field for the " +
file:///D|/1/final/BBL0098.html (1 von 5) [01.12.2007 04:49:24]
Generic Classes
"int object was {0}. \n\n", theIntObject.TheField); firstGenericClass<double> theDoubleObject = new firstGenericClass<double>(); Console.Write("What is the value of the double field? "); theDoubleObject.TheField = Double.Parse(Console.ReadLine()); Console.WriteLine("\n\nYou said the value of the field for the" + " double object was {0}. \n\n", theDoubleObject.TheField);
See the following class' definition: firstGenericClass.cs and the following program: testingGenericClass.cs. Create the project: testingGenericClass. Copy these two files into the project where the second file replaces: Program.cs and the first file is a class file. Next compile and run the program. Notice how the program was able to handle the two different data types: int and double to implement the class. The example above only had one unknown data type. The following class processes when there are two unknown data types: class secondGenericClass { private T theFirst; private R theSecond; public T First { get { return theFirst; } set { theFirst = value; } } public R Second { get { return theSecond; } set { theSecond = value; } } }
To view how this class works create the project: testingGenericClasses2.cs. Copy the file: testingGenericClasses2 in Program.cs and create a class file for the file: secondGenericClass.cs.
Problems with Generic Classes Now things have worked so far in the examples above. However that is only because the examples are so simple. Suppose that a program included the class: thirdGenericClass which is defined as the following:
file:///D|/1/final/BBL0098.html (2 von 5) [01.12.2007 04:49:24]
Generic Classes
class thirdGenericClass { private T theField; thirdGenericClass() { theField = new T(); } }
If you place this class within a project, it will not compile. The reason is that the definition assumes that the data type T has a default constructor. Since this is a not requirement of all classes, the assumption is not acceptable. Another problem can be writing a generic class definition which assumes that the unknown data type has the operators: == and != defined. This feature is also not a requirement, so such a class will also not compile. Another problem can occur if it is necessary to initialize a field which is an instance of the unknown data type. That is suppose the fourthGenericClass needs a constructor definition to include the following: class fourthGenericClass { T theField; fourthGenericClass() { theField = ???; } ....... }
The question is what should replace the ???. One possibility is 0 and another is null. But these are not the same and therefore can not be used for all unknown data types. One solution is to use the function: default() as in the following: class fourthGenericClass { T theField; fourthGenericClass() { theField = default(T); } ....... }
In this case, if the data type T was a value type, then a 0 as one of the possibilities would be supplied by the compiler. However, if the data type T was a reference type, then null would be supplied instead. Another type of error that can occur is if the generic class attempts to use any of the following operators: +, -, *, / or %. These operators can not be used either because they are not required of all classes. In addition, the .Net methods: Add(), Multiply(), Subtract() and Divide() may not be used because it is not a requirement that all classes implement these methods.
Generic Constraints
file:///D|/1/final/BBL0098.html (3 von 5) [01.12.2007 04:49:24]
Generic Classes
As discussed above, a generic class must be defined in such a way that the unknown data types do not provide compiler errors because some data type T may not possess a particular property needed in the class' definition‥ Recall that above, one of the examples required that the default constructor be defined on the unknown data type T. As a result, the code would not compile. The reason for this is that the generic classes discussed so far have what is called: unbounded constraints. To solve this problem requires the use of constraints and the use of the key word: where. To implement this feature, the header of the generic class needs to be defined like the following: class theClass where T: theconstraint { ...... }
or if there is more than one constraint, then they may appear sequential separated by commas as in the following example: class theClass where T : theTconstraint, where R : theRconstraint { ..... }
The following table contains the possible constraints:
Open table as spreadsheet Constraint
Meaning
where T: struct
T must be a value type
where T: class
T must be a reference type
where T: new()
T must have a default constructor
where T: derivedFromParticularClass
T must be derived from the class: derivedFromParticularClass
where T: derivedFromParticularInterface
T must be derived from the interface: derivedFromParticularInterface
The following are some examples of the class header of generic classes that have constraints: class Class1 where T: new() { … }
so that the data type T implements a default constructor, or class Class2 where T:struct { .... }
file:///D|/1/final/BBL0098.html (4 von 5) [01.12.2007 04:49:24]
Generic Classes
so that the data type T is a value type, or class Class3 where T: class { … }
so that the data type T is a reference type, or class Class4 where T: struct, where R: theInterface { … }
so the data type T is a value type and the data type R is derived from theInterface.
file:///D|/1/final/BBL0098.html (5 von 5) [01.12.2007 04:49:24]
Generic Class Inheritance from Classes and Interfaces
Generic Class Inheritance from Classes and Interfaces Generic Classes Inheritance from Classes Suppose that you had the following generic class: class theGenericClass1 { .... }
It is possible to not only derive other generic classes from theGenericClass but it is also possible to derive non generic classes from this class. Having said this, one must keep in mind that there may be several restrictions. Suppose that you wanted to derive a non-generic class from theGenericClass. In order to do this the data type going to be used for T in the non-generic class must be explicitly specified in the class' header as in the following: class nonGenericClass:theGenericClass1<decimal> { ..... }
It would also be possible to derive a generic class from theGenericClass1. The only restriction would be that the derived class must also implement the data type T. For example the following would be permissible: class theDerivedGenericClass : theGenericClass1 { … }
Next suppose that a generic class had constraints as in the following case: class theGenericClass2 where T: struct { … }
In this case the generic (or the nongeneric) class derived from theGenericClass2 must also have the same constraint. And of course, if there was more than one constraint then each of them must be implemented by the derived class. If the generic base class had virtual or abstract methods, then the derived class must override these methods. The examples above only dealt with one unknown data type in the generic base class. What should be kept in mind is that the statements above for one unknown data type can also be extend to the case where the base class has more than one unknown data type.
Interfaces, Inheritance and Generics file:///D|/1/final/BBL0099.html (1 von 2) [01.12.2007 04:49:25]
Generic Class Inheritance from Classes and Interfaces
As noted in an earlier section of this lecture, there are built into C# several generic interfaces. Therefore it is obvious that generic interfaces may be written as well. The main thing to keep in mind when deriving from a generic interface, is that the derived class must implement the unknown data type as a specific data type. That is, if T is the unknown data type, then the derived class must implement T with a specific data type like: decimal.
Comment about Generics and Inheritance As can be seen from the discussion in this section of the lecture, C# implements inheritance with respect to generic classes, generic interfaces and non-generic classes. While this is possible, there seems to be at the moment little likely hood that other than the builtin generics, little code will be written which implements generic inheritance.
file:///D|/1/final/BBL0099.html (2 von 2) [01.12.2007 04:49:25]
Lecture 11 Examples
Lecture 11 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
CustomerList.cs
This program along with the class file People.cs uses the generic List to manage a customers list.
firstGenericClass.cs
This file along with testingGenericClasses.cs simulates generic classes.
MAXMUM2.CPP
This example shows how to use template functions with a non-class argument.
MAXIMUM.CPP
This example shows how to use template functions which have arguments all of which are of the same data type.
People.cs
This file contains the definition of the class: People.
secondGenericClass.cs
This file along with testingGenericClasses2.cs demonstrates using generic class with two unknown data types.
testingGenericClasses2. cs
This file along with secondGenericClass.cs demonstrates using generic class with two unknown data types.
testingGenericClasses.cs
This file along with firstGenericClas.cs demonstrates how generic classes could be defined.
theMaximum2.cs
This program demonstrates that generic methods in C# may overload non-generic methods.
theMaximum3.cs
This program demonstrates that two generic methods in C# may overload each other.
theMaximum.cs
This program demonstrates generic methods in C# similar to the template methods in C++.
// program_id CustomerList.cs // written_by Don Voils // date_written 11/10/2006 // description This program along with the class file People.cs // uses the generic List to manage a customers list. // using System; using System.Collections.Generic; using System.Text; using thePeople; namespace CustomersList { class Program { static List theCustomers = new List(); static void Main(string[] args) { bool moreOptions = true; int theOption; do { Console.Clear(); Console.WriteLine(" Select an option\n\n");
file:///D|/1/final/BBL0100.html (1 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
Console.WriteLine(" 1. Add a customer\n"); Console.WriteLine(" 2. Find a customer\n"); Console.WriteLine(" 3. Delete a customer\n"); Console.WriteLine(" 4. Exit\n"); Console.Write("\n Which Option? "); theOption = Int16.Parse(Console.ReadLine()); Console.Clear(); switch (theOption) { case 1: AddCustomer(); break; case 2: FindCustomer(); break; case 3: DeleteCustomer(); break; case 4: moreOptions = false; break; default: break; } } while (moreOptions); } static void AddCustomer() { Console.Clear(); People thePerson = new People(); Console.Write(" What is the customer's Credit Card Company? "); thePerson.TheCompany = Console.ReadLine(); Console.Write("\n What is the customer's ID? "); thePerson.TheID = Console.ReadLine(); Console.Write("\n What is the customer's name? "); thePerson.TheName = Console.ReadLine(); Console.Write("\n What is the customer's address? "); thePerson.TheAddress = Console.ReadLine(); Console.Write("\n What is the customer's city? "); thePerson.TheCity = Console.ReadLine(); Console.Write("\n What is the customer's state? "); thePerson.TheState = Console.ReadLine(); Console.Write("\n What is the cusotmer's zip code? "); thePerson.TheZipCode = Console.ReadLine(); Console.Write("\n\n Is the information above correct? (Y/N) "); char theResponse = Char.Parse(Console.ReadLine()); if ((theResponse == 'Y') || (theResponse == 'y')) { Console.WriteLine("\n\n The information to be saved is:"); Console.Write("\n\n" + thePerson.ToString()); Console.Write("\n\n Press any key to continue. "); Console.ReadKey(); theCustomers.Add(thePerson); } else { Console.WriteLine("\n\n The information will not be saved.\n");
file:///D|/1/final/BBL0100.html (2 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
Console.Write("\n\n Press any key to continue. "); Console.ReadKey(); } } static void FindCustomer() { Console.Clear(); string findID; int foundIt = -1; Console.Write(" What is the customer's ID you wish to find? "); findID = Console.ReadLine(); for(int index = 0;index < theCustomers.Count;++index) { if (theCustomers[index].TheID == findID) { Console.Write("\n\n" +theCustomers[index].ToString()); foundIt = index; } } if (foundIt == -1) Console.WriteLine("\n That customer is not on record.\n\n"); Console.Write("\n\n Press any key to continue. "); Console.ReadKey(); } static void DeleteCustomer() { Console.Clear(); string findID; int foundIt = -1; Console.Write(" What is the customer's ID you wish to find? "); findID = Console.ReadLine(); for (int index = 0; index < theCustomers.Count; ++index) { if (theCustomers[index].TheID == findID) { Console.Write("\n\n"+theCustomers[index].ToString()); foundIt = index; Console.Write("\n\n Delete this customer? (Y/N) "); char theAnswer = Char.Parse(Console.ReadLine()); if((theAnswer=='Y')||(theAnswer=='y')) { bool wasDeleted = theCustomers.Remove(theCustomers[index]); if(wasDeleted) Console.WriteLine("\n\n This customer will be deleted.\n\n"); else Console.WriteLine("\n\n This customer was not deleted.\n\n"); } else Console.WriteLine("\n\n That customer will be retained.\n\n"); } } if (foundIt == -1) Console.WriteLine("\n That customer is not on record.\n\n");
file:///D|/1/final/BBL0100.html (3 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
Console.Write("\n\n Press any key to continue."); Console.ReadKey(); } } }
// program_id firstGenericClass.cs // written_by don voils // date_written 11/10/2006 // description This file along with testingGenericClasses.cs // simulates generic classes. // using System; using System.Collections.Generic; using System.Text; namespace thefirstGenericClass { class firstGenericClass { private T theField; public T TheField { get { return theField; } set { theField = value; } } } }
// program_id MAXMUM2.CPP // author don voils // date written 10/23/2006 // // program description This example shows how to use // template functions with a non-class // argument. // #include using namespace std; template T MAX(char *word,T value1, T value2) { cout << word << endl; return ((value1
file:///D|/1/final/BBL0100.html (4 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
void main() { int int1=3,int2=4; float float1=4.0,float2=5.0; double double1=6.0,double2=7.0; cout << "The maximum of the integers " << int1 << " and " << int2 << " is " << MAX("FIRST ONE", int1, int2) << endl << endl; cout << "The maximum of the floats " << float1 << " and " << float2 << " is " << MAX("SECOND ONE",float1, float2) << endl << endl; cout << "The maximum of the doubles " << double1 << " and " << double2 << " is " << MAX("THIRD ONE ",double1, double2) << endl << endl; cout << "The maximum of the integer " << int1 << " and the double " << double2 << " is " << MAX("FOURTH ONE",double(int1), double2) << endl << endl; }
// program_id MAXIMUM.CPP // author don voils // data written 10/23/2006 // // program description This example shows how to use // template functions which have arguments // all of which are of the same data type. // #include #include using namespace std; template T MAX(T value1, T value2) { return ((value1
file:///D|/1/final/BBL0100.html (5 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
cout << "The maximum of the integer " << int1 << " and the double " << double2 << " is " << MAX(double(int1), double2) << endl << endl << endl;
}
// program_id People.cs // written_by don voils // date_written 1/3/2006 // description This file contains the definition of the class: People namespace thePeople { public class People { private string CreditCompany; private string PeopleID; private string PeopleName; private string PeopleAddress; private string PeopleCity; private string PeopleState; private string PeopleZipCode; public string TheCompany { get { return CreditCompany; } set { CreditCompany = value; } } public string TheID { get { return PeopleID; } set { PeopleID = value; } } public string TheName { get { return PeopleName; } set { PeopleName = value;
file:///D|/1/final/BBL0100.html (6 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
} } public string TheAddress { get { return PeopleAddress; } set { PeopleAddress = value; } } public string TheCity { get { return PeopleCity; } set { PeopleCity = value; } } public string TheState { get { return PeopleState; } set { PeopleState = value; } } public string TheZipCode { get { return PeopleZipCode; } set { PeopleZipCode = value; } } public override string ToString() { string theValue = " Credit Card:" + TheCompany + "\n" + " ID: " + TheID + "\n" + " Name: " + TheName + "\n" + " Address: " + TheAddress + "\n" + " City: " + TheCity + "\n" + " State: " + TheState + "\n" + file:///D|/1/final/BBL0100.html (7 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
" Zip:
" + TheZipCode + "\n";
return theValue; } } }
// program_id secondGenericClass.cs // written_by don voils // date_written 11/10/2006 // description This file along with testingGenericClasses2.cs // demonstrates using generic class with two // unknown data types. // using System; using System.Collections.Generic; using System.Text; namespace theSecondGenericClass { class secondGenericClass { private T theFirst; private R theSecond; public T First { get { return theFirst; } set { theFirst = value; } } public R Second { get { return theSecond; } set { theSecond = value; } } } }
// program_id testingGenericClasses2.cs // written_by don voils // date_written 11/10/2006 // description This file along with secondGenericClass.cs // demonstrates using generic class with two
file:///D|/1/final/BBL0100.html (8 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
// //
unknown data types.
using System; using System.Collections.Generic; using System.Text; using theSecondGenericClass; namespace testingGenericClasses2 { class Program { static void Main(string[] args) { secondGenericClass theFirst = new secondGenericClass(); Console.Write("What is the char value? "); theFirst.First = Char.Parse(Console.ReadLine()); Console.Write("\n\nWhat is the int value? "); theFirst.Second = Int32.Parse(Console.ReadLine()); Console.WriteLine("\n\nThe first value is: {0} and the second value is: {1}\n", theFirst.First, theFirst.Second); secondGenericClass<decimal, string> theSecond = new secondGenericClass<decimal,string>(); Console.Write("What is the decimal value? "); theSecond.First = Decimal.Parse(Console.ReadLine()); Console.Write("\n\nWhat is the string value? "); theSecond.Second = Console.ReadLine(); Console.WriteLine("\n\nThe first value is: {0} and the second value is: {1}\n", theSecond.First, theSecond.Second); } } }
// program_id testingGenericClasses.cs // written_by don voils // date_written 11/10/2006 // description This file along with firstGenericClas.cs // demonstrates how generic classes could be // defined. // using System; using System.Collections.Generic; using System.Text; using thefirstGenericClass; namespace testingGenericClasses { class Program { static void Main(string[] args) { firstGenericClass theIntObject = new firstGenericClass();
file:///D|/1/final/BBL0100.html (9 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
Console.Write("What is the value of the int field? "); theIntObject.TheField = Int32.Parse(Console.ReadLine()); Console.WriteLine("\n\nYou said the value of the field for the " + "int object was {0}. \n\n", theIntObject.TheField); firstGenericClass<double> theDoubleObject = new firstGenericClass<double>(); Console.Write("What is the value of the int field? "); theDoubleObject.TheField = Double.Parse(Console.ReadLine()); Console.WriteLine("\n\nYou said the value of the field for the" + " double object was {0}. \n\n", theDoubleObject.TheField); } } }
//propgram_id theMaximum2.cs //written_by don voils //date_written 11/08/2006 //description This program demonstrates that generic methods // in C# may overload non-generic methods. // using System; using System.Collections.Generic; using System.Text; namespace theMaximum { class Program { static void Main(string[] args) { Console.Write("What is the first integer? "); int theFirstInt = Int32.Parse(Console.ReadLine()); Console.Write("What is the Second integer? "); int theSecondInt = Int32.Parse(Console.ReadLine()); int theMaxInt = MAX(theFirstInt,theSecondInt); Console.WriteLine("\n\nThe maximum of {0} and {1} is {2}\n\n", theFirstInt,theSecondInt,theMaxInt); Console.Write("What is the first double? "); double theFirstDouble = Double.Parse(Console.ReadLine()); Console.Write("What is the Second double? "); double theSecondDouble = Double.Parse(Console.ReadLine()); double theMaxDouble = MAX(theFirstDouble, theSecondDouble); Console.WriteLine("\n\nThe maximum of {0} and {1} is {2}\n\n", theFirstDouble, theSecondDouble, theMaxDouble); Console.ReadKey(); } static int MAX(int theFirst, int theSecond) { Console.WriteLine("\n\nThe non-generic MAX()was used\n\n"); int theMax = theSecond; if (theFirst > theMax)
file:///D|/1/final/BBL0100.html (10 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
theMax = theFirst; else theMax = theSecond; return theMax; } static T MAX(T theFirst, T theSecond) where T : IComparable { T theMax = theSecond; ; if (theFirst.CompareTo(theMax) > 0) theMax = theFirst; else theMax = theSecond; return theMax; } } }
//propgram_id theMaximum3.cs //written_by don voils //date_written 11/08/2006 //description This program demonstrates that two generic methods // in C# may overload each other. // using System; using System.Collections.Generic; using System.Text; namespace theMaximum { class Program { static void Main(string[] args) { string theMessage ="Two integers were used.\n"; Console.Write("What is the first integer? "); int theFirstInt = Int32.Parse(Console.ReadLine()); Console.Write("What is the Second integer? "); int theSecondInt = Int32.Parse(Console.ReadLine()); int theMaxInt = MAX(theMessage,theFirstInt,theSecondInt); Console.WriteLine("\nThe maximum of {0} and {1} is {2}\n", theFirstInt,theSecondInt,theMaxInt); Console.Write("What is the first double? "); double theFirstDouble = Double.Parse(Console.ReadLine()); Console.Write("What is the Second double? "); double theSecondDouble = Double.Parse(Console.ReadLine()); double theMaxDouble = MAX(theFirstDouble, theSecondDouble); Console.WriteLine("\nThe maximum of {0} and {1} is {2}\n", theFirstDouble, theSecondDouble, theMaxDouble); Console.ReadKey(); } static T MAX(string theMessage, T theFirst, T theSecond) where T : IComparable { Console.WriteLine("\nThe generic MAX() with three arguments was called \n" + "and the message was: {0}",theMessage); T theMax = theSecond; ;
file:///D|/1/final/BBL0100.html (11 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
if (theFirst.CompareTo(theMax) > 0) theMax = theFirst; else theMax = theSecond; return theMax; } static T MAX(T theFirst, T theSecond) where T : IComparable { T theMax = theSecond; ; if (theFirst.CompareTo(theMax) > 0) theMax = theFirst; else theMax = theSecond; return theMax; } } }
//propgram_id theMaximum.cs //written_by don voils //date_written 11/08/2006 //description This program demonstrates generic methods // in C# similar to the template methods in C++. // using System; using System.Collections.Generic; using System.Text; namespace theMaximum { class Program { static void Main(string[] args) { Console.Write("What is the first integer? "); int theFirstInt = Int32.Parse(Console.ReadLine()); Console.Write("What is the Second integer? "); int theSecondInt = Int32.Parse(Console.ReadLine()); int theMaxInt = MAX(theFirstInt,theSecondInt); Console.WriteLine("\n\nThe maximum of {0} and {1} is {2}\n\n", theFirstInt,theSecondInt,theMaxInt); Console.Write("What is the first double? "); double theFirstDouble = Double.Parse(Console.ReadLine()); Console.Write("What is the Second double? "); double theSecondDouble = Double.Parse(Console.ReadLine()); double theMaxDouble = MAX(theFirstDouble, theSecondDouble); Console.WriteLine("\n\nThe maximum of {0} and {1} is {2}\n\n", theFirstDouble, theSecondDouble, theMaxDouble); Console.ReadKey(); } static T MAX(T theFirst, T theSecond)where T:IComparable { T theMax = theSecond; ; if (theFirst.CompareTo(theMax)>0) theMax = theFirst; else
file:///D|/1/final/BBL0100.html (12 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
theMax = theSecond; return theMax; } } }
file:///D|/1/final/BBL0100.html (13 von 13) [01.12.2007 04:49:26]
Lecture 12: Delegates and Events
Lecture 12: Delegates and Events Introduction to Delegates The language C++ uses pointers to access places in memory to include data variables that store either system data type or objects of programmer data types. This is done with pointers using statements dealing with system data type variables like the following: int theIntVariable; int *thePointer = &theIntVariable;
or with class objects like the following: theClass theVariable; theClass * theClassPointer = &theVariable;
and when using the new operator in C++ to create objects dynamically statements like the following are allowed: theClass* thePointer; thePointer = new theClass(theSignature);
When C# was created, it was decided that pointers to these places in memory caused too many problems and that the concept of pointers did not support OOP. Therefore pointers were replaced with references to better control these places in memory as well as to better support OOP. Therefore to refer to objects of a class, pointers are not used but instead references to these objects are used. This is accomplished as in the following example: theClass theReference; theReference = new theClass(theSignature);
In looking at these two sets of expressions above, they appear to be the same but under the "hood" they are not. References are more type safe than pointers. References can also be used when working with variables of system data types by boxing and unboxing these variables. References enable the programmer to achieve something similar to pointers to system variables and to objects but without the problems caused by pointers. Another feature of pointers in C++ is pointers to functions. You may recall that if the following is the declaration of a function: theFunction(): int theFunction(double theDouble, int theInteger, string theString);
then a pointer: thePointer to this type of function could be defined by the following statement: int (*thePointer)(double, int, string);
file:///D|/1/final/BBL0101.html (1 von 3) [01.12.2007 04:49:27]
Lecture 12: Delegates and Events
This pointer could then be assigned to point to theFunction by the following statement: thePointer = &theFunction;
As you may recall, it is possible to define an array of pointers to functions of the same type. For example: outputtype (*ptr [SIZE]) (signature);
would define the function pointer ptr to point to an array of pointers to SIZE different functions of the same type. For example see MENUS.CPP There are several interesting uses of pointers to functions other than not deciding until run time which function will be used as discussed above. Another interesting use is that a pointer to a function can be used to pass one function into the body of another function. Functions as such may not be an argument of another function. However a pointer to a function may be passed into the body of another function. Using this technique, this little inconvenience of functions not allowed to be arguments can be overcome. A callback function is a function that a program "specifies" and then "registers" in some way. The function then gets called by another part of the program. In C and C++ callback functions are implemented by functional pointers as indicated in the discussion above. As with pointers to variables, pointers to functions have problems as well and they do not support OOP. Therefore the creators of C# included a way to replace the concept of pointers to functions and at the same time make this newly defined approach support OOP. To support these concepts, the developers of C# created the delegate because pointers have problems and pointers are not used in .NET managed programming. Delegates are type safe and therefore permit the features of pointers to functions without the problems. Delegates are used as callbacks so that one class can say to another "do this work and when you are done, let me know." The delegates may be passed as arguments to other methods and may themselves pass methods. It is therefore recommended that the names of the delegates include the word: Callback or maybe NotifyCallback. While delegates are like pointers to functions in C++, they are instead objects of classes. These classes are defined as sealed classes when the delegates are called. Delegates that specify a single method are known as a singlecast delegate and their classes are implicitly derived from the System.Delegate class. Delegates that specify multiple methods are known as multicast delegates and their class is implicitly derived from the System. MulticastDelegate class. Delegates are used to encapsulate methods that will only become known at runtime. The methods may be static or non-static methods. The delegate may call these methods either synchronously or asynchronously. The arguments of these methods may be modified with ref or out. To define a delegate method, the keyword delegate must precede its declaration as in the following example: public delegate returnType delegateName(argumentList);
The keyword public is not required but is usually used. This statement defines a delegate that can be used with functions whose output type is: returnType and whose signature is: argumentList. In the current version of C# most of the delegates used are created by the IDE and not the programmer. Therefore while this lecture provides some discussion of delegates, it will not provide an indepth discussion because this course only uses delegates that are created by the IDE. In addition as C# has developed from .NET 1.0 to .NET 2.0 more of this type of coding is being done by the IDE. It would be reasonable to expect that in future versions of the . NET environment, even additional coding will be done by the IDE and therefore even less knowledge of delegates will be necessary
file:///D|/1/final/BBL0101.html (2 von 3) [01.12.2007 04:49:27]
Lecture 12: Delegates and Events
file:///D|/1/final/BBL0101.html (3 von 3) [01.12.2007 04:49:27]
Singlecast Delegates
Singlecast Delegates For an example of a singlecast delegate, suppose that you are designing a program which needs to be able to sort inventory items using their inventory item numbers. Suppose that sometimes the program should be able to sort in ascending order and sometimes the program would sort in descending order. What could be done is to create both approaches. That is to create methods for each approach. However delegates provide the opportunity to create only one approach and at runtime which sort is going to be used would be decided then. Example 1: To begin with, it is necessary to first define the delegate. For example suppose that the program had the following delegate declaration: public delegate toCompare ToSortCallBack(object firstObject, object secondObject);
where toCompare is the following enumerated data type: public enum toCompare {theFirst, theSecond}
This is a definition of the delegate ToSortCallBack whose signature is two objects and whose output is a one of the enumerators of the enumerated data type: toCompare. As noted from the above general form of delegates, this definition includes the keyword: delegate as well as the function name, the output type, the signature and the access specifier (it happens to be public this time but it could be one of the other access specifier possibilities.) Notice that this definition of the delegate contains no body. As a result, this definition does not include what the outcome of this method will be. The outcome is decided at runtime when a particular implementation is selected. The next step is to define an implementation of this delegate in a program. To achieve this objective, the program is going to include the definition of the following class: theData that includes the definition of the methods: toSort() and toReverse() that have as arguments a reference: whichWay to the delegate: ToSortCallBack. Notice that whichWay is an implementation of the delegate ToSortCallBack and that it is being passed into the body of the methods toSort() and toReverse(): public class theData { private object[] ourData = new object[2]; public theData(object firstOne, object secondOne) { ourData[0] = firstOne; ourData[1] = secondOne; } public void toSort(ToSortCallBack whichWay) { if(whichWay(ourData[0],ourData[1]) == toCompare.theSecond) { object temp = ourData[0]; ourData[0] = ourData[1]; ourData[1] = temp; } } public void toReverse(ToSortCallBack whichWay) file:///D|/1/final/BBL0102.html (1 von 5) [01.12.2007 04:49:28]
Singlecast Delegates
{ if(whichWay(ourData[0],ourData[1]) == toCompare.theFirst) { object temp = ourData[0]; ourData[0] = ourData[1]; ourData[1] = temp; } } public override string ToString() { return (ourData[0].ToString() + ", " + ourData[1].ToString()); } }
In addition to this class, the following class is included in the program to enable the testing of the sorting on inventory numbers: public class theInventory { private string inventoryNumber; public theInventory(string theNumber) { inventoryNumber = theNumber; } public static toCompare WhichisFirst(object first, object second) { theInventory theFirst = (theInventory) first; theInventory theSecond = (theInventory) second; return (String.Compare(theFirst.inventoryNumber, theSecond.inventoryNumber) < 0 ? toCompare.theFirst:toCompare.theSecond); } public override string ToString() { return inventoryNumber; } }
Notice in the definition of the class: theInventory that there is a definition of a static method: WhichisFirst() that fits the function type declared by the delegate:ToSortCallBack(). As a result, it may be passed into the methods: toSort() and toReverse(). See Delegate.cs. Example 2: In the next example, the delegate is defined above the program class with the following statement: public delegate void NotifyCallback(decimal theBalance);
Notice the use of the word: Callback in the name and the access is public. As stated above, this is frequently recommended to be part of the name of a delegate.
file:///D|/1/final/BBL0102.html (2 von 5) [01.12.2007 04:49:28]
Singlecast Delegates
The implementations of this delegate in the program are the following two static methods: private static void CurrentStatusCallback(decimal theBalance) { Console.WriteLine("\n\nDear Customer:"); Console.WriteLine(" Your balance is {0:c}",theBalance); } private static void OverDrawnAccountCallback(decimal theBalance) { Console.WriteLine("\n\nDear Customer:"); Console.WriteLine(" You are overdrawn and your " + "balance is {0:c}", theBalance); }
Again notice the use of the word: Callback in each of the function's name. As can be seen from the above definitions, these static methods match the type of function that the delegate: NotifyCallback() can call in terms of the signature and the output. At the top of the program, is the following statement that then connects the first of these definitions with the delegate NotifyCallback() which was defined above the namespace for the program: NotifyCallback status = new NotifyCallback(currentStatus);
Next notice that the class: Accounts is connected to this delegate in several ways. First it has the following attribute that is defined as an instance of the delegate: private NotifyCallback theCall;
Next the class' definition includes the delegate in the following class constructor: public Accounts(decimal theBalance, NotifyCallback theOne) { balance = theBalance; theCall = theOne; }
and then to implement this constructor the following statement is included in the program and it includes as an argument the delegate method status defined in the program.: Accounts theOne = new Accounts(theAmount,status);
The following two methods in this class call the delegate regardless of which function is being represented by theCall(): public void Deposit(decimal the Amount) { balance += theAmount; theCall(balance);
file:///D|/1/final/BBL0102.html (3 von 5) [01.12.2007 04:49:28]
Singlecast Delegates
}
and public void Withdrawal(decimal theAmount) { balance -= theAmount; theCall(balance); }
Notice in both cases that the argument of theCall() is a decimal and that there is no output so that each of these methods is an implementation of the delegate: NotifyCallback(). The class Accounts also contains the following method which can then be used to change the value of theCall: public void SetDelegate(NotifyCallback theOne) { theCall = theOne; }
Finally notice in the program when a deposit is being recorded that the following code uses the method: SetDelegate() to switch between CurrentStatusCallback() and OverDrawnAccountCallback() depending on the account's balance: if((theOne.Balance+theAmount)< 0.00m) { status = overdrawnStatus; theOne.SetDelegate(status); } else { status = currentStatus; theOne.SetDelegate(status); }
Similarly when a withdrawal is being recorded then using the method: SetDelegate(), the following code switches between CurrentStatusCallback() and OverDrawnAccountCallback() depending on the account's balance: if((theOne.Balance-theAmount)< 0.00m) { status = overdrawnStatus; theOne.SetDelegate(status); } else { status = currentStatus; theOne.SetDelegate(status); }
For an implementation of this example look at the following two files: Accounts.cs (the class file) and BankAccounts.cs (the program file). file:///D|/1/final/BBL0102.html (4 von 5) [01.12.2007 04:49:28]
Singlecast Delegates
file:///D|/1/final/BBL0102.html (5 von 5) [01.12.2007 04:49:28]
Multicast Delegates
Multicast Delegates If a program contained the following implementations: theFirst, theSecond and theThird, of the same delegate, then the following actions could be possible: theFirst += theSecond; theFirst -= theSecond; theFirst = theSecond + theThird;
It is the ability to implement these features that makes these delegates multicast. As a result, each of these delegates is an implementation of a System.Multicast. Note: If you look into the File.Design.cs file for some C# windows programs you will notice the first of these statements being used. Using the class Accounts.cs previously discussed and with a few modifications of the program file: BankAccounts.cs, it is possible to do the following for deposits: if((theOne.Balance+theAmount)<-500.00m) { status = overdrawnStatus; status += notifyBank; theOne.SetDelegate(status); } else { if((theOne.Balance+theAmount)< 0.00m) { status = overdrawnStatus; theOne.SetDelegate(status); } else { if((theOne.Balance+theAmount)>=0.00m) { status = currentStatus; theOne.SetDelegate(status); } } } theOne.Deposit(theAmount);
and then the following for withdrawals: if((theOne.Balance-theAmount)<-500.00m) { status = overdrawnStatus; status += notifyBank; theOne.SetDelegate(status); } else { if((theOne.Balance-theAmount)< 0.00m) file:///D|/1/final/BBL0103.html (1 von 3) [01.12.2007 04:49:29]
Multicast Delegates
{ status = overdrawnStatus; theOne.SetDelegate(status); } else { if((theOne.Balance-theAmount)>=0.00m) { status = currentStatus; theOne.SetDelegate(status); } } } theOne.Withdrawal(theAmount);
Notice in the above code where the two delegates were added together. (Note: It is also possible to subtract one delegate from another if appropriate.) The above code is based upon the fact that status is defined as: NotifyCallback status = new NotifyCallback(currentStatus);
and this statement is preceded by the following statements: NotifyCallback currentStatus = new NotifyCallback(CurrentStatusCallback); NotifyCallback overdrawnStatus = new NotifyCallback(OverDrawnAccountCallback); NotifyCallback notifyBank = new NotifyCallback(NotifyBankCallback);
These three delegates were defined by the following code in the program: private static void CurrentStatusCallback(decimal theBalance) { Console.WriteLine("\n\nDear Customer:"); Console.WriteLine(" Your balance is {0:c}",theBalance); } private static void OverDrawnAccountCallback(decimal theBalance) { Console.WriteLine("\n\nDear Customer:"); Console.WriteLine(" You are overdrawn and your balance is {0:c}",theBalance); } private static void NotifyBankCallback(decimal theBalance) { Console.WriteLine("\n\nDear Bank Manageer:"); Console.WriteLine(" The customer has overdrawan their " + "account and the balance is {0:c}",theBalance); }
For an example of multicast delegates use the class file: Accounts.cs along with the program file: BankAccounts2.cs.
file:///D|/1/final/BBL0103.html (2 von 3) [01.12.2007 04:49:29]
Multicast Delegates
When Windows programs are created, the IDE creates multicast delegates. This can be seen in the hidden section of the code where delegates will be added and subtracted. Most of the work with delegates is done by the IDE and even more is expected in future versions of the .NET environment.
file:///D|/1/final/BBL0103.html (3 von 3) [01.12.2007 04:49:29]
Introduction to Events
Introduction to Events The major use of delegates in C# is to create event handlers for events. The GUI interfaces of Windows and web browsers require that programs respond to events. An event like pushing a button, clicking a check box, making a menu selection and making a list box selection each requires that these selections (events) have some response occur. Each of these constructs remains inactive until an event like pressing a button occurs and then they respond to that part of the code designed to receive their event. The construct event is created for example when you click a button in a Windows program. In one of the examples in the notes, there is a button labeled Enter Data and named: btnEnter. Associated with this button is a class that has a delegate function associated with it. In the program the following event handler that is dependent on this delegate was created to enable the sender to call the following function: private void btnEnter_Click(object sender, System.EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); ClearBoxes(); txtID.Focus(); }
This function implements a delegate that has as arguments an instance sender of the class object (therefore any data type) and an instance e of the class: System.EventArgs. This is a common signature for this type of event handler. The output of such a delegate is always void. The following is another example of an event handler in another Windows program where the button has the name btnClear: private void btnClear_Click(object sender, System.EventArgs e) { ClearForm(); }
The design of C# is such that any class may be designed to publish to other classes to enable them to subscribe to an event of the publishing class. When an object of a class permits others to subscribe to its event, they are then notified when the event occurs thereby carrying out their instructions automatically. This design is based upon delegates. To implement this design an instance of the class needs to define a method (called an event handler) that is based upon the class' delegate. By convention these event handlers return void and take two arguments. The first argument is the "source" of the event; i.e. the publishing object. The second argument is an object derived from EventArgs. EventArgs is the base class for all event data. As with other classes, it is derived from System.Object and therefore implements this class' methods. In addition to a constructor, this class has a public static attribute: empty. This represents any event that has no state. The general form of an event is the following: [modifiers] event theType memberName
file:///D|/1/final/BBL0104.html (1 von 3) [01.12.2007 04:49:29]
Introduction to Events
For example public event TheHandler OntheChange
In C# it is in general not necessary to write events explicitly. For example if you open Properties, you will see the following:
Notice the yellow lighting bolt icon. Click this icon and you will see the following names of events that may be selected for a program:
file:///D|/1/final/BBL0104.html (2 von 3) [01.12.2007 04:49:29]
Introduction to Events
The above graphic lists some of the events that are possibly in C# that the IDE will write when selected. What will be done in some later examples will be to come to the Properties and select one of these events rather than writing them. In this course the events used will be created by the IDE. As was stated above with respect to delegates, the .NET's IDE provides the programmer with significant assistance needed to use events. Therefore other than this brief introduction to the existence of events, no in depth discussion of events will be provided. A more in depth discussion is beyond the objectives of these lectures. In addition as the . NET environment evolves even more will be done for the programmer and as a result even less knowledge about this topic will be needed.
file:///D|/1/final/BBL0104.html (3 von 3) [01.12.2007 04:49:29]
Lecture 12 Examples
Lecture 12 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
Accounts.cs
This file contains the definition of the class Accounts. Used with BankAccount. cs, the files present a single cast delegate example. Along with BankAccount2. cs, the files demonstrate multicast delegates.
Accounts2.cs
his file contains the definition of the class Accounts. Along with the BankAccount2.cs, they demonstrate multicast delegates.
BankAccounts2. cs
This file along with the class file, Accounts.cs demonstrates the use of multicast delegates.
BankAccounts.cs
This file along with the class file, Accounts.cs demonstrates the use of single cast delegates.
Delegate.cs
This program demonstrates a use of delegates.
Menus.cpp
This C++ program demonstrates the use of arrays of pointers to functions.
// program_id Accounts2.cs // written_by don voils // date_written 11/23/2006 // description This file contains the definition of the class // Accounts. Along with the BankAccount2.cs, they // demonstrate multicast delegates. // using System; namespace Accounts { public class Accounts { private decimal balance; private NotifyCallback theCall; public Accounts(decimal theBalance, NotifyCallback theOne) { balance = theBalance; theCall = theOne; theCall(theBalance); } public void SetDelegate(NotifyCallback theOne) { theCall = theOne; } public void Deposit(decimal theAmount) { balance += theAmount; theCall(balance); } public void Withdrawal(decimal theAmount) { file:///D|/1/final/BBL0105.html (1 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
balance -= theAmount; theCall(balance); } public decimal Balance { get { return balance; } } } }
// program_id Accounts.cs // written_by don voils // date_written 11/23/2006 // description This file contains the definition of the class // Accounts. Used with BankAccount.cs, the files // present a single cast delegate example. // Along with BankAccount2.cs, the files demonstrate // multicast delegates. // using System; namespace Accounts { public class Accounts { private decimal balance; private NotifyCallback theCall; public Accounts(decimal theBalance, NotifyCallback theOne) { balance = theBalance; theCall = theOne; theCall(theBalance); } public void SetDelegate(NotifyCallback theOne) { theCall = theOne; } public void Deposit(decimal theAmount) { balance += theAmount; theCall(balance); } public void Withdrawal(decimal theAmount) { balance -= theAmount; theCall(balance); }
file:///D|/1/final/BBL0105.html (2 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
public decimal Balance { get { return balance; } } } }
// program_id BankAccounts2.cs // written_by don voils // date_written 11/23/2006 // description This file along with the class file, Accounts2.cs demonstrates // the use of multicast delegates. // using System; public delegate void NotifyCallback(decimal theBalance); namespace Accounts { class theProgram { static void Main() { NotifyCallback currentStatus = new NotifyCallback(CurrentStatusCallback); NotifyCallback overdrawnStatus = new NotifyCallback(OverDrawnAccountCallback); NotifyCallback notifyBank = new NotifyCallback(NotifyBankCallback); NotifyCallback status = new NotifyCallback(currentStatus); decimal theAmount; Console.Write("What was the starting balance? "); theAmount = Decimal.Parse(Console.ReadLine()); Accounts theOne = new Accounts(theAmount,status); char again = 'Y'; char type = 'D'; do { Console.Write("\nDo you want to enter deposit or withdrawal? (D/W)"); type = Char.Parse(Console.ReadLine()); switch(type) { case 'D': case 'd': Console.Clear(); Console.Write("\n\nHow much was the deposit? "); theAmount = Decimal.Parse(Console.ReadLine()); if((theOne.Balance+theAmount)<-500.00m) { status = overdrawnStatus;
file:///D|/1/final/BBL0105.html (3 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
status += notifyBank; theOne.SetDelegate(status); } else { if((theOne.Balance+theAmount)< 0.00m) { status = overdrawnStatus; theOne.SetDelegate(status); } else { if((theOne.Balance+theAmount)>=0.00m) { status = currentStatus; theOne.SetDelegate(status); } } } theOne.Deposit(theAmount); break; case 'W': case 'w': Console.Clear(); Console.Write("\n\nHow much was the withdrawal? "); theAmount = Decimal.Parse(Console.ReadLine()); if((theOne.Balance-theAmount)<-500.00m) { status = overdrawnStatus; status += notifyBank; theOne.SetDelegate(status); } else { if((theOne.Balance-theAmount)< 0.00m) { status = overdrawnStatus; theOne.SetDelegate(status); } else { if((theOne.Balance-theAmount)>=0.00m) { status = currentStatus; theOne.SetDelegate(status); } } } theOne.Withdrawal(theAmount); break; default: Console.WriteLine("\n\nPlease enter a D or W."); break; } Console.Write("\nDo you want to enter another transaction? (Y/N)"); again = Char.Parse(Console.ReadLine()); Console.Clear(); }while((again=='y') || (again=='Y'));
file:///D|/1/final/BBL0105.html (4 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
Console.WriteLine("\n"); Console.ReadKey(); } private static void CurrentStatusCallback(decimal theBalance) { Console.WriteLine("\n\nDear Customer:"); Console.WriteLine(" Your balance is {0:c}",theBalance); } private static void OverDrawnAccountCallback(decimal theBalance) { Console.WriteLine("\n\nDear Customer:"); Console.WriteLine(" You are overdrawn and your balance is {0:c}",theBalance); } private static void NotifyBankCallback(decimal theBalance) { Console.WriteLine("\n\nDear Bank Manager:"); Console.WriteLine(" The customer has overdrawn their account and " + "their balance is {0:c}",theBalance); } } }
// program_id BankAccounts.cs // written_by don voils // date_written 11/23/2006 // description This file along with the class file, Accounts.cs // demonstrates the use of single cast delegates. // using System; public delegate void NotifyCallback(decimal theBalance); namespace Accounts { class theProgram { static void Main() { NotifyCallback currentStatus = new NotifyCallback(CurrentStatusCallback); NotifyCallback overdrawnStatus = new NotifyCallback(OverDrawnAccountCallback); NotifyCallback status = new NotifyCallback(currentStatus); decimal theAmount; Console.Write("What was the starting balance? "); theAmount = Decimal.Parse(Console.ReadLine()); Accounts theOne = new Accounts(theAmount,status); char again = 'Y'; char type = 'D'; do { Console.Write("\nDo you want to enter deposit or" +
file:///D|/1/final/BBL0105.html (5 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
" withdrawal? (D/W) "); type = Char.Parse(Console.ReadLine()); switch(type) { case 'D': case 'd': Console.Clear(); Console.Write("\n\nHow much was the deposit? "); theAmount = Decimal.Parse(Console.ReadLine()); if((theOne.Balance+theAmount)< 0.00m) { status = overdrawnStatus; theOne.SetDelegate(status); } else { status = currentStatus; theOne.SetDelegate(status); } theOne.Deposit(theAmount); break; case 'W': case 'w': Console.Clear(); Console.Write("\n\nHow much was the withdrawal? "); theAmount = Decimal.Parse(Console.ReadLine()); if((theOne.Balance-theAmount)< 0.00m) { status = overdrawnStatus; theOne.SetDelegate(status); } else { status = currentStatus; theOne.SetDelegate(status); } theOne.Withdrawal(theAmount); break; default: Console.WriteLine("\n\nPlease enter a D or a W."); break; } Console.Write("\nDo you want to enter another " + "transaction? (Y/N) "); again = Char.Parse(Console.ReadLine()); Console.Clear(); }while((again=='y') || (again=='Y')); Console.WriteLine("\n"); Console.ReadKey(); }
file:///D|/1/final/BBL0105.html (6 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
private static void CurrentStatusCallback(decimal theBalance) { Console.WriteLine("\n\nDear Customer:"); Console.WriteLine(" Your balance is {0:c}",theBalance); } private static void OverDrawnAccountCallback(decimal theBalance) { Console.WriteLine("\n\nDear Customer:"); Console.WriteLine(" You are overdrawn and your balance is {0:c}",theBalance); } } }
// program_id Delegate.cs // written_by don voils // date_written 11/28/2006 // description This program demonstrates a use // of delegates. // using System; namespace newDelegate { public enum toCompare {theFirst,theSecond} public delegate toCompare ToSortCallBack(object firstObject, object secondObject); public class theData { private object[] ourData = new object[2]; public theData(object firstOne, object secondOne) { ourData[0] = firstOne; ourData[1] = secondOne; } public void toSort(ToSortCallBack whichWay) { if(whichWay(ourData[0],ourData[1]) == toCompare.theSecond) { object temp = ourData[0]; ourData[0] = ourData[1]; ourData[1] = temp; } } public void toReverse(ToSortCallBack whichWay) { if(whichWay(ourData[0],ourData[1]) == toCompare.theFirst) { object temp = ourData[0];
file:///D|/1/final/BBL0105.html (7 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
ourData[0] = ourData[1]; ourData[1] = temp; } } public override string ToString() { return (ourData[0].ToString() + ", " + ourData[1].ToString()); } } public class theInventory { private string inventoryNumber; public theInventory(string theNumber) { inventoryNumber = theNumber; } public static toCompare WhichisFirst(object first, object second) { theInventory theFirst = (theInventory) first; theInventory theSecond = (theInventory) second; return (String.Compare(theFirst.inventoryNumber, theSecond.inventoryNumber) < 0 ? toCompare.theFirst : toCompare.theSecond); } public override string ToString() { return inventoryNumber; } } class theProgram { static void Main() { Console.Write("What is the inventory number " + "of item 1? "); string theEntered = Console.ReadLine(); theInventory numberOne = new theInventory(theEntered); Console.Write("\nWhat is the inventory number " + "of item 2? "); theEntered = Console.ReadLine(); theInventory numberTwo = new theInventory(theEntered); theData inventoryData = new theData(numberOne,numberTwo);
file:///D|/1/final/BBL0105.html (8 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
Console.WriteLine("\nThe numbers entered were {0}", inventoryData.ToString()); ToSortCallBack theInventorySort = new ToSortCallBack(theInventory.WhichisFirst); inventoryData.toSort(theInventorySort); Console.WriteLine("\nAfter the sort the data is " + "{0}", inventoryData); inventoryData.toReverse(theInventorySort); Console.WriteLine("\nAfter the reverse sort " + "the data is {0}\n\n",inventoryData); Console.ReadKey(); } } }
// program-id MENUS.CPP // author DON VOILS // date written SEPTEMBER 21, 1988 // modified by dlv // date(s) modified 12/3/93 // program description THIS PROGRAM CONTAINS THE MENUS // FOR ALL MODULES OF THE ACCOUNTING // SYSTEM. FROM THESE MENUS THE USER // CAN SELECT WHICH OF THE ACCOUNTING // MODULES HE/SHE WANTS TO USE. // // One of the new modifications was the // creation of arrays of pointers to functions. // The individual menus were then changed so // that these arrays would call the individual // functions required by the menus. This was // done by using the ability of C++ to permit // late binding of function. Notice that in // each case the exact function to be used // on the menu choice is not determined // until the program is executed. This enables // the elimination of the switch. Late binding // causes the program to be larger but the // elimination of the switches makes it smaller. // #include #include #include<string> using namespace std; // FUNCTION PROTOTYPES // void expense_ldgr();
file:///D|/1/final/BBL0105.html (9 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
void sales_ldgr(); // Empty functions // void strtclnt(){}; void expenseout(){} void expenseedit(){} void expenseprt(){} void eomexpenses(){} void quit_expenses(){}
void salesout(){}; void salesprt(){}; void salesedit(){}; void eomsales(){}; void quit_sales(){}; void pandl(){}; void eoy(){}; void quit() { for(int loop_counter=0;loop_counter<=50;++loop_counter) cout << endl; exit(1); } // The following are arrays of pointers to functions which are // used to make the individual menus work without the switch. // void (*menu1[])()={strtclnt, expense_ldgr, sales_ldgr, pandl, eoy, quit}; void (*menu2[])()={expenseout, expenseedit, expenseprt, eomexpenses, quit_expenses}; void (*menu3[])()={salesout, salesedit, salesprt, eomsales, quit_sales}; void main() { char index; do { for(int loop_counter=0;loop_counter<=50;++loop_counter) cout << endl; cout << " Main Menu" << endl << endl << endl << " 1. Start New Client" << endl << endl << " 2. Expense Ledger Menu" << endl << endl << " << " << " << " << "
3. 4. 5. 6.
Sales Ledger Menu" << endl << endl Print P&L" << endl << endl End of Year Processing" << endl << endl Exit" << endl << endl Which? ";
file:///D|/1/final/BBL0105.html (10 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
cin.get(index).get(); // This is an example of late binding. The compiler does not specify // the location of the jump until the execution of the program. // menu1[(index-'0')-1](); for(loop_counter=0;loop_counter<=50;++loop_counter) cout << endl; }while (1); } /*
program-id EXPENSE_LDGR() author DON VOILS date written SEPTEMBER 21, 1988 modified by date(s) modified hardware requirements IBM XT/AT 512 K RAM HARDDISK software requirements PC DOS 2.1 or higher program description THIS FUNCTION CONTAINS THE MENU FOR THE EXPENSES.
*/ void expense_ldgr() { int loop_counter; char index; /* THIS MODULE HELPS THE USER TO SELECT WHICH OF THE EXPENSE MODULES TO USE. */ do { for(loop_counter=0;loop_counter<=50;++loop_counter) cout << endl; cout << flush; cout << " Expense Ledger Menu" << endl << endl << " 1. Enter Expenses" << endl << endl << " 2. Change Expenses" << endl << endl << " 3. Print Expense Ledger" << endl << endl << " 4. End of Month Processing for Expenses" << endl << endl << " 5. Return to Main Menu" << endl << endl << " Which? "; cin.get(index).get(); menu2[(index-'0')-1](); if (index=='5') break; } while (1); }
file:///D|/1/final/BBL0105.html (11 von 12) [01.12.2007 04:49:31]
Lecture 12 Examples
/*
program-id SALES_LDGR() author DON VOILS date written SEPTEMBER 21, 1988 modified by date(s) modified hardware requirements IBM XT/AT 512 K RAM HARDDISK software requirements PC DOS 2.1 or higher program description THIS FUNCTION CONTAINS THE MENU FOR THE SALES.
*/ void sales_ldgr() { int loop_counter; char index; /* THIS MODULE HELP THE USER TO SELECT WHICH OF THE SALES MODULES TO USE. */ do { for(loop_counter=0;loop_counter<=50;++loop_counter) cout << endl; cout << flush; cout << " Sales Ledger Menu" << endl << endl << " 1. Enter Sales" << endl << endl << " 2. Change Sales" << endl << endl << " 3. Print Sales" << endl << endl << " 4. End of Month Processing for Sales" << endl << endl << " 5. Return to Main Menu" << endl << endl << " Which? "; cin.get(index).get(); menu3[(index-'0')-1](); if (index=='5') break; } while (1); }
file:///D|/1/final/BBL0105.html (12 von 12) [01.12.2007 04:49:31]
Lecture 13: Building Windows Applications and Event Driven Programming
Lecture 13: Building Windows Applications and Event Driven Programming Notice: Graphics are listed to be used in this lecture. However they are not included in this book. If you would like to have access to these graphics, email: [email protected].
Invoices Specification: Create an invoicing program that permits the entry of the product ID number of the product ordered, the name of that product, the number of that product ordered and finally the cost per item ordered. Have the program permit the entry of as many items as the user desires. When the items ordered have been entered, permit the user to display the invoice items ordered in the window where the data entered is arranged in columns with column headers. Have the program calculate the total cost for each item and the total cost for the entire invoice. After the invoice data stored in memory has been displayed, it should be cleared so that another invoice may be entered. The form should have labels with the following text: Product ID Number, Product Name, Number of Items Purchased and Price per Item. There should be four textboxes (one for each label) that would permit the entry of each of the four items to be provided by the user. There should be three buttons with the following text: Enter Data, Display Invoice and Clear Invoice that will provide the services indicated by their text. Next there should be a textbox where the invoice items will be displayed once all of the items have been entered and the Display Invoice button is clicked. The form should look like the following:
(Note: In addition to the sample form above, there should be sufficient data samples supplied to adequately test the program. This is left to the reader to supply.) When the program loads, the textboxes should all be empty and the two buttons will be grayed out. The program should then permit the user to enter each of the four properties of the item ordered into their respective textboxes. This should be followed by clicking the Enter Data button. When the Enter Data button is clicked, have the data that was entered stored into arrays. After the data has been stored into the arrays, have each of the text boxes cleared and the button: Display Invoice and Clear Invoice should become active. When all of the data has been entered, the user will click the Display Invoice button and the data will appear in the Display Invoice textbox. The data should appear in columns with a column header above each column to include the four items of data entered and the total amount for that item. The headers should be: Product ID, Product Name, Number, Price and Total. After all of the items have been displayed, have the total for the invoice display below the data in the Total column. Coding: Open Visual Studio .NET 2005 and create the C# Windows project: Invoices. Click on the form and then Properties. Change the form's Text to Invoices. Set the Size, Maximum Size and Minimum Size to 900, 550. file:///D|/1/final/BBL0106.html (1 von 4) [01.12.2007 04:49:32]
Lecture 13: Building Windows Applications and Event Driven Programming
Select for Font: Courier New and size 10. (Note: Using this font will make it easier to control the format of the data that will be displayed in the bottom textbox.) Place the five textboxes, the three buttons and the four labels as indicated in the specification document above. (Be sure to leave room between the top of the textboxes and the blue bar for additional controls that will be added later.) Change the names of the first four text boxes to txtID, txtName, txtNumber and txtPrice respectively. Set their Tab Index to 1 through 4 respectively. Set the Text Align of txtNumber and txtPrice to Right. Name the fifth textbox: txtDisplayInvoice. Set its Tab Index to 7, its TabStop to false, its ReadOnly to true, its Scroll Bars to Vertical, set its MultiLine to true, set its ScrollBar to Vertical, set its Location to 15,265 and set its Size to 860,230. Pick values for the size and location of the other textboxes to make them more attractive. Place the four labels as indicated above with the Text as: Product ID Number, Product Name, Number of Items Purchased and Price per Item respectively. Using the property Font, make all of the text bold. Leave their names unchanged. Pick values for the size and location of the textboxes to make them look attractive. Try to use the IDE's automatic alignment feature. Place the three buttons as indicated in the Specification document. Change their Text to Enter Data, Display Invoice and Clear Invoice as indicated. Name the buttons: btnEnter, btnDisplay and btnClear respectively. Using the property Font, make all of the text bold. Set the Tab Index of the button Enter Data to 5. Set the Tab Index of the button Display Invoice to 6 and its Tab Stop to false. Set the Tab Index of the button Clear Invoice to 7 and its TabStop to false. Pick values for the size and location of these buttons to make them attractive. Try to use the IDE's alignment feature. Since the program will permit the entry of as many items as the user desires, the type of arrays used for each of the items entered should be from ArrayList. Therefore add the following attributes to the class Form1: private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList();
Note: Recall that to use an ArrayList requires the addition of the following using statement: using System.Collections;
Add this statement to the top of the program below the other using statements if it is not already available. Modify the Form1 constructor to the following: public Form1() { InitializeComponent(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); }
The second and third statements set the Display and the Clear buttons so that they do not allow clicking until data has been entered. The fourth statement sets the startup focus to the textbox for the Product ID Number. Create the following method in the class Form1:
file:///D|/1/final/BBL0106.html (2 von 4) [01.12.2007 04:49:32]
Lecture 13: Building Windows Applications and Event Driven Programming
private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); }
Recall that the Enter Data button was named: btnEnter. From the Designer Mode, double click on the Enter Data button and when the IDE changes to the View Code, enter the following code into the event handler for this button: private void btnEnter_Click(object sender, System.EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); btnDisplay.Enabled = true; btnClear.Enabled = true; ClearBoxes(); txtID.Focus(); }
Notice the addition of each of the entries to their respective arrays by using the ArrayList method: Add(). Notice the use of the ClearBoxes() method to clear the textbox entries after the entries have been stored into the arrays. Notice the movement of the program's focus to the Product ID textbox by using the method: Focus() in the code above. Recall that the Display Invoice button was named: btnDisplay. From the Designer Mode, double click on the Display Invoice button and when the View Code appears enter the following code into the event handler: private void btnDisplay_Click(object sender, System.EventArgs e) { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20)+ "Product Name".PadRight(20)+ "Number".PadRight(15)+ "Price".PadRight(20)+ "Total".PadRight(20)+"\r\n"; int numberItems = productID.Count; for(int index=0;index
file:///D|/1/final/BBL0106.html (3 von 4) [01.12.2007 04:49:32]
Lecture 13: Building Windows Applications and Event Driven Programming
String.Format("{0,60:c}",invoiceTotal); }
Notice in the above code that for some of the string output in the header, the string method: PadRight() was used to get the data to appear left justified in the columns. For the rows and the footer, the traditional formatting was used except for the strings negative numbers were used to get the text data to be left justified in the columns. The Clear Invoice button is named: btnClear. From the Designer Mode, double click on the Clear Invoice button and when it changes to the View Code enter the following code into the event handler: private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); }
After you have entered the above four methods into your program, compile and run it. Notice that you can move from one textbox to the next by pressing the tab key. See Invoices_Form1.cs, Invoices_Form1.Designer.cs and Invoices_Program.cs
file:///D|/1/final/BBL0106.html (4 von 4) [01.12.2007 04:49:32]
Invoices Menu
Invoices Menu Built into the Visual Studio .NET IDE are the tools to create menu bar tools, status bars, message boxes and popup menus. The purpose of this part of the lecture is to learn how to use these tools and therefore to create SDI programs. To begin with, create a project: menuInvoices. Copy into this project the files that were created for the program Invoices. Or link to the following files: Invoices_Form1.cs, Invoices_Form1.Designer.cs and Invoices_Program. cs The objective of this example will be to do maintenance on that program by including a menu. Next open the Toolbox and select the option: MenuStrip and drag it to the top of the form but just below the blue bar. In the Form1.cs[Design] view, you should now see something like the following:
Notice at the bottom of the screen is a block that contains: menuStrip1 and at the top of the form just below the blue name bar is a block that contains the words: Type Here. If the Type Here should disappear, click the menuStrip1 at the bottom of the form. Click on the Type Here and when it opens type in: &File and press the Enter key. (The purpose of the & is to permit the user to type the Alt-F to activate this menu option.) When you type this information in, two new Type Here regions appear: one below and one to the right. These are open for you to type in additional commands as you can see in the following graphic: In the View Code, change the namespace to menuInvoices in each of the three files. Next, switch to the Designer view. Click on the form. Open Properties and change the Text of the form to Menu Invoices.
In the Type Here region below the &File, place: &New followed by clicking the Enter key. In the next Type Here below that entry, place the text: &Open and press Enter. In the next Type Here enter a minus sign (-). This places a separation line between the menu controls that have already been entered and the ones that will follow. In the next Type Here place &Save and press Enter. In the next Type Here enter the minus symbol (-) and press Enter. Follow this by &Print, then another minus sign (-) followed by E&xit. file:///D|/1/final/BBL0107.html (1 von 12) [01.12.2007 04:49:34]
Invoices Menu
Compile and run the program. Notice that the word: File is now in the menu location. Try Alt-F and notice that the menu opens up and reveals all of the options under File. It should now look like the following:
Select Form1.cs[Designer]. Click the menuStrip1 strip at the bottom of the screen. In the Properties window change the Name to MainMenu. Click on the File on the menu and observe the Properties menu for this option. Change the name of this option to: fileMenuItem. Now perform a similar action for each of the other options using the respective names listed in the following table:
Open table as spreadsheet Item
New name
New
newMenuItem
Open
openMenuItem
Save
saveMenuItem
Print
printMenuItem
Exit
exitMenuItem
For an elementary demonstration of how to implement these menu options, open the menu in the Designer view and double click on the Exit option. When you do this, an event hander for this option should appear. Modify the code in this event handler to the following: private void exitMenuItem_Click(object sender, System.EventArgs e) { Application.Exit(); }
Now compile and run the program. Click Alt+F. and then click the X key This will open the menu and notice that next the program is exited. Clicking on any of the other options will not do anything because their event handlers have not yet been implemented. The next step is to activate the & for each of the menu options. First select the New opton on the menu while in Designer mode. Click on ShortcutKeys. Select: as Modifiers: Ctrl. In the Key: column scroll down until you have reached N and select it. What you should see is something like the following:
file:///D|/1/final/BBL0107.html (2 von 12) [01.12.2007 04:49:34]
Invoices Menu
Press the Enter key. Using this approach change each of the remaining menu options' ShortcutKey to the following:
Open table as spreadsheet Item
Shortcut
File
Alt+F
Open
Ctrl+O
Save
Ctrl+S
Print
Ctrl+P
Exit
Ctrl+X
When the program begins, the textboxes will contain no data. Therefore it would not make sense for the program have available the menu options to Save or to Print. Therefore, for each of these options, change Enabled to False. Compile and run the program. Open the menu and it should look like the following with these two options shaded out:
file:///D|/1/final/BBL0107.html (3 von 12) [01.12.2007 04:49:34]
Invoices Menu
To begin the entry of data into program, the user should click New on the menu. This menu option should enable each of the four textboxes and the Enter Data button. Therefore when the program begins, the buttons Clear Invoice, Enter Data and Display Invoice and the text boxes should not be enabled. To achieve this, the Form1 constructor should be changed to the following: public Form1() { InitializeComponent(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; txtID.Focus(); }
Recall that part of this code was already done in the Form1 constructor in the original program. Compile and run the program. Notice that each of the four textboxes and the three buttons are now grayed out and it is not possible to enter any data into the textboxes or to press any of the buttons. The next step is to enable the New menu option so close the program and return to the Designer mode. To begin with, double click the menu item: New in the Designer. When you do, an event handler will be created‥ Change it to the following: private void newMenuItem_Click(object sender, System.EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveMenuItem.Enabled=true; printMenuItem.Enabled=true; btnEnter.Enabled = true;
file:///D|/1/final/BBL0107.html (4 von 12) [01.12.2007 04:49:34]
Invoices Menu
txtID.Focus(); }
The first line in this event handler will call the method ClearBoxes() which as you will recall from the previous example Invoice.exe clears each of the textboxes. The next four lines enable each of the four textboxes. Now since a new invoice is being created, it should now be possible to Save or to Print. Therefore the next two lines enable these two menu option. The next option enables the Enter Data button and the last option moves the focus to the Product ID Number textbox. There should be a modification to the ClearBoxes() method. What should be done is to clear the textbox named: txtDisplayInvoice. The method should now read: private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); txtDisplayInvoice.Clear(); }
Compile and run the program. Notice that when the program begins the four textboxes, the Enter Data, Clear Invoice and the Display Invoice buttons as well as the textbox for the displaying of the invoice are not enabled. They are grayed out. Click on New on the menu and notice that the four textboxes and the Enter Data button are now enabled and the textboxes are available for data entry. Now enter at least five invoice items. After each item is added, the Enter Data button should be clicked and the Display Invoice and the Clear Invoice buttons become activated when the first item is entered. Finally when all of the items have been entered, click the Display Invoice button. When you do, the display invoice textbox is enabled and the data appears in the textbox. Suppose that you now want to save this data to a file in secondary storage. What should be possible is to click the Save menu option and the program would permit the user to save the data. To achieve this objective, select the Designer mode to create an event handler for Save by double clicking on the menu option. Go back to the View Code mode and add to the top of the code the following statement will permit the program to use code for file IO: using System.IO;
Next return to the Designer mode and click on the form. View the Toolbox. Notice that under Dialogs categories under the Toolbox options there is a tool called: SaveFileDialog. Drag this tool to the bottom of the form and drop it. When you do, saveFileDialog1 should appear at the bottom of the form like the following:
file:///D|/1/final/BBL0107.html (5 von 12) [01.12.2007 04:49:34]
Invoices Menu
Click on the saveFileDialog1 and select Properties. Make the following changes to its properties:
Open table as spreadsheet Property
Value
Description
(Name)
saveFileDialog
This will name the control.
AddExtension
True
Setting this to True allows the dialog box to add the file extension indicated by the DefaultExt property to the name of the file specified by the user if the user omits the extension.
DefaultExt
txt
The default file extension to use if the user does not specify the extension when providing the file name.
FileName
(Leave Blank)
Permits the user to supply a name
InitialDirectory
C:\
This indicates the default location to save the file but the user has an option to change it.
OverWritePrompt
True
When this property is True, the user is warned when an attempt is made to overwrite an existing file with the same ValidateNames must be True as well.
Title
Invoices
A string that is displayed on the title bar of the dialog box.
file:///D|/1/final/BBL0107.html (6 von 12) [01.12.2007 04:49:34]
Invoices Menu
ValidateNames
True
This property indicates whether filenames are validated. It is used by some other properties such as OverWritePrompt. If this property is set to True, the dialog box also checks to verify that any filename typed in by the user contains only valid characters.
Double click on the Save menu option and change the event handler for saveInvoiceMenuItem to the following:
private void saveInvoiceMenuItem_Click(object sender, System.EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if(buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); // used to find the number of elements in each // of the arrays. int numberItems = productID.Count; // loops through each array and extracts the // elements and then writes them to the file. // for(int index=0;index
file:///D|/1/final/BBL0107.html (7 von 12) [01.12.2007 04:49:34]
Invoices Menu
txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Clear(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for Save and Print since // there is no more data contained in memory. // saveMenuItem.Enabled=false; printMenuItem.Enabled=false; } }
Compile and run the program on at least five items. After the items have been entered, display the data. Next select Save Invoice from the menu options and save the file as Invoice.txt to either the C: drive or select some other drive. It will also be possible to select some folder on that drive. Complete the saving of the data. Notice that a MessageBox appears at the end of the saving process saying that the data has been saved. After you close the MessageBox all of the textboxes are now gray as well as the three buttons. Clicking Alt-F and then Ctrl-X, notice that the program exits. To see what was done by this process, use Notepad and open the file: invoices.txt and observe the data that just appeared in the display invoice textbox is now stored to this file where each item is on a line of its own. The next menu item that needs to be activated is the Open option. Next, notice that the Toolbox has an option for this purpose. It is called: OpenFileDialog. Select this option and drop it at the bottom next to where the SaveFileDialog was placed. Click on this option and open Properties. Make the following changes:
Open table as spreadsheet Property
Value
Description
(Name)
openFileDialog
This will name the control.
AddExtension
True
Setting this to True allows the dialog box to add the file extension indicated by the DefaultExt property to the name of the file specified by the user if the user omits the extension.
CheckFileExists
True
Setting this to True forces the operating system to check if the file exists.
CheckPathExists
True
Setting this to True forces the operating system to check if the path exists.
DefaultExt
txt
The default file extension to use if the user does not specify the extension when providing the file name.
FileName
(Leave Blank)
Permits the user to supply a name
InitialDirectory
C:\
This indicates the default location to save the file but the user has an option to change it.
Title
Invoices.txt
A string that is displayed on the title bar of the dialog box.
file:///D|/1/final/BBL0107.html (8 von 12) [01.12.2007 04:49:34]
Invoices Menu
ValidateNames
True
This property indicates whether filenames are validated. It is used by some other properties such as OverWritePrompt. If this property is set to True, the dialog box also checks to verify that any filename typed in by the user contains only valid characters.
The first thing to do is to double click on the Open menu option to create an event handler. Change the openMenuItem event handler to the following: private void openMenuItem_Click(object sender, System.EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if(buttonClicked.Equals(DialogResult.OK)) { ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while(theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } }
Next the event handler for the Clear Button needs to be changed to the following: private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); file:///D|/1/final/BBL0107.html (9 von 12) [01.12.2007 04:49:34]
Invoices Menu
numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); txtID.Enabled = false; txtName.Enabled = false; txtPrice.Enabled = false; txtNumber.Enabled = false; saveMenuItem.Enabled = false; printMenuItem.Enabled = false; }
After making these modifications to the program, compile and run it. Open the file that you saved previously. After the data has been loaded, click the Display Invoice button and notice that the data loaded and is into the arrays in memory. Note: One of the options to the program that could be considered would be to create an option to edit an invoice. In this way, data could be entered and saved. Then the saved data could be loaded and edited. This option will be left for you to try. The last menu item that needs to be activated is the Print option. Open the Designer mode. Click the form. Open the Toolbar and then the select the Printing option. Notice that there are several items dealing with printing. Only two will be discussed. When you get time, experiment with the others. Drag the PrintDialog to the bottom of the form as was done with the previous controls. After the PrintDialog icon appears at the bottom of the form, click it and open Properties. Change the name to printDialog. Double click on the Print option on the menu. When you do, the event handler for this option will appear in the code. Open the View Code and move to the event handler just created. Change the event handler to the following: private void printMenuItem_Click(object sender, System.EventArgs e) { if(productID.Count!=0) { DialogResult buttonClicked = printDialog.ShowDialog(); if(buttonClicked.Equals(DialogResult.OK)) { // more code to be added here. } } else MessageBox.Show("There is no data to be printed.","Error"); }
The purpose of the conditional statement is to prevent the user from attempting to print when there is no data. Should this happen, the MessageBox would send an error message to the screen and the program would end this attempt to print. After entering the above code, return to the Designer. Again click the form and look at the Toolbar. Drag PrintDocument to the bottom of the form as with the other options. Click it and open Properties for this option. Change the name to printDocument. Clear the DocumentName property. Click on the PrintDialog control. In the Properties for this control, change the Document control to printDocument. In the Design View window, click the printDocument control. Click the Events button (has the yellow lighting bolt
file:///D|/1/final/BBL0107.html (10 von 12) [01.12.2007 04:49:34]
Invoices Menu
icon) in the Properties window as can be seen in the following graphic.
With the Events selection open, select the PrintPage event and type in printPage. Follow this with pressing the Enter key. Next, switch back to the View Code. Inside the printMenuItem event handler where the comment symbols are in the above code, place the following statement: printDocument.Print();
This statement will start the printing process on the selected printer. This line of code is calling to the method: printPage() which must now be added to the end of the program. Add the following method at the bottom of the code: private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { StringBuilder data = new StringBuilder(); StringWriter writer = new StringWriter(data); writer.WriteLine("Product ID".PadRight(20)+ "Product Name".PadRight(20)+ "Number".PadRight(15)+ "Price".PadRight(20)+ "Total".PadRight(20)+"\r\n"); decimal invoiceTotal = 0.00m; int numberItems = productID.Count; for(int index=0;index
file:///D|/1/final/BBL0107.html (11 von 12) [01.12.2007 04:49:34]
Invoices Menu
Convert.ToDecimal(itemPrice[index]))+ String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]))); invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } writer.WriteLine("\r\n" + String.Format("{0,-20}","Total:") + String.Format("{0,60:c}",invoiceTotal)); writer.Close(); float leftMargin = e.MarginBounds.Left; float topMargin = e.MarginBounds.Top; float yPos = 0; Font printFont = null; printFont = new Font("Courier New",10); yPos = topMargin + printFont.GetHeight(e.Graphics); e.HasMorePages = false; e.Graphics.DrawString(data.ToString(), printFont,Brushes.Black, leftMargin, yPos, new StringFormat()); }
Compile and run the program. Open the data that was saved previously and print it. See if the printed data looks like the data that appeared in the form. The result should be like the following three files: menuInvoices_Form1.cs menuInvoices_Form1.Designer.cs menuInvoices_Program.cs
file:///D|/1/final/BBL0107.html (12 von 12) [01.12.2007 04:49:34]
Activation of a Tool Strip
Activation of a Tool Strip Next is the consideration of a Tool Strip to complement the menu bar. This example will use the files created above in the menuInvoices program: menuInvoices_Form1.cs, menuInvoices_Form1.Designer.cs and menuInvoices_Program.cs This example will use buttons on the tool bar so download the following image files using the URLs listed below: New , Open, Save and Print. Save each of these files to the project's folder where you will be able to find them later. First click on the Form in the Form1[Designer] mode and change the Title Strip to Tool Strip Invoices. Next open the Toolbox and select the ToolStrip tool as in the graphic below and drag it to the form just below the menu (Note: Adjustments may need to be made between the ToolStrip and the labels and textboxes below):
At the bottom of the form will appear the icon for the Tool Strip as with respect to the other tools discussed above. Click on the icon and in Properties change the Name to toolStrip and remove the Text. The bottom of the form should now appear like the following:
file:///D|/1/final/BBL0108.html (1 von 5) [01.12.2007 04:49:35]
Activation of a Tool Strip
Now look at the upper left corner of the form and notice the tool strip just be below the menu strip like the following:
On the left notice the vertical line of four dots on the left. This image indicates that the user may pick up this tool strip and move it to another place on the screen. To remove this option, click on the tool strip and look at Properties. Change the GripStyle to Hidden. This change will eliminate the possiblity of the user moving the tool strip. The next step will be to insert each of the graphics listed above that were downloaded. These graphics will become icons on the toolstrip. The first one will be as in the menustrip,: New, then Open, Save and finally Print. Click on the down arrow on the left side of the toolstrip. When this is done, a drop down menu like the following should appear:
file:///D|/1/final/BBL0108.html (2 von 5) [01.12.2007 04:49:35]
Activation of a Tool Strip
Click on the Button option. What should now appear will be a blue button icon on the left side as in the following graphic:
The next step is to place the New graphic into this position. On Properties for this button, select the Image option and select the New image. Change the Name of this option to toolstripNew and the Text to New. The toolstrip should now appear as in the following:
file:///D|/1/final/BBL0108.html (3 von 5) [01.12.2007 04:49:35]
Activation of a Tool Strip
Follow this up by inserting the Open, the Save and then the Print graphics. Change their Names to toolstripOpen, toolstripSave and then toolstripPrint and the Text to Open, Save and Print respectively. The tool strip should now appear like the following:
As with the menu strip, the Save and the Print icons need to be disabled when the program begins. Therefore each of these options need to have their Enabled set to False. The btnClear_Click() event handler needs to be changed to the following: private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; btnEnter.Enabled = false; txtID.Focus(); txtID.Enabled = false; txtName.Enabled = false; txtPrice.Enabled = false; txtNumber.Enabled = false; saveMenuItem.Enabled = false; printMenuItem.Enabled = false; toolStripPrint.Enabled = false; file:///D|/1/final/BBL0108.html (4 von 5) [01.12.2007 04:49:35]
Activation of a Tool Strip
toolStripSave.Enabled = false; }
The tool strip icons need to be integrated into the event handlers: newMenuItem_Click() and openMenuItem_Click() by including the following two lines: toolStripSave.Enabled = true; toolStripPrint.Enabled = true;
And the following two lines to saveMenuItem_Click(): toolStripSave.Enabled = true; toolStripPrint.Enabled = true;
The next step is to create an event handler for each button. To accomplish this, double click each of the buttons to create the following four event handlers: private void toolStripNew_Click(object sender, EventArgs e) { } private void toolStripOpen_Click(object sender, EventArgs e) { } private void toolStripSave_Click(object sender, EventArgs e) { } private void toolStripPrint_Click(object sender, EventArgs e) { }
Into the first event handler copy the code from the event handler: newMenuItem_Click(), into the second copy the code from the event handler: openMenuItem_Click(), into the third copy the code from the event handler: saveMenuItem_Click() and finally into the fourth copy the code from the event handler: printMenuItem_Click(). After all of the steps above have been completed, compile and run the program. This time try the ToolStrip icons instead of the menu options. The program is the following files: ToolStripMenus_Form1.cs, ToolStripMenus_Form1.Designer.cs and ToolStripMenus_Program.cs.
file:///D|/1/final/BBL0108.html (5 von 5) [01.12.2007 04:49:35]
Activation of a Status Strip
Activation of a Status Strip Suppose that it would be important for the Invoice program to show the user the number of invoice items entered and the total amount of money of the invoice as the program progresses. While MessageBoxes can be used to provide the user with this information, they would not be a good solution for this specification. Instead what should be considered is the use of a status strip. A status strip appears at the bottom of the form. It may contain text messages, buttons and list boxes. This discussion will only consider placing a message at the bottom of the screen. Create a Windows project: StatusStripInvoices. Copy the files from the MenuInvoices.exe program into this project which were. That should be the following three files: menuInvoices_Form1.cs menuInvoices_Form1. Designer.cs menuInvoices_Program.cs Open the Form1.cs [Design]. Change the Text for the Form to be: Status Strip Invoices. Next select the Toolbox. Under the Menus & Toolbars is the option: StatusStrip. Select this option and drag it onto the bottom of the form.
When this is done, the control statusStrip1 will join the menu strip controls already there as in the following:
file:///D|/1/final/BBL0109.html (1 von 3) [01.12.2007 04:49:35]
Activation of a Status Strip
Click the statusStrip1 and select Properties. Change the Name to statusStrip and remove any Text . Click on the down arrow at the lower left of the form in the status bar as in the following:
Click the down arrow in the lower left corner of the screen. Select the option: StatusLabel. This will add a toolStripStatusLabel for the statusStrip. After this selection, notice that this option appears at the bottom left of the screen as in the following:
Click on this option and select Properties. Change the name to statusbarMessages. Clear the Text property. Change the Font to Ariel, Bold and 8 pt. Change to the Code View. Add the following field definition to Form1: private double InvoiceTotal = 0.00;
In the event handler: btnEnter_Click() add the following code beginning as the fifth statement:
file:///D|/1/final/BBL0109.html (2 von 3) [01.12.2007 04:49:35]
Activation of a Status Strip
statusbarMessages.ForeColor = Color.Black; InvoiceTotal += double.Parse(txtNumber.Text) * double.Parse(txtPrice.Text); statusbarMessages.Text = string.Format("Number Invoice Items: {0} Invoice Total: {1:c}", productID.Count,InvoiceTotal);
In the event handler: btnClear_Click() add the following line of code: statusbarMessages.Text = "";
This will clear the status bar of any text when there is no longer any invoice data being held in memory. Compile and run the program. After entering several items, notice the message on the status bar like the following:
Next click the Clear Invoice button and notice that the status bar text has been cleared. The result should be like the following: StatusStripMenus_Form1.cs, StatusStrip_Menus_Form1.Designer.cs and StatusStripMenus_Program.cs
file:///D|/1/final/BBL0109.html (3 von 3) [01.12.2007 04:49:35]
Cash Register
Cash Register This example will create a program that processes the entry and display of cash register data. This example will try to simulate part of the specifications of the accounting problem discussed in Lecture 1. What is different about this example from the program: Invoices.exe is that this program will be based upon the class CashRegister defined in the file: CashRegister.cs. Specification: Create an income program for small businesses that has five categories on their cash registers. The program should permit the user to enter the date and the day's income amounts for each of the five cash register categories. After the amounts have been entered, display the total income for the day so that the user can determine if the totals are correct and may make corrections if they are not. If the day's amounts are correct, permit the user to store the amounts followed by an automatic clearing of the day's entries. Once all of the days for the month have been entered, permit the user to view all of the income transactions for the month. After viewing the amounts, permit the user to clear the report from the screen. From this point the user may either run the program on another month or end the program. The form should look like the following:
The program should begin by having the user enter values into the Date first. After the Date values have been entered, the user should be able to enter the values for Category 1 to Category 5. The user should be able to move from one of these entries to the next by pressing the Tab key. After permitting the entry of the sales, the Tab key should move from Category 5 to the button View Daily Sales Total and then to Enter Daily Sales. If the Tab key is pressed again, the cursor should move to the Date again. When the user clicks the button: View Daily Sales Total, the program should total the values of the entries from Category 1 to Category 5 for the date entered and place this total into the textbox Daily Totals in dollar format. The textbox for Daily Totals should be set up so that the user is not able to enter any data into that textbox. After viewing the totals and making any corrections necessary, the user should tab to and then click the button: Enter Daily Sales. This should store the values into memory for this particular day. After this button is clicked, the Category 1 - 5 textboxes should be cleared and the cursor should return to Date. After all of the days of the month are entered, the user should be able to view the month's report by clicking the button: View Monthly Report. The report should be in seven columns. The first column should contain the numeric value of the day of the month. The next five columns should contain the day's amount for each of the respective categories. The last column should contain the day's totals. Following the information for each day should be a row that contains the totals for the month for each category and for all of the daily totals.
file:///D|/1/final/BBL0110.html (1 von 5) [01.12.2007 04:49:37]
Cash Register
The user should be able to clear the report by clicking the button Clear Report and to start data entry again. If desired, the user may click the Close Program button and the program would terminate. (Note: In addition to the description of the specifications and the sample screen above, there should also be sample data provided. Creating sample data is left to the reader.) Design: This program is to be designed to use a file from the company's component library's class: CashRegister. cs. Its UML is the following:
Coding: Create a Windows project: useCashRegister. Using the class CashRegister create the file: CashRegister.cs add the class to the project. Place the following using at the top of the code and below the other using statements to permit access to the class CashRegister: using ViewCashRegister;
Change the Font of Form1 to 10 pt Courier New so that the table will be easier to format. Make the Size, the Maximum Size and the Minimum Size of Form1 to 900,650 so that the form can not be changed by the user. Change the StartPosition to Manual so that the form will start with its upper left corner in the upper left corner of the window. Change the Text of Form1 to The Cash Register. Place the nine labels, the ten textboxes and the five buttons on the form as seen in the Specifications document. Change the labels' Text to Date:, Category 1:, Category 2:, Category 3:, Category 4:, Category 5: and Daily Totals: as indicated in the Specifications document. Change the Font of each label to Bold. Using two labels place one / in a label between Month and Day and one between Day and Year. Change the names of the Date textboxes to txtMonth, txtDay and txtYear respectively. Set their Tab Index to 1 through 3 respectively. Set the TextAlign to Right for each of these textboxes. Change the names of the category textboxes to txtCategory1, txtCategory2, txtCategory3, txtCategory4 and txtCategory5 respectively. Set their Tab Index to 4 through 8 respectively for the category textboxes. Set the TextAlign to Right for each of these textboxes. Set the name of the Daily Totals textbox to txtDailyTotals, set its ReadOnly property to True and set its TabStop property to False. Set the TextAlign to Right for the textbox. Change the name of the last text box to txtReport, set its Tab Stop to False, set its ReadOnly to True, set its Multiline to True, set its ScrollBars to Vertical, set its Location to 15, 420 and set its Size to 865,180. Set the Font to Bold and to 8pt. Change the text of the five buttons to View Daily Sales Total, Enter Daily Sales, View Monthly Report, Clear Report and Close Program respectively. Using the Font property, change the Text of each button to bold. Change their names to btnViewDaily, btnEnter, btnReport, btnClear and btnClose respectively. Set the Tab Index of these buttons to 9 through 13 respectively. Set the Tab Stop of the btnReport, btnClear and btnClose buttons to False. Switch to View Code. Add the following to the Form1 class in Form1.cs as an attribute of the class:
file:///D|/1/final/BBL0110.html (2 von 5) [01.12.2007 04:49:37]
Cash Register
private CashRegister[] dailySales = new CashRegister[31];
This attribute defines a reference to an array of 31 references to objects of the class: CashRegister. It will be used to control the storage of each of the five category sales to the 31 elements of this array. (Note that an Array was used in this example rather than an ArrayList as was done in the program Invoice.exe because in this program the number of elements is known before hand.) Add the following code to the Form1 constructor: txtMonth.Focus(); for(int day = 1;day <= 31;++day) dailySales[day-1] = new CashRegister();
The first line of code will move the cursor to the Month's textbox. The for() loop will define each of the 31 CashRegister objects referenced by the elements of the array. Define the following Form1 method that will be available to be used to clear each of the textboxes when needed: private void ClearForm() { txtMonth.Clear(); txtDay.Clear(); txtYear.Clear(); txtCategory1.Clear(); txtCategory2.Clear(); txtCategory3.Clear(); txtCategory4.Clear(); txtCategory5.Clear(); txtDailyTotals.Clear(); txtReport.Clear(); }
Double click on the View Daily Sales Total button to create an event handler. Place the following code into this event hander to be available to calculate the sum of the category sales for the current day and then to store this value into the textbox whose name is txtDailyTotals: private void btnViewDaily_Click(object sender, System.EventArgs e) { decimal theTotal = 0.00m; theTotal = Convert.ToDecimal(txtCategory1.Text); theTotal += Convert.ToDecimal(txtCategory2.Text); theTotal += Convert.ToDecimal(txtCategory3.Text); theTotal += Convert.ToDecimal(txtCategory4.Text); theTotal += Convert.ToDecimal(txtCategory5.Text); txtDailyTotals.Text = String.Format("{0:c}",theTotal); }
Double click on the Enter Daily Sales button to create an event handler. Place the following code into this event handler which stores the category sales data for the particular day into the array of CashRegister objects:
file:///D|/1/final/BBL0110.html (3 von 5) [01.12.2007 04:49:37]
Cash Register
private void btnEnter_Click(object sender, System.EventArgs e) { int day = Convert.ToInt16(txtDay.Text); dailySales[day-1].enterCategoryAmount(1, Convert.ToDecimal(txtCategory1.Text)); dailySales[day-1].enterCategoryAmount(2, Convert.ToDecimal(txtCategory2.Text)); dailySales[day-1].enterCategoryAmount(3, Convert.ToDecimal(txtCategory3.Text)); dailySales[day-1].enterCategoryAmount(4, Convert.ToDecimal(txtCategory4.Text)); dailySales[day-1].enterCategoryAmount(5, Convert.ToDecimal(txtCategory5.Text)); ClearForm(); txtMonth.Focus(); }
Double click on the View Monthly Report button to create an event handler. Place the following code into this event handler. This code is available to store the monthly report into the multiline textbox which scrolls vertically. This report will show the data for each of the days of the month: private void btnReport_Click(object sender, System.EventArgs e) { decimal dailyTotal; decimal monthlyTotal = 0.00m; decimal[] categoryTotal = new decimal[5]; for(int cat = 1;cat<=5;++cat) categoryTotal[cat-1] = 0.00m; string output = String.Format("{0}\t{1}\t\t{2}\t\t{3}\t\t{4}\t\t{5}\t\t{6}\r\n", "Day","Cat1","Cat2","Cat3","Cat4","Cat5", "Daily Total"); for(int day = 1;day <= 31;++day) { dailyTotal = 0.00m; output += String.Format("{0,2}",(day)); for(int cat = 1;cat <= 5;++cat) { dailyTotal += dailySales[day-1].returnCategoryAmount(cat); categoryTotal[cat-1] += dailySales[day-1].returnCategoryAmount(cat); output += String.Format("\t{0,11:c}", dailySales[day-1].returnCategoryAmount(cat)); } monthlyTotal += dailyTotal; output += String.Format("\t{0,11:c}",dailyTotal)+"\r\n"; } output += "\r\nTotals"; for(int cat = 1;cat <=5;++cat) output += String.Format("\t{0,11:c}",categoryTotal[cat-1]); output += String.Format("\t{0,11:c}",monthlyTotal)+"\r\n"; txtReport.Text = output; }
Double click on the Clear Report button to create an event handler. Place the following code into this event handler This button will be available to clear the report when the user no longer wants to see the data in the View Monthly Report textbox. private void btnClear_Click(object sender, System.EventArgs e) file:///D|/1/final/BBL0110.html (4 von 5) [01.12.2007 04:49:37]
Cash Register
{ ClearForm(); txtMonth.Focus(); }
Double click on the Close Program button to create an event handler. Place the following coding into this event handler: private void btnClose_Click(object sender, System.EventArgs e) { Application.Exit(); }
This button will be available to close the program when the user no longer wants to use the program. Testing: Compile and run the program several times using data you have created to see if the program functions correctly. Maintenance: What needs to be added to this program is the ability to save the data to a file, to open a data file and load the data in memory, to permit the editing of the data and to print the data stored in memory. Warning: There is a major fault with the programs in the lectures mentioned so far. There has been no code included that would handle possible user errors. For example in useCashResister.exe what would happen if non numeric characters were included in the textboxes? If this happened, errors would have occurred in the running of the program. What would have happened if an incorrect date was entered? An error could occur and maybe crash the program. These and other errors need to be handled in the code. Some discussion of that topic is included in the lecture on Exception Handling later in these notes Note: Look closely at the program code. Observe how the different pieces of the code interrelate. In particular look at the event handlers and how they relate to the form upon which they are based. Do a search in each of the files on the words: event and delegate. Did you find any? Look above in the code to see how the event handlers were coded. Notice how much the IDE coded for you. There is still a lot of coding to do, but it is a lot easier using the IDE. In this and every program created by the IDE there is a call to InitializeComponent() in the constructor. This method is used to define and set the properties of all of the controls. The properties are set based upon the values set in the code. Notice in these examples how additional code may be added after this call in the constructor. During the coding of some of these programs, watch how the program moves through the code. To observe this, under Debug select to use Step Into (F11) and Step Over (F10) instead of Start without Debugging. Watch as the program moves through each of the parts of the problem and builds the Form. The result is: CashRegister_Form1.cs, CashRegister_Form1.Designer.cs and CashRegister_Program.cs.
file:///D|/1/final/BBL0110.html (5 von 5) [01.12.2007 04:49:37]
Implementing Messageboxes
Implementing Messageboxes One of the things that you should consider when you write a Windows program is to add MessageBoxes to your code. For example if the program completed a task correctly or if some error occurred, the code could have a MessageBox to appear and to display a message. For example to have a MessageBox tell the user that some data has just been saved by the program then the following code could be included: MessageBox.Show("The program saved the data.");
See Message1_Form1.cs, Message1_Form1.Designer.cs and Message1_Program.cs that implements this version of Show() in the program Message1.exe. Or if there was a problem when trying to print: MessageBox.Show("There is no data to be printed","Error");
See Message2_Form1.cs, Message2_Form1.Designer.cs and Message2_Program.cs that implements this version of Show() in the program Message2.exe‥ Notice that both of these examples had a Title bar with a X for closing the MessageBox. In addition they both had a single button. The first example only had a message in the body of the window while the second example had not only a message in the body of the window but a message in the title bar as well. The method Show() is an overloaded static method of the class: MessageBox. There are 21 different forms of this method only the first argument is required as can be seen in the examples in this section of the lecture. There are additional arguments but they will not be discussed here. The general form is: MessageBox.Show(string theText,string theCaption, MessageBoxButtons theButtons, MessageBoxIcon theIcon, MessageBoxDefaultButton theDefault, MessageBoxOption theOptions, bool displayHelpButton);
The method Show() has as output enumerators of the enumerated data type: DialogResult whose enumerators are described in the following table:
Enumerators Abort Cancel Ignore No None OK Retry Yes
file:///D|/1/final/BBL0111.html (1 von 4) [01.12.2007 04:49:38]
Implementing Messageboxes
These enumerators could be used with statements like the following: if(MessageBox.Show(.....) == DialogResult.OK) ......
or if(MessageBox.Show(.....) == DialogResult.Ignore) ......
where the ..... means that code has been left out for these examples but must be included when used in a program. With respect to the arguments, the function Show() has 21 overloaded versions that are available each of which is briefly described in the following table:
Open table as spreadsheet Type of arguments
Explanation
String
Displays a message box which is the string.
String, String
Displays a message box with the first string and the second string appears in the title bar.
String, String, MessageBoxButtons
Displays a message box with the first string, the second string appears in the title bar and the specified buttons would appear.
String, String, MessageBoxButtons, MessageBoxIcon
Displays a message box with the first string, the second string appears in the title bar with the specified buttons and icon would appear.
String, String, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton
Displays a message box with the first string, the second string appears in the title bar with the specified buttons and icon would appear. The default button is the MessageBoxDefaultButton.
String, String, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions
Displays a message box with the first string, the second string appears in the title bar with the specified buttons and icon would appear. The default button is the MessageBoxDefaultButton and the specified options.
Form owner
Each of the above options except there is an additional argument on the left which specifies the form owner of the message box.
The following table includes the MessageBoxButtons which are data members of the class MessageBox that must be dotted with the MessageBox object: MessageBoxButtons:
Open table as spreadsheet Data Member
Description
AbortRetryIgnore
Displays the three buttons: Abort, Retry and Ignore
OK
Displays the OK button and is the default if no button is requested.
file:///D|/1/final/BBL0111.html (2 von 4) [01.12.2007 04:49:38]
Implementing Messageboxes
OKCancel
Displays the OK and the Cancel button.
RetryCancel
Displays the Retry and the Cancel button
YesNo
Displays the Yes and the No button
YesNoCancel
Displays the Yes, the No and the Cancel button
The following table includes the MessgeBoxIcon values which are data members of the class MessageBox that must be dotted with the MessageBox object: MessageBoxIcon:
Open table as spreadsheet Member Name
Description
Asterisk
The message box contains a symbol that contains a lowercase i in a circle.
Error
The message box contains a white X in a circle with a red background
Exclamation
The message box contains a symbol consisting of an exclamation point in a triangle with a yellow background.
Hand
The message box contains a symbol consisting of a white X in a circle with a red background.
Information
The messsage box contains a symbol consisting of a lowercase letter i in a circle.
None
No icon appears
Question
The message box contains a symbol consisting of a question mark in a circle.
Stop
The message box contains asymbol consisting of a white X in a circle with a red background
Warning
The message box contains a symbol consisting of an exclamation point in a triangle with a yellow background.
The following table includes the MessageDefaultButtons that are data members of the class MessageBox which must be dotted with the MessageBox object: MessageBoxDefault:
Open table as spreadsheet Data Member
Description
Button1
The first button is the default.
Button2
The second button is the default.
Button3
The third button is the default.
The following table includes the MessageBoxOptions that are data members of the class MessageBox which must be dotted with the MessageBox object: MessageBoxOptions:
Open table as spreadsheet Member Name
Description
DefaultDesktopOnly
The message box appears on the active desktop
file:///D|/1/final/BBL0111.html (3 von 4) [01.12.2007 04:49:38]
Implementing Messageboxes
RightAlign
The message box text is right-aligned
RtlReading
The messge box text is displayed right-to-left reading order
ServiceNotification
The message box appears on the active desktop
For some additional examples of programs that use MessageBox and some of its variations see the following (these programs were written using Visual Studio 2003. To use them in the 2005 version, create a Windows project and copy the code from the example into Program.cs. Next remove all of code from the files: Form1.cs and Form1.Designer.cs. ●
accountsreceivable2.cs
●
Invoices2.cs
●
useCashRegister2.cs along with the class in the file: CashRegister.cs.
file:///D|/1/final/BBL0111.html (4 von 4) [01.12.2007 04:49:38]
Validating Input Data
Validating Input Data In a previous section of this lecture, MessageBox was used to help to validate the data entered. However there are other ways one of which is to use events handlers. The only event handlers considered so far have been those which are used by buttons. However it is possible to define event handlers by using some of the tools that are built into the IDE. To see what is possible create a Windows project: Accounts Receivable. Copy the following files into that project: AccountsReceivable_Form1.cs, AccountsReceivable_Form1.Designer.cs and AccountsReceivable_Program.cs. Compile and run the program. When you do, the form should appear like the following:
When the form comes up, type in your name into the textbox to the right of the Amount label and then press either the Payment or Charge button. When you do, the program will not work properly. What needs to be done is to protect the program from user error by forcing the user to only be able to enter numeric data into the textbox associated with Amount. This may be accomplished by preventing the user from entering in any characters other than numeric characters, the period or the backspace (to be used for corrections). This will be accomplished by using the event handler, KeyPress. To implement this event handler, click on the textbox: theAmount. Open the Properties dialog. Near the top you will notice an orange lighting bolt. Click this icon. Notice that the name of textbox: theAmount appears near the top. Scroll down until you see KeyPress. When these steps are followed, the screen should show something like the graphic below:
file:///D|/1/final/BBL0112.html (1 von 5) [01.12.2007 04:49:39]
Validating Input Data
Double click KeyPress. When this is done, the IDE editor should open into Form1.cs and code like the following should appear: private void theAmount_KeyPress(object sender, KeyPressEventArgs e) { }
Inside of this event handler there needs to be code that restricts input to only numeric characters, a period or a backspace. To achieve this objective, the above event handler needs the following code included within the body of the method: private void theAmount_KeyPress(object sender, KeyPressEventArgs e) { if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46) e.Handled = true; }
Since the digits 0 to 9 have the ASCII code numbers 48 to 57, the backspace is the ASCII number 8 and the period is the ASCII number 46, the above code will only permit enter of these characters into the textbox: theAmount when the key strokes are one of those options. The Handled being set to true says to the program that if the data is outside of the acceptable data range then do not permit it to be viewed or used. Make the above changes, compile and run the program. Try to enter your name into the textbox: theAmount as you did previously. Notice that the program will not permit this to occur. Therefore this particular event handler has solved the errors caused by entering non-numeric data into a textbox which should only have numeric data. This program still has problems. If either one of the buttons: Payment or Charge is clicked before a number is
file:///D|/1/final/BBL0112.html (2 von 5) [01.12.2007 04:49:39]
Validating Input Data
entered into the textbox theAmount, then the program would crash. This problem will be handled in the discussion of the next example. The result of this example is the following: AccountsReceivable2_Form1.cs, AccountsReceivable2_Form1.Designer.cs and AccountsReceivable2_Program.cs. The next problem to be considered is when a textbox requires the entry of data but there is the possibility that the user may leave the data out. For example in a previous program: Accounts Payable the program required the entry of the Company Name. The output of the data was to a text file. In order to keep the accounts payable records accurate, the company name must be entered. The user must be prevented from leaving this data field blank. Create a windows project AccountsPayable. Copy the following files into that project: AccountsPayable_Form1.cs, AccountsPayable_Form1.Designer.cs and Accounts_Payable_Program.cs. Compile and run the program. Next should appear will be something similar to the following graphic:
Recall that this program sends the fields: Company Name and Amount Due to a text file where each field occupies a separate line in the text file. To begin the steps to prevent the user from leaving out data, enter the following into the Form1 constructor below the code that is already there: thePosting.Enabled = false; companyName.Tag = false; amountDue.Tag = false;
The first statement sets the button so that it may not be clicked. The next two statements set the Tag properties to false. These properties will be used in other parts of the program. Next add the following two event handlers into the Form1 constructor just below the previous three lines of code added: companyName.Validating += new System.ComponentModel.CancelEventHandler(textboxEmpty_Validating); amountDue.Validating += new System.ComponentModel.CancelEventHandler(textboxEmpty_Validating);
These two statements record both of the textboxes: companyName and amountDue to subscribe to the event handler: textboxEmpty_Validating. The next step is to define this event handler. Copy the following method definition at the bottom of the Form1.cs just below the other methods. file:///D|/1/final/BBL0112.html (3 von 5) [01.12.2007 04:49:39]
Validating Input Data
private void textboxEmpty_Validating(object sender,System.ComponentModel.CancelEventArgs e) { TextBox theBox = (TextBox)sender; if (theBox.Text.Length == 0) { theBox.BackColor = Color.Red; theBox.Tag = false; } else { theBox.BackColor = System.Drawing.SystemColors.Window; theBox.Tag = true; } ValidatePost(); }
Since the argument sender is an object of the class object and the event handler is designed to work with TextBoxes, the first statement above is used to typecast the argument sender to an object theBox of the class: TextBox because that is the type of argument that will really be entered. The conditional statement is designed to handle the case were the cursor enters the textbox but nothing has been typed into it. Notice that if the cursor appears in the textbox but nothing was entered (i.e. the length is 0), then the color of the textbox is set to Red. Should there have been data entered then the textbox is reset to the Windows color. The method: ValidatePost() needs to be defined next. Its definition is: private void ValidatePost() { thePosting.Enabled = (bool)(companyName.Tag) && (bool)(amountDue.Tag); thePosting.Focus(); }
The first statement will enable the button thePosting provided that data has been entered into the two textboxes correctly. The last remaining modification is to ensure that the data in the textbox theAmount is of the correct type. The event handler below is similar to the one used in the first example above. Place this event handler's definition below the definition of ValidatePost(). The event handler's definition is the following: private void amountDue_KeyPress(object sender, KeyPressEventArgs e) { if((e.KeyChar< 48||e.KeyChar>57) && e.KeyChar != 8 && e.KeyChar !=46) e.Handled=true; }
The examples above do not handle the case where after the user had entered the data correctly thereby activating the buttons, how should the program be modified to prevent the user from nullifying this protection by changing the data to a form that should no longer be acceptable. To achieve this modification at the following event handler below the last method of the program:
file:///D|/1/final/BBL0112.html (4 von 5) [01.12.2007 04:49:39]
Validating Input Data
private void textbox_Changed(object sender, System.EventArgs e) { TextBox theBox = (TextBox)sender; if (theBox.Text.Length == 0) { theBox.Tag = false; theBox.BackColor = Color.Red; } else { theBox.Tag = true; theBox.BackColor = SystemColors.Window; } ValidatePost(); }
Now that all of these modifications have been made, compile and run the program trying to see if the problems with data entry have been handled correctly. This discussion above about data validation is only an introduction to the subject. This subject should be studied further but their discussion is beyond this course. The result of this example is the following: AccountsPayable2_Form1.cs, AccountsPayable2_Form1.Designer. cs and AccountsPayable2_Program.cs.
file:///D|/1/final/BBL0112.html (5 von 5) [01.12.2007 04:49:39]
Programs with Multiple Windows
Programs with Multiple Windows The GUI programs so far have been either a single dialog program or a single-document interface (SDI) program. However, most programs are made up of multiple windows. Such a program is called a multiple-document interface (MDI). To enable a program to be an MDI, it is first necessary to set the IsMDIContainer control to True. This control permits a project to have multiple windows. The next example will create an accounting program that has several windows. To begin, create a Windows project: Accounting. Click on the form. Open Properties scroll down until you see the option IsMDIContainer property and set it to True. Properties should look like the following:
When you change the value of this property to True, the appearance of the project's form changes to the following:
file:///D|/1/final/BBL0113.html (1 von 8) [01.12.2007 04:49:40]
Programs with Multiple Windows
Change the Name and the Text of the form to Accounting. The next step is to open the Solution Explorer and to right click on Accounting. (Note: It may happen that in the code one or more of the Form1 statements will not change to Accounting and may need to be hand coded.) Next select Add and then click on Add Windows Form as seen in the following graphic:
What should appear is a dialog box like the follow:
file:///D|/1/final/BBL0113.html (2 von 8) [01.12.2007 04:49:40]
Programs with Multiple Windows
Change the name of the new form to: Sales.cs and then click Open. After the form Sales.cs has been created, create two more forms: Expenses.cs and ProfitandLoss.cs. Set the Text of Sales.cs to Sales, the Text of Expenses.cs to Expenses and the Text of ProfitandLoss.cs to Profit and Loss. Set the Size, MaximumSize and MinimumSize of each of the four forms to 600,600. Set the StartPosition to Manual. Download the image: Lighttext.gif to the folder and then make it the BackgroundImage for each of the forms. To achieve this objective, click on one of the forms and then click on Properties. It should appear like the following:
Click on the button with the three dots to the right of the BackgroundImage property. When this is done the following should appear:
file:///D|/1/final/BBL0113.html (3 von 8) [01.12.2007 04:49:40]
Programs with Multiple Windows
Select Local resource: and then click on the Import button. Select the Lighttext.gif from your download. Do this for each of the forms. Drop a label onto the main form. Change the text to Times New Roman, Bold and 12pt. Center the label on the page. Change the text to Appleton Accounting System. Next go back to Properties for Accounting.cs and drop a MainMenu onto it. Create the menu options: ●
&File
●
&Sales
●
&Expenses
●
&Profit and Loss
●
E&xit
Create a border between each of these selections. The menu should look like the following:
file:///D|/1/final/BBL0113.html (4 von 8) [01.12.2007 04:49:40]
Programs with Multiple Windows
Change the Shortcut for each of these menu options to the following: ●
Alt-F
●
Ctrl-S
●
Ctrl-E
●
Ctrl-P
●
Ctrl-X
Name each of these respective menu items the following: ●
fileMenuItem
●
salesMenuItem
●
expenseMenuItem
●
profitandLossMenuItem
●
exitMenuItem
Click on the mainMenu control at the bottom of the form. Change the name of the menu to MainMenu. Next go to each of the child forms: Sales.cs, Expenses.cs and ProfitandLoss.cs in their respective Design views. Drop a MainMenu on each of these forms. Name these menus as: SalesMenu, ExpenseMenu and ProfitandLossMenu respectively. On both the Sales.cs and the Expense.cs forms create the following options on their respective menus: ●
&File
●
&New
●
&Open
●
border (-)
●
&Save
●
border (-)
●
&Print
●
border (-)
●
E&xit
Set their respective ShortcutKey to: ●
Alt-F
●
Ctrl-N
●
Ctrl-O
●
Ctrl-S
●
Ctrl-P
file:///D|/1/final/BBL0113.html (5 von 8) [01.12.2007 04:49:40]
Programs with Multiple Windows ●
Ctrl-X
On the ProfitandLossMenu create the options: ●
&File
●
&Open
●
border (-)
●
&Print
●
border (-)
●
E&xit.
Set their Shortcut to: ●
Alt-F
●
Ctrl-O
●
Ctrl-P
●
Ctrl-X
Name the menu options for Sales.cs to the following: ●
sFileMenuItem
●
sNewMenuItem
●
sOpenMenuItem
●
sSaveMenuItem
●
sPrintMenuItem
●
sExitMenuItem
Name the menu options for Expense.cs to the following: ●
eFileMenuItem
●
eNewMenuItem
●
eOpenMenuItem
●
eSaveMenuItem
●
ePrintMenuItem
●
eExitMenuItem
Name the menu options for ProfitandLoss.cs to the following: ●
plFileMenuItem
●
plPrintMenuItem
●
plExitMenuItem
file:///D|/1/final/BBL0113.html (6 von 8) [01.12.2007 04:49:40]
Programs with Multiple Windows
The next step is to activate the menu options of the different forms. In this example only some of these menu options will be activated and it is left to you to implement all of the other options. In the Accounting.cs form double click on each of the respective menu options one at a time and set them to the following: private void salesMenuItem_Click(object sender, System.EventArgs e) { Sales newItem = new Sales(); newItem.Show(); } private void expenseMenuItem_Click(object sender, System.EventArgs e) { Expenses newItem = new Expenses(); newItem.Show(); } private void profitAndLossMenuItem_Click(object sender, System.EventArgs e) { ProfitandLoss newItem = new ProfitandLoss(); newItem.Show(); }
private void exitMenuItem_Click(object sender, System.EventArgs e) { Application.Exit(); }
After each of the first three event handlers above is clicked, a window will open for the respective sub form. The last event handler will exit the program. What is needed now would be to activate the ability to return to the main form: Accounting.cs when the Exit menu option is clicked for each of the respective subforms. To begin in the form Sales.cs double click on the Exit menu option. Then add the following code to the event handler: private void SExitMenuItem_Click(object sender, System.EventArgs e) { Close(); }
In the form Expenses.cs double click on the Exit menu option. Add the following code to the event handler: private void EExitMenuItem_Click(object sender, System.EventArgs e) { Close(); }
Finally double click on the Exit menu option of the form: ProfitandLoss.cs. Add the following code to the event handler: private void PLExitMenuItem_Click(object sender, System.EventArgs e) file:///D|/1/final/BBL0113.html (7 von 8) [01.12.2007 04:49:40]
Programs with Multiple Windows
{ Close(); }
Now compile and run the example. With the code that has been discussed, it should be possible to move from the main form: Accounting.cs to each of the sub forms: Sales.cs, Expenses.cs and ProfitandLoss.cs and then back to the main form. The remainder of the menu options could be implemented as was done in the previous section of this lecture. Note: It is recommended that the main form contain no code other than to connect to its sub forms. The program above violated this recommendation a little when an image was created for the background and a label was placed in the middle of the form. The result are the following files: Accounting.cs, Accounting.Designer.cs Expenses.cs, Expenses.Designer. cs, Sales.cs, Sales.Designer.cs, ProfitandLoss.cs, ProfitandLoss.Designer.cs, and Program.cs.
file:///D|/1/final/BBL0113.html (8 von 8) [01.12.2007 04:49:40]
The Alligators Baseball Team's Kiosk
The Alligators Baseball Team's Kiosk Specification: Create an order program to purchase team jerseys, team caps or game tickets for an athletic team the Alligators baseball team from Boca Raton, FL. The program is to be installed into a kiosk in the Town Center Mall. The user should be able to: ●
select the date of the game for which they are purchasing the tickets using a date selection box.
●
select the credit card company either Diners, Master Card or Visa for payment of the order and enter the credit card number using a combo box for the selection of the credit card companies.
●
enter the number of tickets for a specific date where the cost of each game ticket is $75.00 and the date is selected using a date selection box
●
if purchasing a team jersey, to enter the number of jerseys purchasing, the color of the jerseys which are red, green, blue and yellow and the size jersey which are: small, medium, large and extra large where the cost of each team jersey is $50.00 are to be selected from combo boxes.
●
check off if there is to be a purchase of a team cap where the cost of the team caps is $15.00.
●
select the type of shipping where the cost for shipping the tickets and the merchandise is $10.00 to have the shipment within 5 days, $5.00 if within 10 days and no charge if the shipment can arrive around 15 days after the order using radio buttons.
The program should permit the entry of the order date, the credit card company and ID, the customer's name, address, city, state and zip. The user may select to purchase game tickets by entering the number of game tickets for a specific date. The user may select to purchase team jerseys by entering the number, the size and the color of jerseys ordered. They may select to purchase a team cap. The user may select the method of sending the tickets and merchandise to the customer. There are to be three buttons: ●
One would be to check the amount of the order to display in a textbox,
●
another button to send the order to the team and
●
a third to clear all entries of the order.
When users are done, they should be able to view the total cost of the purchase and if satisfactory, to be able to submit the order. The screen should look similar to the following:
file:///D|/1/final/BBL0114.html (1 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
Design: The program should be based upon the class: People stored in the component library file: People.cs. The UML chart for this class is the following:
(Note: The pseudo code is left to the reader.) file:///D|/1/final/BBL0114.html (2 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
Coding: To begin with, create a project called: theAlligators. Since the program is to be based upon the class: People stored in the library file: People.cs. This class should be added to the project. Since the namespace for this class is: thePeople, at the top of Form1.cs should be placed the following statement after the other using statements. using thePeople;
Next select Form1 in the Designer mode and open the Properties listing. Click the Text property and type in: The Alligators Order Form. Click the Font property and change the font to: Times New Roman, Bold and 12pt. (This will make all text have this font property rather than having to change each control.) Download the graphic: Chalk.JPG to the theAlligators folder of the project. Click on the BackgroundImage for Form1 and select Chalk.JPG. Select BackColor and change it to Window. This selects the color of all controls to be that of the Window. Change the Form1's Size, Maximum Size and Minimum Size to 700, 670. Set the Start Position to Manual placing the form into the upper left corner‥ Select Build and then use Debug/Start without Debugging. When you do, you should see something like the following showing the graphic background:
Since the program is to provide the user with the opportunity to enter their name, address, city, state, zip, credit card company, credit card ID, order date, number of tickets on a particular date, the number of jerseys ordered of a size: small, medium, large or extra large and whether to purchase a team cap place the following on the screen in locations similar to the Specifications sample screen to implement these conditions: ●
16 labels
●
8 textboxes
●
2 DateTimePickers
●
4 comboboxes
●
3 buttons
●
1 groupbox 3 radio buttons inside of the group box
●
1 checkbox.
file:///D|/1/final/BBL0114.html (3 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
These controls should have the following properties (Note: In Visual Studio 2003 it was necessary to specify the size of each label. In 2005, this is done automatically by the IDE. However after the values have been entered some adjustments may be necessary to make the form more attractive.)
Open table as spreadsheet Control
Property
Value
Label1
Text
Date Ordered
Location
225, 20
Text
Customer Information
Location
20, 45
Text
Credit Card
Location
50, 75
Text
Credit Number
Location
50, 105
Text
Name
Location
50, 135
Text
Address
Location
50, 165
Text
City
Location
50, 195
Text
State
Location
50, 225
Text
Zip
Location
50, 255
Text
Number Tickets
Location
75, 290
Text
$75.00 each
Location
90, 315
Text
Team Jersey
Location
75, 390
Text
$50.00 each
Location
95, 415
Text
Game Date
Location
255, 285
Text
Color
Location
285, 380
Text
Size
Location
430, 380
Name
txtID
Location
200, 105
Tab Index
3
Label2
Label3
Label4
Label5
Label6
Label7
Label8
Label9
Label10
Label11
Label12
Label13
Label14
Label15
Label 16
Textbox1
file:///D|/1/final/BBL0114.html (4 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
Textbox2
Textbox3
Textbox4
Textbox5
Textbox6
Textbox7
Textbox8
DateTimePicker1
DateTimePicker2
ComboBox1
Size
140, 26
Name
txtName
Location
200, 135
Tab Index
4
Size
160, 26
Name
txtAddress
Location
200, 165
Tab Index
5
Size
160, 26
Name
txtCity
Location
200, 195
Tab Index
6
Size
160, 26
Name
txtZip
Location
200, 255
Tab Index
8
Size
110, 26
Name
txtNoTickets
Location
230, 310
Tab Index
9
Size
30, 26
Name
txtNoJersey
Location
215, 405
Tab Index
12
Size
30, 26
Name
txtAmount
Location
455,520
Tab Stop
False
Size
100, 26
Name
dateOrdered
Location
365,15
Tab Index
1
Size
310, 26
Name
dateGame
Location
280, 310
Tab Index
10
Size
310, 26
Name
creditCo
Items
file:///D|/1/final/BBL0114.html (5 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
Diners Master Card Visa
ComboBox2
Location
200, 75
Tab Index
2
Size
170, 27
Name
txtState
Items
AL AK AR AZ CA CO CN DE FL GA HI IA ID IN IL LA KS KY MA MI MN MO MR MS MT NC ND NE NH NJ NM NV NY OH
file:///D|/1/final/BBL0114.html (6 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
OK OR PA RI TN TX SC SD UT VA VT WA WI WV WY
ComboBox3
Location
200, 225
Tab Index
7
Size
55, 27
Name
txtColor
Items
Red Green Blue Yellow
ComboBox4
Location
260, 405
Tab Index
13
Size
120, 27
Name
txtSize
Items
Small Medium Large Extra Large
Button1
Button2
Location
390, 405
Tab Index
14
Size
150, 27
Name
btnSend
Text
Send Order
Location
30, 580
Tab Stop
False
Size
120, 23
Name
btnClear
Text
Clear Order
file:///D|/1/final/BBL0114.html (7 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
Button3
Groupbox1
RadioButton1
RadioButton2
RadioButton3
CheckBox1
Location
170, 580
Tab Stop
False
Size
130, 23
Name
btnCheck
Text
Check Amount
Location
430, 480
Tab Index
18
Size
150, 23
Name
shippingGroup
Text
Select Shipping:
Location
110, 450
Tab Index
15
Size
250, 120
Name
rBtn15
Text
15 days No Charge
Location
20,25
Tab Stop
True
Tab Index
15
Name
rBtn10
Text
10 days $5.00 Charge
Location
20,55
Tab Stop
true
Tab Index
16
Name
rBtn5
Text
5 days $10.00 Charge
Location
20,85
Tab Stop
true
Tab Index
17
Name
chkCap
Text
Select a team cap at $15.00
Location
95, 350
Tab Index
11
Size
210, 23
Compile and run the program. Try the tabbing to see if it works. Next change to View Code and add the following method to the class Form1: private void ClearForm() { // Notice that some of the entries may be cleared by // the Clear() method while others may be cleared // by using an empty string or a string with 0 as file:///D|/1/final/BBL0114.html (8 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
// a character. creditCo.Text=" "; txtID.Clear(); txtName.Clear(); txtAddress.Clear(); txtCity.Clear(); txtState.Text=" "; txtZip.Clear(); txtNoTickets.Text="0"; txtColor.Text=" "; txtSize.Text=" "; txtNoJersey.Text="0"; txtAmount.Clear(); // Notice that the checkbox and the radio button are reset by // using the Checked attribute and setting it to false. chkCap.Checked= false; rBtn5.Checked = false; rBtn10.Checked= false; rBtn15.Checked= false; }
While still in View Code scroll up to the Form1 constructor and add a call to ClearForm() by changing the constructor to the following: public Form1() { InitializeComponent(); ClearForm(); }
Return to Form1.cs[Design]. Double click on the button: Send Order. When the View Code appears with the event handler for this button, add the following code: private void btnSend_Click(object sender, System.EventArgs e) { // The following would prepare the People object to be // sent to the Alligators. It would be sent to a file // or a database. // People theCustomer = new People(); theCustomer.TheCompany = creditCo.Text; theCustomer.TheID = txtID.Text ; theCustomer.TheName = txtName.Text; theCustomer.TheAddress = txtAddress.Text; theCustomer.TheCity = txtCity.Text; theCustomer.TheState = txtState.Text; theCustomer.TheZipCode = txtZip.Text; string theOrderedDate = dateOrdered.ToString(); string theGameDate = dateGame.ToString(); // Below this point would be the preparation of the other data // to be sent to the Aligators as well either to a file or to a // database. //
file:///D|/1/final/BBL0114.html (9 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
ClearForm(); }
Notice how an object of the class People was defined and initialized using the contents of the form. This would store the data into the object and prepare it to be sent to the Alligators either by sending it to a file or to a database. Return to Form1.cs[Design]. Double click on the button: Clear Order. When the View Code appears with the event handler for this button, add the following code: private void btnClear_Click(object sender, System.EventArgs e) { ClearForm(); }
Return to Form1.cs[Design]. Double click on the button: Check Amount. When the View Code appears with the event handler for this button, add the following code: private void btnCheck_Click(object sender, System.EventArgs e) { decimal theAmount = 0.00m; theAmount += Convert.ToDecimal(txtNoTickets.Text) * 75.00m; theAmount += Convert.ToDecimal(txtNoJersey.Text) * 50.00m; if(chkCap.Checked) theAmount += 15.00m; if(rBtn5.Checked) theAmount += 10.00m; else if (rBtn10.Checked) theAmount += 5.00m; else theAmount += 0.00m; txtAmount.Text = String.Format("{0:c}", theAmount); }
In the code above, notice how the Checked attribute was used with the combo box and the radio buttons to determine which if any were checked. This should complete the program. Compile and run the program to see if it meets the specifications. Look closely at the program code. Observe how the different pieces of the code interrelate. In particular look at the event handlers and how they relate to the events upon which they are based. Look above in the code to see how the event handlers were coded there as well. Notice how much the IDE coded for you. There is still a lot of coding to do, but it is a lot easier using the IDE Maintenance: The major maintenance feature needed is to prevent runtime errors by the user entering incorrect data. What could also be added would be code which would send the order to a file or to a database when the Send Order button is clicked. Another modification could be to print a copy of the transaction to an attached printer so that the user would have a hard copy. Instead of printing, the program could ask for the user's email address and when the order was processed an email copy of the order could be sent. Maybe a copy of the order could be displayed in a MessageBox on the screen so that the user could see if the data entered was correct. What other improvements do you believe should be implemented? The result is the following files: theAlligator_Form1.cs, theAlligator_Form1.Designer.cs and theAlligator_Program.cs.
file:///D|/1/final/BBL0114.html (10 von 11) [01.12.2007 04:49:42]
The Alligators Baseball Team's Kiosk
file:///D|/1/final/BBL0114.html (11 von 11) [01.12.2007 04:49:42]
Printing Multiple Pages
Printing Multiple Pages The previously discussed Windows printing option in menuInvoices.exe only printed a single page even though the amount of data to be printed may have exceeded one page. Some programs have a need to print more that one page. This section will address this idea. While this example does not answer all questions with respect to this issue, it should at least help you to begin to understand this complex topic. I would recommend that after experimenting with this modification that you try variations on the values used in this example on different programs. First add the following using statement to the top of the program: using System.Drawing.Printing;
Next using the program: menuInvoice.exe discussed previously in the lecture, create at least 80 records. Save the data in a file, e.g. Invoice.txt and in a folder that you can find. Add the following to the following as fields for the Form1 class: private string[] theLines; private int linesPrinted;
The printPage() event handler should be changed from the previous example to the following: private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { // The following requires the user to display the data stored in RAM into the // textbox: txtDisplayInvoice. The data in this textbox will be used to fill // the string array // if(txtDisplayInvoice.Text.Equals((Object)"")) MessageBox.Show("Press Display Invoice Button First","No Data to Print"); else { float xPos = 50; float yPos = 50; Font printFont = null; printFont = new Font("Courier New", 10); yPos += printFont.GetHeight(e.Graphics); // This while loop will cause the data stored in theLines[] to output until a page // has been printed. If the amount of data exceeds the current page, the event // handler ends with a return. Although it returns, it is called again and // continues to print the data where it left off. The location of the printing is kept // by using the variable: linesPrinted. This continuation is created by the field: // HasMorePages which at first is set to true. Once all of the data (the pages) // have been printed this field is then set to false which terminates the printing // and the linesPrinted is set to 0 to permit another printing. // while (linesPrinted < productID.Count) { e.Graphics.DrawString(theLines[linesPrinted++],printFont, Brushes.Black, xPos, yPos,new StringFormat()); file:///D|/1/final/BBL0115.html (1 von 2) [01.12.2007 04:49:43]
Printing Multiple Pages
yPos += 15; if (yPos >= e.PageBounds.Height - 90) { e.HasMorePages = true; return; } } linesPrinted = 0; e.HasMorePages = false; } }
Create a BeginPrint event handler and call it: OnBeginPrint() using the PrintDocument properties. This event handler should look like the following: private void OnBeginPrint(object sender, PrintEventArgs e) { linesPrinted = 0; char[] lineEnd = { '\n' }; theLines = txtDisplayInvoice.Text.Split(lineEnd); }
This event handler takes the data that is stored in txtDisplayInvoice and splits each line into an element of the array: theLines[]. Create an EndPrint event handler and call it: OnEndPrint() using the PrintDocument properties. The event handler should look like the following: private void OnEndPrint(object sender, PrintEventArgs e) { theLines = null; }
The purpose of this event handler is to return the data stored in the array: theLines[] to the GC. Compile and run the modified program. Open the file that you created previously. Next be sure that you click the Display Invoices button before trying to print. Click the Print option on the menu. Depending on how many invoices you entered, the print out should be at least two pages. After you have run the modified program, try to change some of the values in printPage(). Notice what these changes do to the size of the margins. Now that you have a vague idea of how this works, try it on some other program which have a print option.
file:///D|/1/final/BBL0115.html (2 von 2) [01.12.2007 04:49:43]
Lecture 13 Examples
Lecture 13 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
Invoices:
This is a windows program that is an invoicing program that permits the entry of the product ID number of the product ordered, the name of that product, the number of that product ordered and finally the cost per item ordered.
●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Menu Invoices: ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Menu Graphics: ●
New
●
Open
●
Print
●
Save
Background Graphic: ●
Lighttext.gif
●
Chalk.jpg
Tool Strip Menu: ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Status Strip ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
This is a modification of the Invoice program above that contains a menu strip.
These graphics are used in a program that is a modification of the Menu Invoices program above by adding a menu strip. Note: These links do not seem to work in Adobe Acrobat format. Therefore go to the lecture13 folder and copy the files.
These graphics are used as the background for several different windows files.
This is a modification of the Menu Invoices program above by adding a tool strip.
This is a modification of the Menu Invoices above to add a status strip which shows the invoice total.
CashRegister.cs
This file contains the definition of the class: CashRegister.
People.cs
This file contains the definition of the class: People.
Cash Register:
This program processes the daily cash sales of a company with a cash register having five departments to which the sales are posted.
●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Message1 ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Message2 ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
This program demonstrates one of the 12 overloaded versions of the show() method of the class MessageBox.
This program demonstrates one of the 12 overloaded versions of the show() method of the class MessageBox.
file:///D|/1/final/BBL0116.html (1 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
Accounts Receivable ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Accounts Receivable 2 ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Accounts Payable ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Accounts Payable 2 ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Multiple Windows ●
Accounting.cs
●
Accounting.Designer.cs
●
Expenses.cs
●
Expenses.Designer.cs
●
Sales.cs
●
Sales.Designer.cs
●
ProfitandLoss.cs
●
ProfitandLoss.Designer.cs
●
Program.cs
The Alligator ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
These files simulate a Windows Accounts Receivable program.
These files create a program that is a modification of the one above and attempts to make it more robust by adding data validation.
These files simulate a Windows Accounts Payable program.
These files create a program that is a modification of the one above and attempts to make it more robust by adding data validation.
These files create a program that has multiple windows.
These files create a program with simulates a kiosk program to enable the user to purchase several different items.
Accountsreceivable2.cs
This program is a maintenance of another program and it adds MessageBox options for when the Amount text box is empty.
Invoices2.cs
This program is a maintenance of another program and it adds messageboxes to notify the user that data has not been entered.
useCashRegister2.cs
This program is a maintenance of another program and it adds messageboxes to make the program more robust.
// program_id Accounting.Designer.cs // namespace Accounting { partial class Accounting { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary>
file:///D|/1/final/BBL0116.html (2 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
/// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (Accounting)); this.MainMenu = new System.Windows.Forms.MenuStrip(); this.fileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.salesMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.expensesMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.profitAndLossToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.label1 = new System.Windows.Forms.Label(); this.MainMenu.SuspendLayout(); this.SuspendLayout(); // // MainMenu // this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileMenuItem}); this.MainMenu.Location = new System.Drawing.Point(0, 0); this.MainMenu.Name = "MainMenu"; this.MainMenu.Padding = new System.Windows.Forms.Padding(9, 3, 0, 3); this.MainMenu.Size = new System.Drawing.Size(592, 24); this.MainMenu.TabIndex = 1; this.MainMenu.Text = "menuStrip1"; // // fileMenuItem // this.fileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.salesMenuItem, this.toolStripMenuItem1, this.expensesMenuItem, this.toolStripMenuItem2, this.profitAndLossToolStripMenuItem, this.toolStripMenuItem3, this.exitToolStripMenuItem}); this.fileMenuItem.Name = "fileMenuItem"; this.fileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.fileMenuItem.Size = new System.Drawing.Size(35, 18); this.fileMenuItem.Text = "&File"; // // salesMenuItem // this.salesMenuItem.Name = "salesMenuItem"; this.salesMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.salesMenuItem.Size = new System.Drawing.Size(194, 22); this.salesMenuItem.Text = "&Sales"; this.salesMenuItem.Click += new System.EventHandler(this.salesMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(191, 6); // // expensesMenuItem //
file:///D|/1/final/BBL0116.html (3 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.expensesMenuItem.Name = "expensesMenuItem"; this.expensesMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys. E))); this.expensesMenuItem.Size = new System.Drawing.Size(194, 22); this.expensesMenuItem.Text = "&Expenses"; this.expensesMenuItem.Click += new System.EventHandler(this.expensesMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(191, 6); // // profitAndLossToolStripMenuItem // this.profitAndLossToolStripMenuItem.Name = "profitAndLossToolStripMenuItem"; this.profitAndLossToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows. Forms.Keys.P))); this.profitAndLossToolStripMenuItem.Size = new System.Drawing.Size(194, 22); this.profitAndLossToolStripMenuItem.Text = "&Profit and Loss"; this.profitAndLossToolStripMenuItem.Click += new System.EventHandler(this.profitAndLossToolStripMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(191, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms. Keys.X))); this.exitToolStripMenuItem.Size = new System.Drawing.Size(194, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Times New Roman", 20.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(203, 200); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(197, 31); this.label1.TabIndex = 3; this.label1.Text = "ASI Accounting"; // // Accounting // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 19F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(592, 572); this.Controls.Add(this.label1); this.Controls.Add(this.MainMenu); this.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.IsMdiContainer = true; this.MainMenuStrip = this.MainMenu; this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.MaximumSize = new System.Drawing.Size(600, 600); this.MinimumSize = new System.Drawing.Size(600, 600); this.Name = "Accounting"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Accounting"; this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip MainMenu;
file:///D|/1/final/BBL0116.html (4 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.ToolStripMenuItem fileMenuItem; private System.Windows.Forms.ToolStripMenuItem salesMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem expensesMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem profitAndLossToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.Label label1; } }
// program_id Accounting.cs // written_by Don Voils // date_written 9/25/2006 // description The is the main module for an MDI windows program. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Accounting { public partial class Accounting : Form { public Accounting() { InitializeComponent(); } private void salesMenuItem_Click(object sender, EventArgs e) { Sales newItem = new Sales(); newItem.Show(); } private void expensesMenuItem_Click(object sender, EventArgs e) { Expenses newItem = new Expenses(); newItem.Show(); } private void profitAndLossToolStripMenuItem_Click(object sender, EventArgs e) { ProfitandLoss newItem = new ProfitandLoss(); newItem.Show(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } } }
// program_id Expenses.Designer.cs // namespace Accounting { partial class Expenses { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null;
file:///D|/1/final/BBL0116.html (5 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
/// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (Expenses)); this.expenseMenu = new System.Windows.Forms.MenuStrip(); this.eFileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.eNewMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.eSaveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.ePrintMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.eExitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.expenseMenu.SuspendLayout(); this.SuspendLayout(); // // expenseMenu // this.expenseMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.eFileMenuItem}); this.expenseMenu.Location = new System.Drawing.Point(0, 0); this.expenseMenu.Name = "expenseMenu"; this.expenseMenu.Size = new System.Drawing.Size(592, 24); this.expenseMenu.TabIndex = 0; this.expenseMenu.Text = "menuStrip1"; // // eFileMenuItem // this.eFileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.eNewMenuItem, this.openToolStripMenuItem, this.toolStripMenuItem1, this.eSaveMenuItem, this.toolStripMenuItem2, this.ePrintMenuItem, this.toolStripMenuItem3, this.eExitMenuItem}); this.eFileMenuItem.Name = "eFileMenuItem"; this.eFileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.eFileMenuItem.Size = new System.Drawing.Size(35, 20); this.eFileMenuItem.Text = "&File"; // // eNewMenuItem // this.eNewMenuItem.Name = "eNewMenuItem"; this.eNewMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.eNewMenuItem.Size = new System.Drawing.Size(166, 22); this.eNewMenuItem.Text = "&New"; // // openToolStripMenuItem // this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms. Keys.O)));
file:///D|/1/final/BBL0116.html (6 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.openToolStripMenuItem.Size = new System.Drawing.Size(166, 22); this.openToolStripMenuItem.Text = "&Open"; // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(163, 6); // // eSaveMenuItem // this.eSaveMenuItem.Name = "eSaveMenuItem"; this.eSaveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys. Right))); this.eSaveMenuItem.Size = new System.Drawing.Size(166, 22); this.eSaveMenuItem.Text = "&Save"; // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(163, 6); // // ePrintMenuItem // this.ePrintMenuItem.Name = "ePrintMenuItem"; this.ePrintMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.ePrintMenuItem.Size = new System.Drawing.Size(166, 22); this.ePrintMenuItem.Text = "&Print"; // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(163, 6); // // eExitMenuItem // this.eExitMenuItem.Name = "eExitMenuItem"; this.eExitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.eExitMenuItem.Size = new System.Drawing.Size(166, 22); this.eExitMenuItem.Text = "E&xit"; this.eExitMenuItem.Click += new System.EventHandler(this.eExitMenuItem_Click); // // Expenses // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(592, 572); this.Controls.Add(this.expenseMenu); this.MainMenuStrip = this.expenseMenu; this.MaximumSize = new System.Drawing.Size(600, 600); this.MinimumSize = new System.Drawing.Size(600, 600); this.Name = "Expenses"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Expenses"; this.expenseMenu.ResumeLayout(false); this.expenseMenu.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip expenseMenu; private System.Windows.Forms.ToolStripMenuItem eFileMenuItem; private System.Windows.Forms.ToolStripMenuItem eNewMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem eSaveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem ePrintMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem eExitMenuItem; } }
file:///D|/1/final/BBL0116.html (7 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// program_id Expenses.cs // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Accounting { public partial class Expenses : Form { public Expenses() { InitializeComponent(); } private void eExitMenuItem_Click(object sender, EventArgs e) { Close(); } } }
// program_id ProfitandLoss.Designer.cs // namespace Accounting { partial class ProfitandLoss { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (ProfitandLoss)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.plFileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.plOpenMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.plPrintMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.plExitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 //
file:///D|/1/final/BBL0116.html (8 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.plFileMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(592, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // plFileMenuItem // this.plFileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.plOpenMenuItem, this.toolStripMenuItem2, this.plPrintMenuItem, this.toolStripMenuItem1, this.plExitMenuItem}); this.plFileMenuItem.Name = "plFileMenuItem"; this.plFileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.plFileMenuItem.Size = new System.Drawing.Size(35, 20); this.plFileMenuItem.Text = "&File"; // // plOpenMenuItem // this.plOpenMenuItem.Name = "plOpenMenuItem"; this.plOpenMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.plOpenMenuItem.Size = new System.Drawing.Size(151, 22); this.plOpenMenuItem.Text = "&Open"; // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(148, 6); // // plPrintMenuItem // this.plPrintMenuItem.Name = "plPrintMenuItem"; this.plPrintMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.plPrintMenuItem.Size = new System.Drawing.Size(151, 22); this.plPrintMenuItem.Text = "&Print"; // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(148, 6); // // plExitMenuItem // this.plExitMenuItem.Name = "plExitMenuItem"; this.plExitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.plExitMenuItem.Size = new System.Drawing.Size(151, 22); this.plExitMenuItem.Text = "E&xit"; this.plExitMenuItem.Click += new System.EventHandler(this.plExitMenuItem_Click); // // ProfitandLoss // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(592, 572); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.MaximumSize = new System.Drawing.Size(600, 600); this.MinimumSize = new System.Drawing.Size(600, 600); this.Name = "ProfitandLoss"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Profit and Loss"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1;
file:///D|/1/final/BBL0116.html (9 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.ToolStripMenuItem plFileMenuItem; private System.Windows.Forms.ToolStripMenuItem plOpenMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem plPrintMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem plExitMenuItem; } }
// program_id ProfitandLoss.cs // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Accounting { public partial class ProfitandLoss : Form { public ProfitandLoss() { InitializeComponent(); } private void plExitMenuItem_Click(object sender, EventArgs e) { Close(); } } }
// program_id Program.cs // using System; using System.Collections.Generic; using System.Windows.Forms; namespace Accounting { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Accounting()); } } }
// program_id Sales.Designer.cs // namespace Accounting { partial class Sales { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary>
file:///D|/1/final/BBL0116.html (10 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
/// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Sales)); this.salesMenu = new System.Windows.Forms.MenuStrip(); this.sFileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sNewMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sOpenMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.sSaveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.sPrintMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.sExitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.salesMenu.SuspendLayout(); this.SuspendLayout(); // // salesMenu // this.salesMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sFileMenuItem}); this.salesMenu.Location = new System.Drawing.Point(0, 0); this.salesMenu.Name = "salesMenu"; this.salesMenu.Size = new System.Drawing.Size(592, 24); this.salesMenu.TabIndex = 0; this.salesMenu.Text = "menuStrip1"; // // sFileMenuItem // this.sFileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sNewMenuItem, this.sOpenMenuItem, this.toolStripMenuItem1, this.sSaveMenuItem, this.toolStripMenuItem3, this.sPrintMenuItem, this.toolStripMenuItem4, this.sExitMenuItem}); this.sFileMenuItem.Name = "sFileMenuItem"; this.sFileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.sFileMenuItem.Size = new System.Drawing.Size(35, 20); this.sFileMenuItem.Text = "&File"; // // sNewMenuItem // this.sNewMenuItem.Name = "sNewMenuItem"; this.sNewMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.sNewMenuItem.Size = new System.Drawing.Size(151, 22); this.sNewMenuItem.Text = "&New"; // // sOpenMenuItem // this.sOpenMenuItem.Name = "sOpenMenuItem"; this.sOpenMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.sOpenMenuItem.Size = new System.Drawing.Size(151, 22); this.sOpenMenuItem.Text = "&Open"; // // toolStripMenuItem1
file:///D|/1/final/BBL0116.html (11 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(148, 6); // // sSaveMenuItem // this.sSaveMenuItem.Name = "sSaveMenuItem"; this.sSaveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.sSaveMenuItem.Size = new System.Drawing.Size(151, 22); this.sSaveMenuItem.Text = "&Save"; // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(148, 6); // // sPrintMenuItem // this.sPrintMenuItem.Name = "sPrintMenuItem"; this.sPrintMenuItem.ShortcutKeys = System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.sPrintMenuItem.Size = new System.Drawing.Size(151, 22); this.sPrintMenuItem.Text = "&Print"; // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(148, 6); // // sExitMenuItem // this.sExitMenuItem.Name = "sExitMenuItem"; this.sExitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.sExitMenuItem.Size = new System.Drawing.Size(151, 22); this.sExitMenuItem.Text = "E&xit"; this.sExitMenuItem.Click += new System.EventHandler(this.sExitMenuItem_Click); // // Sales // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(592, 572); this.Controls.Add(this.salesMenu); this.MainMenuStrip = this.salesMenu; this.MaximumSize = new System.Drawing.Size(600, 600); this.MinimumSize = new System.Drawing.Size(600, 600); this.Name = "Sales"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Sales"; this.salesMenu.ResumeLayout(false); this.salesMenu.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip salesMenu; private System.Windows.Forms.ToolStripMenuItem sFileMenuItem; private System.Windows.Forms.ToolStripMenuItem sNewMenuItem; private System.Windows.Forms.ToolStripMenuItem sOpenMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem sSaveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem sPrintMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem sExitMenuItem; } }
// program_id Sales.cs // using System;
file:///D|/1/final/BBL0116.html (12 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Accounting { public partial class Sales : Form { public Sales() { InitializeComponent(); } private void sExitMenuItem_Click(object sender, EventArgs e) { Close(); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 6/28/2006 // description This files along with Form1.cs and Program.cs create a program // that provides for the output of data from a Windows form // to a text file. In addition they protect against the entry of incorrect data // or the lack of the entry of any data. // namespace accountsPayable { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.companyName = new System.Windows.Forms.TextBox(); this.amountDue = new System.Windows.Forms.TextBox(); this.thePosting = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
file:///D|/1/final/BBL0116.html (13 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label1.Location = new System.Drawing.Point(9, 35); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(94, 13); this.label1.TabIndex = 0; this.label1.Text = "Company Name"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(9, 78); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(76, 13); this.label2.TabIndex = 1; this.label2.Text = "Amount Due"; // // companyName // this.companyName.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.companyName.Location = new System.Drawing.Point(104, 35); this.companyName.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.companyName.Name = "companyName"; this.companyName.Size = new System.Drawing.Size(108, 19); this.companyName.TabIndex = 1; // // amountDue // this.amountDue.Location = new System.Drawing.Point(104, 78); this.amountDue.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.amountDue.Name = "amountDue"; this.amountDue.Size = new System.Drawing.Size(108, 20); this.amountDue.TabIndex = 2; this.amountDue.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.amountDue_KeyPress); // // thePosting // this.thePosting.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.thePosting.Location = new System.Drawing.Point(9, 139); this.thePosting.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.thePosting.Name = "thePosting"; this.thePosting.Size = new System.Drawing.Size(56, 19); this.thePosting.TabIndex = 3; this.thePosting.Text = "Post"; this.thePosting.UseVisualStyleBackColor = true; this.thePosting.Click += new System.EventHandler(this.thePosting_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(219, 221); this.Controls.Add(this.thePosting); this.Controls.Add(this.amountDue); this.Controls.Add(this.companyName); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.MaximumSize = new System.Drawing.Size(227, 249); this.MinimumSize = new System.Drawing.Size(227, 249); this.Name = "Form1"; this.Text = "Accounts Payable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox companyName;
file:///D|/1/final/BBL0116.html (14 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.TextBox amountDue; private System.Windows.Forms.Button thePosting; } }
// program_id Form1.cs // written_by don voils // date_written 6/28/2006 // description This files along with Form1.cs and Form1.Designer.cs create a program // that provides for the output of data from a Windows form // to a text file. In addition they protect against the entry of incorrect data // or the lack of the entry of any data. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace accountsPayable { public partial class Form1 : Form { static string fileName = "accountsPayable.txt"; static FileStream writeFileStream; static StreamWriter fileWriter; public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = "0.00"; writeFileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); thePosting.Enabled = false; companyName.Tag = false; amountDue.Tag = false; companyName.Validating += new System.ComponentModel.CancelEventHandler(textboxEmpty_Validating); amountDue.Validating += new System.ComponentModel.CancelEventHandler(textboxEmpty_Validating); } private void thePosting_Click(object sender, EventArgs e) { fileWriter.WriteLine(companyName.Text); fileWriter.WriteLine(amountDue.Text); fileWriter.Flush(); companyName.Text = ""; amountDue.Text = "0.00"; companyName.Focus(); } private void textboxEmpty_Validating(object sender, System.ComponentModel.CancelEventArgs e) { TextBox theBox = (TextBox)sender; if (theBox.Text.Length == 0) { theBox.BackColor = Color.Red; theBox.Tag = false; } else { theBox.BackColor = System.Drawing.SystemColors.Window; theBox.Tag = true; } ValidatePost(); }
file:///D|/1/final/BBL0116.html (15 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private void ValidatePost() { thePosting.Enabled = (bool)(companyName.Tag) && (bool)(amountDue.Tag); thePosting.Focus(); } private void amountDue_KeyPress(object sender, KeyPressEventArgs e) { if((e.KeyChar< 48||e.KeyChar>57) && e.KeyChar != 8 && e.KeyChar !=46) e.Handled=true; } private void textbox_Changed(object sender, System.EventArgs e) { TextBox theBox = (TextBox)sender; if (theBox.Text.Length == 0) { theBox.Tag = false; theBox.BackColor = Color.Red; } else { theBox.Tag = true; theBox.BackColor = SystemColors.Window; } ValidatePost(); } } }
// program_id Program.cs // written_by don voils // date_written 6/28/2006 // description This files along with Form1.cs and Form1.Designer.cs create a program // that provides for the output of data from a Windows form // to a text file. In addition they protect against the entry of incorrect data // or the lack of the entry of any data. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace accountsPayable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 6/28/2006 // description This file along with Form1.cs and Program.cs // create a program that provides for the output of data // from a Windows form to a text file. // namespace accountsPayable { partial class Form1
file:///D|/1/final/BBL0116.html (16 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.companyName = new System.Windows.Forms.TextBox(); this.amountDue = new System.Windows.Forms.TextBox(); this.thePosting = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(12, 43); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(120, 17); this.label1.TabIndex = 0; this.label1.Text = "Company Name"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(12, 96); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 17); this.label2.TabIndex = 1; this.label2.Text = "Amount Due"; // // companyName // this.companyName.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.companyName.Location = new System.Drawing.Point(138, 43); this.companyName.Name = "companyName"; this.companyName.Size = new System.Drawing.Size(142, 22); this.companyName.TabIndex = 1; // // amountDue // this.amountDue.Location = new System.Drawing.Point(138, 96); this.amountDue.Name = "amountDue"; this.amountDue.Size = new System.Drawing.Size(142, 22); this.amountDue.TabIndex = 2; // // thePosting // this.thePosting.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0)));
file:///D|/1/final/BBL0116.html (17 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.thePosting.Location = new System.Drawing.Point(12, 171); this.thePosting.Name = "thePosting"; this.thePosting.Size = new System.Drawing.Size(75, 23); this.thePosting.TabIndex = 3; this.thePosting.Text = "Post"; this.thePosting.UseVisualStyleBackColor = true; this.thePosting.Click += new System.EventHandler(this.thePosting_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 267); this.Controls.Add(this.thePosting); this.Controls.Add(this.amountDue); this.Controls.Add(this.companyName); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.MaximumSize = new System.Drawing.Size(300, 300); this.MinimumSize = new System.Drawing.Size(300, 300); this.Name = "Form1"; this.Text = "Accounts Payable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox companyName; private System.Windows.Forms.TextBox amountDue; private System.Windows.Forms.Button thePosting; } }
// program_id Form1.cs // written_by don voils // date_written 6/28/2006 // description This file along with Form1.Designer.cs and Program.cs // create a program that provides for the output of data // from a Windows form to a text file. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace accountsPayable { public partial class Form1 : Form { static string fileName = "accountsPayable.txt"; static FileStream writeFileStream; static StreamWriter fileWriter; public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = "0.00"; writeFileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } private void thePosting_Click(object sender, EventArgs e) { fileWriter.WriteLine(companyName.Text);
file:///D|/1/final/BBL0116.html (18 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
fileWriter.WriteLine(amountDue.Text); fileWriter.Flush(); companyName.Text = ""; amountDue.Text = "0.00"; companyName.Focus(); } } }
// program_id Program.cs // written_by don voils // date_written 6/28/2006 // description This file along with Form1.cs and Form1.Designer.cs // create a program that provides for the output of data // from a Windows form to a text file. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace accountsPayable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id accountsreceivable2.cs // written_by don voils // date_written 1/2/2006 // description This program is a maintenance // of accountsreceivable.cs. It // add MessageBox options for // when the Amount text box is // empty. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace accountsReceivable { /// <summary> /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Button thePayment; private System.Windows.Forms.Button theCharge; private System.Windows.Forms.TextBox theAmount; private System.Windows.Forms.TextBox theBalance; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null;
file:///D|/1/final/BBL0116.html (19 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // theBalance.Text = "0.00"; theAmount.Text = ""; } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.thePayment = new System.Windows.Forms.Button(); this.theCharge = new System.Windows.Forms.Button(); this.theAmount = new System.Windows.Forms.TextBox(); this.theBalance = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(65, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(151, 20); this.label1.TabIndex = 0; this.label1.Text = "Accounts Receivable"; // // thePayment // this.thePayment.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.thePayment.Location = new System.Drawing.Point(60, 160); this.thePayment.Name = "thePayment"; this.thePayment.Size = new System.Drawing.Size(80, 25); this.thePayment.TabIndex = 2; this.thePayment.Text = "Payment"; this.thePayment.Click += new System.EventHandler(this.thePayment_Click); // // theCharge // this.theCharge.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.theCharge.Location = new System.Drawing.Point(170, 160); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(80, 25); this.theCharge.TabIndex = 3;
file:///D|/1/final/BBL0116.html (20 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.theCharge.Text = "Charge"; this.theCharge.Click += new System.EventHandler(this.theCharge_Click); // // theAmount // this.theAmount.Location = new System.Drawing.Point(160, 70); this.theAmount.Name = "theAmount"; this.theAmount.TabIndex = 1; this.theAmount.Text = ""; // // theBalance // this.theBalance.Location = new System.Drawing.Point(160, 105); this.theBalance.Name = "theBalance"; this.theBalance.ReadOnly = true; this.theBalance.TabIndex = 4; this.theBalance.TabStop = false; this.theBalance.Text = ""; // // label2 // this.label2.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label2.Location = new System.Drawing.Point(50, 70); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(65, 20); this.label2.TabIndex = 5; this.label2.Text = "Amount"; // // label3 // this.label3.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label3.Location = new System.Drawing.Point(50, 105); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(65, 20); this.label3.TabIndex = 6; this.label3.Text = "Balance"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 262); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.theBalance); this.Controls.Add(this.theAmount); this.Controls.Add(this.theCharge); this.Controls.Add(this.thePayment); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Accounts Receivable"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void thePayment_Click(object sender, System.EventArgs e) { if(theAmount.Text=="") MessageBox.Show("No amount was entered!!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error); else { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance += amount; theBalance.Text = String.Format("{0:n}",balance);
file:///D|/1/final/BBL0116.html (21 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
theAmount.Text=""; } } private void theCharge_Click(object sender, System.EventArgs e) { if(theAmount.Text=="") MessageBox.Show("No amount was entered!!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error); else { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance -= amount; theBalance.Text = String.Format("{0:n}",balance); theAmount.Text=""; } } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 9/14/2006 // description This file along with Form1.cs and Program.cs create // a program that permits the enter of numeric data. Then by // clicking either the Payment or the Charge button calculates // the balance depending on whether it was a Payment or a // Charge. The program has code that will protect it from // the user entering none numeric data into the textbox. // namespace accountsReceivable { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.theAmount = new System.Windows.Forms.TextBox(); this.theBalance = new System.Windows.Forms.TextBox(); this.thePayment = new System.Windows.Forms.Button(); this.theCharge = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point,
file:///D|/1/final/BBL0116.html (22 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
((byte)(0))); this.label1.Location = new System.Drawing.Point(38, 16); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(149, 19); this.label1.TabIndex = 0; this.label1.Text = "Accounts Receivable"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(33, 68); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(61, 19); this.label2.TabIndex = 1; this.label2.Text = "Amount"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(33, 102); this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(63, 19); this.label3.TabIndex = 2; this.label3.Text = "Balance"; // // theAmount // this.theAmount.Location = new System.Drawing.Point(125, 68); this.theAmount.Margin = new System.Windows.Forms.Padding(2); this.theAmount.Name = "theAmount"; this.theAmount.Size = new System.Drawing.Size(76, 20); this.theAmount.TabIndex = 1; this.theAmount.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.theAmount_KeyPress); // // theBalance // this.theBalance.Location = new System.Drawing.Point(125, 102); this.theBalance.Margin = new System.Windows.Forms.Padding(2); this.theBalance.Name = "theBalance"; this.theBalance.ReadOnly = true; this.theBalance.Size = new System.Drawing.Size(76, 20); this.theBalance.TabIndex = 4; this.theBalance.TabStop = false; // // thePayment // this.thePayment.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.thePayment.Location = new System.Drawing.Point(24, 167); this.thePayment.Margin = new System.Windows.Forms.Padding(2); this.thePayment.Name = "thePayment"; this.thePayment.Size = new System.Drawing.Size(81, 28); this.thePayment.TabIndex = 2; this.thePayment.Text = "Payment"; this.thePayment.UseVisualStyleBackColor = true; this.thePayment.Click += new System.EventHandler(this.thePayment_Click); // // theCharge // this.theCharge.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.theCharge.Location = new System.Drawing.Point(134, 167); this.theCharge.Margin = new System.Windows.Forms.Padding(2); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(66, 28); this.theCharge.TabIndex = 3; this.theCharge.Text = "Charge"; this.theCharge.UseVisualStyleBackColor = true; this.theCharge.Click += new System.EventHandler(this.theCharge_Click);
file:///D|/1/final/BBL0116.html (23 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(222, 217); this.Controls.Add(this.theCharge); this.Controls.Add(this.thePayment); this.Controls.Add(this.theBalance); this.Controls.Add(this.theAmount); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Margin = new System.Windows.Forms.Padding(2); this.MaximumSize = new System.Drawing.Size(230, 245); this.MinimumSize = new System.Drawing.Size(230, 245); this.Name = "Form1"; this.Text = "Accounts Receivable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox theAmount; private System.Windows.Forms.TextBox theBalance; private System.Windows.Forms.Button thePayment; private System.Windows.Forms.Button theCharge; } }
// program_id Form1.cs // written_by don voils // date_written 9/14/2006 // description This file along with Form1.Designer.cs and Program.cs create // a program that permits the enter of numeric data. Then by // clicking either the Payment or the Charge button calculates // the balance depending on whether it was a Payment or a // Charge. The program has code that will protect it from // the user entering none numeric data into the textbox. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace accountsReceivable { public partial class Form1 : Form { public Form1() { InitializeComponent(); theAmount.Text = " "; theBalance.Text = "0.00"; } private void thePayment_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance -= amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; } private void theCharge_Click(object sender, EventArgs e)
file:///D|/1/final/BBL0116.html (24 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance += amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; } private void theAmount_KeyPress(object sender, KeyPressEventArgs e) { if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46) e.Handled = true; } } }
// program_id Program.cs // written_by don voils // date_written 9/14/2006 // description This file along with Form1.cs and Form1.Designer.cs create // a program that permits the enter of numeric data. Then by // clicking either the Payment or the Charge button calculates // the balance depending on whether it was a Payment or a // Charge. The program has code that will protect it from // the user entering none numeric data into the textbox. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace accountsReceivable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Form1.Designer.cs // written_by Don Voils // date_written 9/14/2006 // description This file along with Form1.cs and // Program1.cs simulate a Windows Accounts // Receivable program. // namespace accountsReceivable { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); }
file:///D|/1/final/BBL0116.html (25 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.theAmount = new System.Windows.Forms.TextBox(); this.theBalance = new System.Windows.Forms.TextBox(); this.thePayment = new System.Windows.Forms.Button(); this.theCharge = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(38, 16); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(149, 19); this.label1.TabIndex = 0; this.label1.Text = "Accounts Receivable"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(33, 68); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(61, 19); this.label2.TabIndex = 1; this.label2.Text = "Amount"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(33, 102); this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(63, 19); this.label3.TabIndex = 2; this.label3.Text = "Balance"; // // theAmount // this.theAmount.Location = new System.Drawing.Point(125, 68); this.theAmount.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.theAmount.Name = "theAmount"; this.theAmount.Size = new System.Drawing.Size(76, 20); this.theAmount.TabIndex = 1; // // theBalance // this.theBalance.Location = new System.Drawing.Point(125, 102); this.theBalance.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.theBalance.Name = "theBalance"; this.theBalance.ReadOnly = true; this.theBalance.Size = new System.Drawing.Size(76, 20); this.theBalance.TabIndex = 4; this.theBalance.TabStop = false; // // thePayment
file:///D|/1/final/BBL0116.html (26 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.thePayment.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.thePayment.Location = new System.Drawing.Point(24, 167); this.thePayment.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.thePayment.Name = "thePayment"; this.thePayment.Size = new System.Drawing.Size(81, 28); this.thePayment.TabIndex = 2; this.thePayment.Text = "Payment"; this.thePayment.UseVisualStyleBackColor = true; this.thePayment.Click += new System.EventHandler(this.thePayment_Click); // // theCharge // this.theCharge.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.theCharge.Location = new System.Drawing.Point(134, 167); this.theCharge.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(66, 28); this.theCharge.TabIndex = 3; this.theCharge.Text = "Charge"; this.theCharge.UseVisualStyleBackColor = true; this.theCharge.Click += new System.EventHandler(this.theCharge_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(222, 217); this.Controls.Add(this.theCharge); this.Controls.Add(this.thePayment); this.Controls.Add(this.theBalance); this.Controls.Add(this.theAmount); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.MaximumSize = new System.Drawing.Size(230, 245); this.MinimumSize = new System.Drawing.Size(230, 245); this.Name = "Form1"; this.Text = "Accounts Receivable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox theAmount; private System.Windows.Forms.TextBox theBalance; private System.Windows.Forms.Button thePayment; private System.Windows.Forms.Button theCharge; } }
// program_id Form1.cs // written_by Don Voils // date_written 9/14/2006 // description This file along with Form1.Designer.cs and // Program1.cs simulate a Windows Accounts // Receivable program. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;
file:///D|/1/final/BBL0116.html (27 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
namespace accountsReceivable { public partial class Form1 : Form { public Form1() { InitializeComponent(); theAmount.Text = " "; theBalance.Text = "0.00"; } private void thePayment_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance -= amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; } private void theCharge_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance += amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; } } }
// program_id Program.cs // written_by Don Voils // date_written 9/14/2006 // description This file along with Form1.cs and // Form1.Designer.cs simulate a Windows // Accounts Receivable program. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace accountsReceivable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id CashRegister.cs // written_by don voils // date_written 4/15/2003 // description This file contains the definition of the // class: CashRegister contained in the // namespace: viewCashRegister. // using System; namespace ViewCashRegister { public class CashRegister
file:///D|/1/final/BBL0116.html (28 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ private decimal [] dailySales = new decimal[5]; public CashRegister() { for(int index = 0; index <5; ++index) { dailySales[index] = 0.00m; } } public void EnterSales() { for(int index=0;index<5;++index) { Console.Write("What does the cash register have in category {0}? ",index+1); dailySales[index] = decimal.Parse(Console.ReadLine()); } } public void enterCategoryAmount(int index,decimal theAmount) { dailySales[index-1] = theAmount; } public decimal returnCategoryAmount(int category) { return dailySales[category-1]; } public decimal totalDailyTotal() { decimal totalAmount = 0; for(int index = 0 ; index<5;++index) totalAmount += dailySales[index]; return totalAmount; } }
}
// program_id Form1.Designer.cs // written_by don voils // date_written 10/14/2006 // description This along with Form1.cs and Program.cs create // a program that processes the daily cash sales of a company // with a cash register having five departments to which the // sales are posted. // namespace useCashRegister { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); }
file:///D|/1/final/BBL0116.html (29 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
#region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.txtMonth = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.txtDay = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.txtYear = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.txtCategory1 = new System.Windows.Forms.TextBox(); this.txtCategory2 = new System.Windows.Forms.TextBox(); this.txtCategory3 = new System.Windows.Forms.TextBox(); this.txtCategory4 = new System.Windows.Forms.TextBox(); this.txtCategory5 = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.txtDailyTotals = new System.Windows.Forms.TextBox(); this.btnClose = new System.Windows.Forms.Button(); this.btnViewDaily = new System.Windows.Forms.Button(); this.btnEnter = new System.Windows.Forms.Button(); this.btnReport = new System.Windows.Forms.Button(); this.txtReport = new System.Windows.Forms.TextBox(); this.btnClear = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.Location = new System.Drawing.Point(350, 40); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(59, 20); this.label1.TabIndex = 0; this.label1.Text = "Date:"; // // txtMonth // this.txtMonth.Location = new System.Drawing.Point(420, 40); this.txtMonth.Name = "txtMonth"; this.txtMonth.Size = new System.Drawing.Size(30, 27); this.txtMonth.TabIndex = 1; this.txtMonth.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.Location = new System.Drawing.Point(452, 42); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(19, 20); this.label2.TabIndex = 2; this.label2.Text = "/"; // // txtDay // this.txtDay.Location = new System.Drawing.Point(480, 40); this.txtDay.Name = "txtDay"; this.txtDay.Size = new System.Drawing.Size(30, 27); this.txtDay.TabIndex = 2; this.txtDay.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label3 // this.label3.AutoSize = true;
file:///D|/1/final/BBL0116.html (30 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label3.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label3.Location = new System.Drawing.Point(514, 40); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(19, 20); this.label3.TabIndex = 4; this.label3.Text = "/"; // // txtYear // this.txtYear.Location = new System.Drawing.Point(540, 40); this.txtYear.Name = "txtYear"; this.txtYear.Size = new System.Drawing.Size(60, 27); this.txtYear.TabIndex = 3; this.txtYear.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.Location = new System.Drawing.Point(80, 110); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(119, 20); this.label4.TabIndex = 6; this.label4.Text = "Category 1:"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label5.Location = new System.Drawing.Point(80, 150); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(119, 20); this.label5.TabIndex = 7; this.label5.Text = "Category 2:"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label6.Location = new System.Drawing.Point(80, 190); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(119, 20); this.label6.TabIndex = 8; this.label6.Text = "Category 3:"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label7.Location = new System.Drawing.Point(80, 230); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(119, 20); this.label7.TabIndex = 9; this.label7.Text = "Category 4:"; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label8.Location = new System.Drawing.Point(80, 270); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(119, 20); this.label8.TabIndex = 10; this.label8.Text = "Category 5:"; // // txtCategory1 // this.txtCategory1.Location = new System.Drawing.Point(220, 110); this.txtCategory1.Name = "txtCategory1"; this.txtCategory1.Size = new System.Drawing.Size(100, 27);
file:///D|/1/final/BBL0116.html (31 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtCategory1.TabIndex = 4; this.txtCategory1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtCategory2 // this.txtCategory2.Location = new System.Drawing.Point(220, 150); this.txtCategory2.Name = "txtCategory2"; this.txtCategory2.Size = new System.Drawing.Size(100, 27); this.txtCategory2.TabIndex = 5; this.txtCategory2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtCategory3 // this.txtCategory3.Location = new System.Drawing.Point(220, 190); this.txtCategory3.Name = "txtCategory3"; this.txtCategory3.Size = new System.Drawing.Size(100, 27); this.txtCategory3.TabIndex = 6; this.txtCategory3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtCategory4 // this.txtCategory4.Location = new System.Drawing.Point(220, 230); this.txtCategory4.Name = "txtCategory4"; this.txtCategory4.Size = new System.Drawing.Size(100, 27); this.txtCategory4.TabIndex = 7; this.txtCategory4.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtCategory5 // this.txtCategory5.Location = new System.Drawing.Point(220, 270); this.txtCategory5.Name = "txtCategory5"; this.txtCategory5.Size = new System.Drawing.Size(100, 27); this.txtCategory5.TabIndex = 8; this.txtCategory5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label9.Location = new System.Drawing.Point(60, 321); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(139, 20); this.label9.TabIndex = 11; this.label9.Text = "Daily Totals:"; // // txtDailyTotals // this.txtDailyTotals.Location = new System.Drawing.Point(205, 310); this.txtDailyTotals.Name = "txtDailyTotals"; this.txtDailyTotals.ReadOnly = true; this.txtDailyTotals.Size = new System.Drawing.Size(115, 27); this.txtDailyTotals.TabIndex = 12; this.txtDailyTotals.TabStop = false; this.txtDailyTotals.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // btnClose // this.btnClose.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.btnClose.Location = new System.Drawing.Point(610, 100); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(180, 25); this.btnClose.TabIndex = 13; this.btnClose.TabStop = false; this.btnClose.Text = "Close Program"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnViewDaily // this.btnViewDaily.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnViewDaily.Location = new System.Drawing.Point(350, 310); this.btnViewDaily.Name = "btnViewDaily";
file:///D|/1/final/BBL0116.html (32 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.btnViewDaily.Size = new System.Drawing.Size(250, 25); this.btnViewDaily.TabIndex = 9; this.btnViewDaily.Text = "View Daily Sales Total"; this.btnViewDaily.UseVisualStyleBackColor = true; this.btnViewDaily.Click += new System.EventHandler(this.btnViewDaily_Click); // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.btnEnter.Location = new System.Drawing.Point(350, 370); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(250, 25); this.btnEnter.TabIndex = 10; this.btnEnter.Text = "Enter Daily Sales"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnReport // this.btnReport.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnReport.Location = new System.Drawing.Point(65, 370); this.btnReport.Name = "btnReport"; this.btnReport.Size = new System.Drawing.Size(230, 25); this.btnReport.TabIndex = 11; this.btnReport.TabStop = false; this.btnReport.Text = "View Monthly Report"; this.btnReport.UseVisualStyleBackColor = true; this.btnReport.Click += new System.EventHandler(this.btnReport_Click); // // txtReport // this.txtReport.Font = new System.Drawing.Font("Courier New", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.txtReport.Location = new System.Drawing.Point(15, 420); this.txtReport.Multiline = true; this.txtReport.Name = "txtReport"; this.txtReport.ReadOnly = true; this.txtReport.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtReport.Size = new System.Drawing.Size(860, 180); this.txtReport.TabIndex = 17; this.txtReport.TabStop = false; // // btnClear // this.btnClear.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.btnClear.Location = new System.Drawing.Point(610, 170); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(180, 25); this.btnClear.TabIndex = 12; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Report"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(892, 617); this.Controls.Add(this.btnClear); this.Controls.Add(this.txtReport); this.Controls.Add(this.btnReport); this.Controls.Add(this.btnEnter); this.Controls.Add(this.btnViewDaily); this.Controls.Add(this.btnClose); this.Controls.Add(this.txtDailyTotals); this.Controls.Add(this.label9); this.Controls.Add(this.txtCategory5); this.Controls.Add(this.txtCategory4); this.Controls.Add(this.txtCategory3); this.Controls.Add(this.txtCategory2); this.Controls.Add(this.txtCategory1);
file:///D|/1/final/BBL0116.html (33 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.txtYear); this.Controls.Add(this.label3); this.Controls.Add(this.txtDay); this.Controls.Add(this.label2); this.Controls.Add(this.txtMonth); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.MaximumSize = new System.Drawing.Size(900, 650); this.MinimumSize = new System.Drawing.Size(900, 650); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "The Cash Register"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtMonth; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtDay; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtYear; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox txtCategory1; private System.Windows.Forms.TextBox txtCategory2; private System.Windows.Forms.TextBox txtCategory3; private System.Windows.Forms.TextBox txtCategory4; private System.Windows.Forms.TextBox txtCategory5; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox txtDailyTotals; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Button btnViewDaily; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnReport; private System.Windows.Forms.TextBox txtReport; private System.Windows.Forms.Button btnClear; } }
// program_id Form1.cs // written_by don voils // date_written 10/14/2006 // description This along with Form1.Designer.cs and Program.cs create // a program that processes the daily cash sales of a company // with a cash register having five departments to which the // sales are posted. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using ViewCashRegister; namespace useCashRegister { public partial class Form1 : Form { private CashRegister[] dailySales = new CashRegister[31];
file:///D|/1/final/BBL0116.html (34 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
public Form1() { InitializeComponent(); txtMonth.Focus(); for (int day = 1; day <= 31; ++day) dailySales[day - 1] = new CashRegister();
} private void ClearForm() { txtMonth.Clear(); txtDay.Clear(); txtYear.Clear(); txtCategory1.Clear(); txtCategory2.Clear(); txtCategory3.Clear(); txtCategory4.Clear(); txtCategory5.Clear(); txtDailyTotals.Clear(); txtReport.Clear(); } private void btnViewDaily_Click(object sender, EventArgs e) { decimal theTotal = 0.00m; theTotal = Convert.ToDecimal(txtCategory1.Text); theTotal += Convert.ToDecimal(txtCategory2.Text); theTotal += Convert.ToDecimal(txtCategory3.Text); theTotal += Convert.ToDecimal(txtCategory4.Text); theTotal += Convert.ToDecimal(txtCategory5.Text); txtDailyTotals.Text = String.Format("{0:c}", theTotal); } private void btnEnter_Click(object sender, EventArgs e) { int day = Convert.ToInt16(txtDay.Text); dailySales[day - 1].enterCategoryAmount(1, Convert.ToDecimal(txtCategory1.Text)); dailySales[day - 1].enterCategoryAmount(2, Convert.ToDecimal(txtCategory2.Text)); dailySales[day - 1].enterCategoryAmount(3, Convert.ToDecimal(txtCategory3.Text)); dailySales[day - 1].enterCategoryAmount(4, Convert.ToDecimal(txtCategory4.Text)); dailySales[day - 1].enterCategoryAmount(5, Convert.ToDecimal(txtCategory5.Text)); ClearForm(); txtMonth.Focus(); } private void btnReport_Click(object sender, EventArgs e) { decimal dailyTotal; decimal monthlyTotal = 0.00m; decimal[] categoryTotal = new decimal[5]; for (int cat = 1; cat <= 5; ++cat) categoryTotal[cat - 1] = 0.00m; string output = String.Format("{0}\t{1}\t\t{2}\t\t{3}\t\t{4}\t\t{5}\t\t{6}\r\n", "Day", "Cat1", "Cat2", "Cat3", "Cat4", "Cat5", "Daily Total"); for (int day = 1; day <= 31; ++day) { dailyTotal = 0.00m; output += String.Format("{0,2}", (day)); for (int cat = 1; cat <= 5; ++cat) { dailyTotal += dailySales[day - 1].returnCategoryAmount(cat); categoryTotal[cat - 1] += dailySales[day - 1].returnCategoryAmount(cat); output += String.Format("\t{0,11:c}", dailySales[day - 1].returnCategoryAmount(cat)); }
file:///D|/1/final/BBL0116.html (35 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
monthlyTotal += dailyTotal; output += String.Format("\t{0,11:c}", dailyTotal) + "\r\n"; } output += "\r\nTotals"; for (int cat = 1; cat <= 5; ++cat) output += String.Format("\t{0,11:c}", categoryTotal[cat - 1]); output += String.Format("\t{0,11:c}", monthlyTotal) + "\r\n"; txtReport.Text = output; } private void btnClear_Click(object sender, EventArgs e) { ClearForm(); txtMonth.Focus(); } private void btnClose_Click(object sender, EventArgs e) { Application.Exit(); } } }
// program_id Program.cs // written_by don voils // date_written 10/14/2006 // description This along with Form1.Designer.cs and Form1.cs create // a program that processes the daily cash sales of a company // with a cash register having five departments to which the // sales are posted. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace useCashRegister { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Form1.Design.cs // written_by don voils // date_written 8/3/2006 // description This file along with Form1.cs // and Program.cs create a program // to hand expenses. // namespace Accounting { partial class Expenses { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false.
file:///D|/1/final/BBL0116.html (36 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (Expenses)); this.expenseMenu = new System.Windows.Forms.MenuStrip(); this.eFileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.eNewMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.eSaveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.ePrintMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.eExitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.expenseMenu.SuspendLayout(); this.SuspendLayout(); // // expenseMenu // this.expenseMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.eFileMenuItem}); this.expenseMenu.Location = new System.Drawing.Point(0, 0); this.expenseMenu.Name = "expenseMenu"; this.expenseMenu.Size = new System.Drawing.Size(592, 24); this.expenseMenu.TabIndex = 0; this.expenseMenu.Text = "menuStrip1"; // // eFileMenuItem // this.eFileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.eNewMenuItem, this.openToolStripMenuItem, this.toolStripMenuItem1, this.eSaveMenuItem, this.toolStripMenuItem2, this.ePrintMenuItem, this.toolStripMenuItem3, this.eExitMenuItem}); this.eFileMenuItem.Name = "eFileMenuItem"; this.eFileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.eFileMenuItem.Size = new System.Drawing.Size(35, 20); this.eFileMenuItem.Text = "&File"; // // eNewMenuItem // this.eNewMenuItem.Name = "eNewMenuItem"; this.eNewMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.eNewMenuItem.Size = new System.Drawing.Size(166, 22); this.eNewMenuItem.Text = "&New"; // // openToolStripMenuItem // this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms. Keys.O))); this.openToolStripMenuItem.Size = new System.Drawing.Size(166, 22); this.openToolStripMenuItem.Text = "&Open"; // // toolStripMenuItem1 //
file:///D|/1/final/BBL0116.html (37 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(163, 6); // // eSaveMenuItem // this.eSaveMenuItem.Name = "eSaveMenuItem"; this.eSaveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys. Right))); this.eSaveMenuItem.Size = new System.Drawing.Size(166, 22); this.eSaveMenuItem.Text = "&Save"; // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(163, 6); // // ePrintMenuItem // this.ePrintMenuItem.Name = "ePrintMenuItem"; this.ePrintMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.ePrintMenuItem.Size = new System.Drawing.Size(166, 22); this.ePrintMenuItem.Text = "&Print"; // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(163, 6); // // eExitMenuItem // this.eExitMenuItem.Name = "eExitMenuItem"; this.eExitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.eExitMenuItem.Size = new System.Drawing.Size(166, 22); this.eExitMenuItem.Text = "E&xit"; this.eExitMenuItem.Click += new System.EventHandler(this.eExitMenuItem_Click); // // Expenses // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(592, 572); this.Controls.Add(this.expenseMenu); this.MainMenuStrip = this.expenseMenu; this.MaximumSize = new System.Drawing.Size(600, 600); this.MinimumSize = new System.Drawing.Size(600, 600); this.Name = "Expenses"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Expenses"; this.expenseMenu.ResumeLayout(false); this.expenseMenu.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip expenseMenu; private System.Windows.Forms.ToolStripMenuItem eFileMenuItem; private System.Windows.Forms.ToolStripMenuItem eNewMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem eSaveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem ePrintMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem eExitMenuItem; } }
// program_id Form1.cs // written_by don voils // date_written 8/3/2006
file:///D|/1/final/BBL0116.html (38 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// description This file along with Form1.Design.cs // and Program.cs create a program // to hand expenses. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace Accounting { /// <summary> /// Summary description for Expenses. /// public class Expenses : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu ExpenseMenu; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem menuItem7; private System.Windows.Forms.MenuItem EFileMenuItem; private System.Windows.Forms.MenuItem ENewMenuItem; private System.Windows.Forms.MenuItem EOpenMenuItem; private System.Windows.Forms.MenuItem ESaveMenuItem; private System.Windows.Forms.MenuItem EPrintMenuItem; private System.Windows.Forms.MenuItem EExitMenuItem; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Expenses() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.ExpenseMenu = new System.Windows.Forms.MainMenu(); this.EFileMenuItem = new System.Windows.Forms.MenuItem(); this.ENewMenuItem = new System.Windows.Forms.MenuItem(); this.EOpenMenuItem = new System.Windows.Forms.MenuItem(); this.ESaveMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.EPrintMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem7 = new System.Windows.Forms.MenuItem(); this.EExitMenuItem = new System.Windows.Forms.MenuItem(); //
file:///D|/1/final/BBL0116.html (39 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// ExpenseMenu // this.ExpenseMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.EFileMenuItem}); // // EFileMenuItem // this.EFileMenuItem.Index = 0; this.EFileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.ENewMenuItem, this.EOpenMenuItem, this.ESaveMenuItem, this.menuItem5, this.EPrintMenuItem, this.menuItem7, this.EExitMenuItem}); this.EFileMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF; this.EFileMenuItem.Text = "&File"; // // ENewMenuItem // this.ENewMenuItem.Index = 0; this.ENewMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlN; this.ENewMenuItem.Text = "&New"; // // EOpenMenuItem // this.EOpenMenuItem.Index = 1; this.EOpenMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlO; this.EOpenMenuItem.Text = "&Open"; // // ESaveMenuItem // this.ESaveMenuItem.Index = 2; this.ESaveMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlS; this.ESaveMenuItem.Text = "&Save"; // // menuItem5 // this.menuItem5.Index = 3; this.menuItem5.Text = "-"; // // EPrintMenuItem // this.EPrintMenuItem.Index = 4; this.EPrintMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlP; this.EPrintMenuItem.Text = "&Print"; // // menuItem7 // this.menuItem7.Index = 5; this.menuItem7.Text = "-"; // // EExitMenuItem // this.EExitMenuItem.Index = 6; this.EExitMenuItem.Shortcut = System.Windows.Forms.Shortcut.AltF4; this.EExitMenuItem.Text = "E&xit"; this.EExitMenuItem.Click += new System.EventHandler(this.EExitMenuItem_Click); // // Expenses // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(592, 541); this.Menu = this.ExpenseMenu; this.Name = "Expenses"; this.Text = "Expenses"; } #endregion private void EExitMenuItem_Click(object sender, System.EventArgs e) { Close(); } }
file:///D|/1/final/BBL0116.html (40 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
}
// program_id Program.cs // written_by don voils // date_written 8/3/2006 // description This file along with Form1.cs and // Form1.Design.cs create a program // to hand expenses. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Accounting { public partial class Expenses : Form { public Expenses() { InitializeComponent(); } private void eExitMenuItem_Click(object sender, EventArgs e) { Close(); } } }
// program_id Form1.cs // written_by don voils // date_written 1/20/2006 // description This file contains the definition of a form // that is to be used with the forms: // Sales.cs, Expenses.cs and ProfitandLoss.cs. // This form is the master form for the application // Accounting.cs using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace Accounting { /// <summary> /// Summary description for Form1. /// public class Accounting : System.Windows.Forms.Form { private System.Windows.Forms.MenuItem menuItem3; private System.Windows.Forms.MainMenu MainMenu; private System.Windows.Forms.MenuItem FileMenuItem; private System.Windows.Forms.MenuItem SalesMenuItem; private System.Windows.Forms.MenuItem ExpenseMenuItem; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem ProfitandLossMenuItem; private System.Windows.Forms.MenuItem menuItem7; private System.Windows.Forms.MenuItem ExitMenuItem; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Accounting() { //
file:///D|/1/final/BBL0116.html (41 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.MainMenu = new System.Windows.Forms.MainMenu(); this.FileMenuItem = new System.Windows.Forms.MenuItem(); this.SalesMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.ExpenseMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.ProfitandLossMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem7 = new System.Windows.Forms.MenuItem(); this.ExitMenuItem = new System.Windows.Forms.MenuItem(); // // MainMenu // this.MainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.FileMenuItem}); // // FileMenuItem // this.FileMenuItem.Index = 0; this.FileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.SalesMenuItem, this.menuItem3, this.ExpenseMenuItem, this.menuItem5, this.ProfitandLossMenuItem, this.menuItem7, this.ExitMenuItem}); this.FileMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF; this.FileMenuItem.Text = "&File"; // // SalesMenuItem // this.SalesMenuItem.Index = 0; this.SalesMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlS; this.SalesMenuItem.Text = "&Sales"; this.SalesMenuItem.Click += new System.EventHandler(this.SalesMenuItem_Click); // // menuItem3 // this.menuItem3.Index = 1; this.menuItem3.Text = "-"; // // ExpenseMenuItem // this.ExpenseMenuItem.Index = 2;
file:///D|/1/final/BBL0116.html (42 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.ExpenseMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlE; this.ExpenseMenuItem.Text = "&Expenses"; this.ExpenseMenuItem.Click += new System.EventHandler(this.menuItem4_Click); // // menuItem5 // this.menuItem5.Index = 3; this.menuItem5.Text = "-"; // // ProfitandLossMenuItem // this.ProfitandLossMenuItem.Index = 4; this.ProfitandLossMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlP; this.ProfitandLossMenuItem.Text = "&Profit and Loss"; this.ProfitandLossMenuItem.Click += new System.EventHandler(this.ProfitandLossMenuItem_Click); // // menuItem7 // this.menuItem7.Index = 5; this.menuItem7.Text = "-"; // // ExitMenuItem // this.ExitMenuItem.Index = 6; this.ExitMenuItem.Shortcut = System.Windows.Forms.Shortcut.AltF4; this.ExitMenuItem.Text = "E&xit"; this.ExitMenuItem.Click += new System.EventHandler(this.ExitMenuItem_Click); // // Accounting // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(592, 541); this.IsMdiContainer = true; this.Menu = this.MainMenu; this.Name = "Accounting"; this.Text = "Accounting"; } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Accounting()); } private void menuItem4_Click(object sender, System.EventArgs e) { Expenses newItem = new Expenses(); newItem.Show(); } private void SalesMenuItem_Click(object sender, System.EventArgs e) { Sales newItem = new Sales(); newItem.Show(); } private void ProfitandLossMenuItem_Click(object sender, System.EventArgs e) { ProfitandLoss newItem = new ProfitandLoss(); newItem.Show(); } private void ExitMenuItem_Click(object sender, System.EventArgs e) { Application.Exit(); } } }
file:///D|/1/final/BBL0116.html (43 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// program_id Invoices2.cs // written_by don voils // date_written 4/5/2003 // description This program is a maintenance program // on Invoices.cs. It adds messageboxes // to notify the user that data has not // been entered. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace invoices { /// <summary> /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { // Definition of the arrays for each of the // invoice items. // private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList();
private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnDisplay; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose(disposing);
file:///D|/1/final/BBL0116.html (44 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
} #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnDisplay = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(16, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(104, 23); this.label1.TabIndex = 0; this.label1.Text = "Product ID Number"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label2.Location = new System.Drawing.Point(16, 48); this.label2.Name = "label2"; this.label2.TabIndex = 1; this.label2.Text = "Product Name"; // // label3 // this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label3.Location = new System.Drawing.Point(376, 48); this.label3.Name = "label3"; this.label3.TabIndex = 2; this.label3.Text = "Price per Item"; // // label4 // this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label4.Location = new System.Drawing.Point(336, 16); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(152, 23); this.label4.TabIndex = 3; this.label4.Text = "Number of Items Purchased"; // // txtID // this.txtID.Location = new System.Drawing.Point(136, 16); this.txtID.Name = "txtID"; this.txtID.TabIndex = 1; this.txtID.Text = ""; // // txtName
file:///D|/1/final/BBL0116.html (45 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.txtName.Location = new System.Drawing.Point(136, 48); this.txtName.Name = "txtName"; this.txtName.TabIndex = 2; this.txtName.Text = ""; // // txtNumber // this.txtNumber.Location = new System.Drawing.Point(504, 16); this.txtNumber.Name = "txtNumber"; this.txtNumber.TabIndex = 3; this.txtNumber.Text = ""; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(504, 48); this.txtPrice.Name = "txtPrice"; this.txtPrice.TabIndex = 4; this.txtPrice.Text = ""; // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.btnEnter.Location = new System.Drawing.Point(256, 80); this.btnEnter.Name = "btnEnter"; this.++.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(16, 120); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(688, 128); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; this.txtDisplayInvoice.Text = ""; // // btnDisplay // this.btnDisplay.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.btnDisplay.Location = new System.Drawing.Point(480, 88); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(112, 23); this.btnDisplay.TabIndex = 9; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(8, 15); this.ClientSize = new System.Drawing.Size(712, 266); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,
file:///D|/1/final/BBL0116.html (46 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
((System.Byte)(0))); this.Name = "Form1"; this.Text = "Invoices"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { txtID.Focus(); } private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); } private void btnEnter_Click(object sender, System.EventArgs e) { if(txtID.Text=="" || txtName.Text=="" || txtNumber.Text=="" || txtPrice.Text=="") { MessageBox.Show("Some of the invoice items have not been entered.","Please check the entered data.", MessageBoxButtons.RetryCancel, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1,MessageBoxOptions.ServiceNotification); } else { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); ClearBoxes(); txtID.Focus(); } } private void btnDisplay_Click(object sender, System.EventArgs e) { if(productID.Count==0) { MessageBox.Show("No invoice items have been entered.","Please enter data.",MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2,MessageBoxOptions.RightAlign); } else { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20)+ "Product Name".PadRight(20)+ "Number".PadRight(15)+ "Price".PadRight(20)+ "Total".PadRight(20)+"\r\n"; int numberItems = productID.Count; for(int index=0;index
file:///D|/1/final/BBL0116.html (47 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } txtDisplayInvoice.Text = theOutput + "\r\n" + String.Format("{0,-20}","Total:") + String.Format("{0,60:c}",invoiceTotal); } } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 8/17/2006 // description This file along the the file: Form1.cs // and Program.cs create a Windows program that // implements a program to handle invoices entry. // //
namespace Invoices { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.txtID = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.btnEnter = new System.Windows.Forms.Button(); this.btnDisplay = new System.Windows.Forms.Button(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnClear = new System.Windows.Forms.Button(); this.SuspendLayout(); // // txtID // this.txtID.Location = new System.Drawing.Point(200, 55); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(110, 23); this.txtID.TabIndex = 1; // // txtNumber //
file:///D|/1/final/BBL0116.html (48 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtNumber.Location = new System.Drawing.Point(590, 55); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(110, 23); this.txtNumber.TabIndex = 3; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(590, 80); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(110, 23); this.txtPrice.TabIndex = 4; // // txtName // this.txtName.Location = new System.Drawing.Point(200, 80); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(146, 23); this.txtName.TabIndex = 2; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(30, 60); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 16); this.label1.TabIndex = 5; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(30, 90); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(104, 16); this.label2.TabIndex = 6; this.label2.Text = "Product Name"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(366, 57); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(208, 16); this.label3.TabIndex = 7; this.label3.Text = "Number of Items Purchased"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(366, 90); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(120, 16); this.label4.TabIndex = 8; this.label4.Text = "Price per Item"; // // btnEnter // this.btnEnter.Location = new System.Drawing.Point(34, 150); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(125, 23); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnDisplay // this.btnDisplay.Location = new System.Drawing.Point(33, 212); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(175, 23); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click);
file:///D|/1/final/BBL0116.html (49 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 265); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(700, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnClear // this.btnClear.Location = new System.Drawing.Point(475, 179); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(160, 23); this.btnClear.TabIndex = 10; this.btnClear.Text = "Clear Invoice"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(732, 522); this.Controls.Add(this.btnClear); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.btnEnter); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.txtName); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtID); this.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(4); this.MaximumSize = new System.Drawing.Size(740, 550); this.MinimumSize = new System.Drawing.Size(740, 550); this.Name = "Form1"; this.Text = "Invoices"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnClear; } }
// program_id Form1.cs // written_by don voils // date_written 8/17/2006 // description This file along the the file: Form1.Design.cs // and Program.cs create a Windows program that // implements a program to handle invoices entry.
file:///D|/1/final/BBL0116.html (50 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; namespace invoicesNew { public partial class Form1 : Form { private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList(); public Form1() { InitializeComponent(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); } private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); } private void btnEnter_Click(object sender, EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); btnDisplay.Enabled = true; btnClear.Enabled = true; ClearBoxes(); txtID.Focus(); } private void btnDisplay_Click(object sender, EventArgs e) { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { theOutput += String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index])) + "\r\n"; invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } txtDisplayInvoice.Text = theOutput + "\r\n" + String.Format("{0,-20}", "Total") + String.Format("{0,60:c}", invoiceTotal);
file:///D|/1/final/BBL0116.html (51 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
} private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); } } }
// program_id Form1.Design.cs // written_by don voils // date_written 8/17/2006 // description This file along the the file: Form1.cs // and Program.cs create a Windows program that // implements a program to handle invoices entry. // // namespace invoicesNew { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnDisplay = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.Location = new System.Drawing.Point(27, 49);
file:///D|/1/final/BBL0116.html (52 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 16); this.label1.TabIndex = 0; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.Location = new System.Drawing.Point(27, 98); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(104, 16); this.label2.TabIndex = 1; this.label2.Text = "Product Name"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label3.Location = new System.Drawing.Point(394, 46); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(208, 16); this.label3.TabIndex = 2; this.label3.Text = "Number of Items Purchased"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.Location = new System.Drawing.Point(394, 98); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(120, 16); this.label4.TabIndex = 3; this.label4.Text = "Price per Item"; // // txtID // this.txtID.Location = new System.Drawing.Point(199, 43); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(100, 22); this.txtID.TabIndex = 1; // // txtName // this.txtName.Location = new System.Drawing.Point(199, 92); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(156, 22); this.txtName.TabIndex = 2; // // txtNumber // this.txtNumber.Location = new System.Drawing.Point(717, 43); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(100, 22); this.txtNumber.TabIndex = 3; this.txtNumber.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(717, 92); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(100, 22); this.txtPrice.TabIndex = 4; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 267); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
file:///D|/1/final/BBL0116.html (53 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtDisplayInvoice.Size = new System.Drawing.Size(860, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnEnter.Location = new System.Drawing.Point(61, 160); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(172, 23); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnClear // this.btnClear.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnClear.Location = new System.Drawing.Point(501, 195); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(177, 23); this.btnClear.TabIndex = 7; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Invoice"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnDisplay // this.btnDisplay.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnDisplay.Location = new System.Drawing.Point(61, 224); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(172, 23); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(892, 522); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(4); this.MaximumSize = new System.Drawing.Size(900, 550); this.MinimumSize = new System.Drawing.Size(900, 550); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Invoices"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3;
file:///D|/1/final/BBL0116.html (54 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnDisplay; } }
// program_id Program.cs // written_by don voils // date_written 8/17/2006 // description This file along the the file: Form1.cs // and Form1.Design.cs create a Windows program that // implements a program to handle invoices entry. // // using System; using System.Collections.Generic; using System.Windows.Forms; namespace invoicesNew { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id menuInvoices.cs // written_by don voils // date_written 4/5/2003 // description This program demonstrates the entry and display // of invoice items into a Windows form. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; using System.Text; namespace mrnuInvoices { /// <summary> /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { // Definition of the arrays for each of the // invoice items. // private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList();
file:///D|/1/final/BBL0116.html (55 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem menuItem7; private System.Windows.Forms.MainMenu MainMenu; private System.Windows.Forms.MenuItem fileMenuItem; private System.Windows.Forms.MenuItem newMenuItem; private System.Windows.Forms.MenuItem openMenuItem; private System.Windows.Forms.MenuItem saveInvoiceMenuItem; private System.Windows.Forms.MenuItem printMenuItem; private System.Windows.Forms.MenuItem exitMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.PrintDialog printDialog; private System.Drawing.Printing.PrintDocument printDocument; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if(disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnDisplay = new System.Windows.Forms.Button(); this.MainMenu = new System.Windows.Forms.MainMenu();
file:///D|/1/final/BBL0116.html (56 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.fileMenuItem = new System.Windows.Forms.MenuItem(); this.newMenuItem = new System.Windows.Forms.MenuItem(); this.openMenuItem = new System.Windows.Forms.MenuItem(); this.saveInvoiceMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.printMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem7 = new System.Windows.Forms.MenuItem(); this.exitMenuItem = new System.Windows.Forms.MenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.printDocument = new System.Drawing.Printing.PrintDocument(); this.SuspendLayout(); // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(16, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(104, 23); this.label1.TabIndex = 0; this.label1.Text = "Product ID Number"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label2.Location = new System.Drawing.Point(16, 48); this.label2.Name = "label2"; this.label2.TabIndex = 1; this.label2.Text = "Product Name"; // // label3 // this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label3.Location = new System.Drawing.Point(376, 48); this.label3.Name = "label3"; this.label3.TabIndex = 2; this.label3.Text = "Price per Item"; // // label4 // this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label4.Location = new System.Drawing.Point(336, 16); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(152, 23); this.label4.TabIndex = 3; this.label4.Text = "Number of Items Purchased"; // // txtID // this.txtID.Enabled = false; this.txtID.Location = new System.Drawing.Point(136, 16); this.txtID.Name = "txtID"; this.txtID.TabIndex = 1; this.txtID.Text = ""; // // txtName // this.txtName.Enabled = false; this.txtName.Location = new System.Drawing.Point(136, 48); this.txtName.Name = "txtName"; this.txtName.TabIndex = 2; this.txtName.Text = ""; // // txtNumber // this.txtNumber.Enabled = false; this.txtNumber.Location = new System.Drawing.Point(504, 16); this.txtNumber.Name = "txtNumber"; this.txtNumber.TabIndex = 3; this.txtNumber.Text = ""; //
file:///D|/1/final/BBL0116.html (57 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// txtPrice // this.txtPrice.Enabled = false; this.txtPrice.Location = new System.Drawing.Point(504, 48); this.txtPrice.Name = "txtPrice"; this.txtPrice.TabIndex = 4; this.txtPrice.Text = ""; // // btnEnter // this.btnEnter.Enabled = false; this.btnEnter.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnEnter.Location = new System.Drawing.Point(256, 80); this.btnEnter.Name = "btnEnter"; this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // txtDisplayInvoice // this.txtDisplayInvoice.Enabled = false; this.txtDisplayInvoice.Location = new System.Drawing.Point(16, 120); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(688, 128); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; this.txtDisplayInvoice.Text = ""; // // btnDisplay // this.btnDisplay.Enabled = false; this.btnDisplay.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing. GraphicsUnit.Point, ((System.Byte)(0))); this.btnDisplay.Location = new System.Drawing.Point(480, 88); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(112, 23); this.btnDisplay.TabIndex = 9; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // MainMenu // this.MainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.fileMenuItem}); // // fileMenuItem // this.fileMenuItem.Index = 0; this.fileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.newMenuItem, this.openMenuItem, this.saveInvoiceMenuItem, this.menuItem5, this.printMenuItem, this.menuItem7, this.exitMenuItem}); this.fileMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF; this.fileMenuItem.Text = "&File"; // // newMenuItem // this.newMenuItem.Index = 0; this.newMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlN; this.newMenuItem.Text = "&New"; this.newMenuItem.Click += new System.EventHandler(this.newMenuItem_Click); // // openMenuItem // this.openMenuItem.Index = 1; this.openMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlO; this.openMenuItem.Text = "&Open";
file:///D|/1/final/BBL0116.html (58 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // saveInvoiceMenuItem // this.saveInvoiceMenuItem.Enabled = false; this.saveInvoiceMenuItem.Index = 2; this.saveInvoiceMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlS; this.saveInvoiceMenuItem.Text = "&Save Invoice"; this.saveInvoiceMenuItem.Click += new System.EventHandler(this.saveInvoiceMenuItem_Click); // // menuItem5 // this.menuItem5.Index = 3; this.menuItem5.Text = "-"; // // printMenuItem // this.printMenuItem.Enabled = false; this.printMenuItem.Index = 4; this.printMenuItem.Text = "&Print"; this.printMenuItem.Click += new System.EventHandler(this.printMenuItem_Click); // // menuItem7 // this.menuItem7.Index = 5; this.menuItem7.Text = "-"; // // exitMenuItem // this.exitMenuItem.Index = 6; this.exitMenuItem.Shortcut = System.Windows.Forms.Shortcut.AltF4; this.exitMenuItem.Text = "E&xit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt"; this.saveFileDialog.Title = "Invoicesw"; // // openFileDialog // this.openFileDialog.DefaultExt = "txt"; this.openFileDialog.InitialDirectory = "c:\\"; this.openFileDialog.Title = "Invoices"; // // printDialog // this.printDialog.Document = this.printDocument; // // printDocument // this.printDocument.DocumentName = ""; this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printPage); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(8, 15); this.ClientSize = new System.Drawing.Size(712, 266); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Menu = this.MainMenu; this.Name = "Form1"; this.Text = "menuInvoices"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false);
file:///D|/1/final/BBL0116.html (59 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
} #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { txtID.Focus(); } private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); txtDisplayInvoice.Clear(); } private void btnEnter_Click(object sender, System.EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); btnDisplay.Enabled = true; ClearBoxes(); txtID.Focus(); } private void btnDisplay_Click(object sender, System.EventArgs e) { txtDisplayInvoice.Enabled = true; decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20)+ "Product Name".PadRight(20)+ "Number".PadRight(15)+ "Price".PadRight(20)+ "Total".PadRight(20)+"\r\n"; int numberItems = productID.Count; for(int index=0;index
file:///D|/1/final/BBL0116.html (60 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
MessageBox.Show("There is no data to be printed","Error"); } private void exitMenuItem_Click(object sender, System.EventArgs e) { Application.Exit(); } private void newMenuItem_Click(object sender, System.EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveInvoiceMenuItem.Enabled = true; printMenuItem.Enabled=true; btnEnter.Enabled=true; txtID.Focus(); } private void saveInvoiceMenuItem_Click(object sender, System.EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if(buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter("Invoice.txt"); // used to find the number of elements in each of the arrays. // int numberItems = productID.Count; // loops through each array and extracts the elements and then // writes them to the file. // for(int index=0;index
file:///D|/1/final/BBL0116.html (61 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
btnEnter.Enabled = false; btnDisplay.Enabled = false; // disables the menu options for save and print since // there is no more data contained in memory. // saveInvoiceMenuItem.Enabled=false; printMenuItem.Enabled=false; } } private void openMenuItem_Click(object sender, System.EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if(buttonClicked.Equals(DialogResult.OK)) { ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; saveInvoiceMenuItem.Enabled = true; printMenuItem.Enabled = true; string theData; StreamReader fileReader = new StreamReader("Invoice.txt"); theData = fileReader.ReadLine(); while(theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { StringBuilder data = new StringBuilder(); StringWriter writer = new StringWriter(data); writer.WriteLine("Product ID".PadRight(20)+ "Product Name".PadRight(20)+ "Number".PadRight(15)+ "Price".PadRight(20)+ "Total".PadRight(20)+"\r\n"); decimal invoiceTotal = 0.00m; int numberItems = productID.Count; for(int index=0;index
file:///D|/1/final/BBL0116.html (62 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
} writer.WriteLine("\r\n" + String.Format("{0,-20}","Total:") + String.Format("{0,60:c}",invoiceTotal)); writer.Close(); float leftMargin = e.MarginBounds.Left; float topMargin = e.MarginBounds.Top; float yPos = 0; Font printFont = null; printFont = new Font("Courier New",10); yPos = topMargin + printFont.GetHeight(e.Graphics); e.HasMorePages = false; e.Graphics.DrawString(data.ToString(), printFont,Brushes.Black, leftMargin, yPos, new StringFormat()); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 8/17/2006 // date_modified 9/19/2006 // date_modified 9/20/2006 // description This file along the the file: Form1.cs // and Program.cs create a Windows program that // implements a program to handle invoices entry. // // This modification includes the addition // of a menu bar. // The second modification include the addition // of a tool bar to emulate the menu bar.
namespace Invoices { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (Form1)); this.txtID = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label();
file:///D|/1/final/BBL0116.html (63 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.btnEnter = new System.Windows.Forms.Button(); this.btnDisplay = new System.Windows.Forms.Button(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnClear = new System.Windows.Forms.Button(); this.MainMenu = new System.Windows.Forms.MenuStrip(); this.fileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.saveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.printMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.exitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.printDocument = new System.Drawing.Printing.PrintDocument(); this.toolStrip = new System.Windows.Forms.ToolStrip(); this.toolStripNew = new System.Windows.Forms.ToolStripButton(); this.toolStripOpen = new System.Windows.Forms.ToolStripButton(); this.toolStripSave = new System.Windows.Forms.ToolStripButton(); this.toolStripPrint = new System.Windows.Forms.ToolStripButton(); this.MainMenu.SuspendLayout(); this.toolStrip.SuspendLayout(); this.SuspendLayout(); // // txtID // this.txtID.Location = new System.Drawing.Point(250, 55); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(110, 23); this.txtID.TabIndex = 1; // // txtNumber // this.txtNumber.Location = new System.Drawing.Point(710, 55); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(110, 23); this.txtNumber.TabIndex = 3; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(710, 85); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(110, 23); this.txtPrice.TabIndex = 4; // // txtName // this.txtName.Location = new System.Drawing.Point(250, 85); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(146, 23); this.txtName.TabIndex = 2; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(50, 55); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 16); this.label1.TabIndex = 5; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(50, 85); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(104, 16); this.label2.TabIndex = 6; this.label2.Text = "Product Name";
file:///D|/1/final/BBL0116.html (64 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(410, 55); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(208, 16); this.label3.TabIndex = 7; this.label3.Text = "Number of Items Purchased"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(410, 85); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(120, 16); this.label4.TabIndex = 8; this.label4.Text = "Price per Item"; // // btnEnter // this.btnEnter.Location = new System.Drawing.Point(34, 150); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(125, 25); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnDisplay // this.btnDisplay.Location = new System.Drawing.Point(33, 212); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(175, 25); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 265); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(840, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnClear // this.btnClear.Location = new System.Drawing.Point(475, 179); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(160, 25); this.btnClear.TabIndex = 10; this.btnClear.Text = "Clear Invoice"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // MainMenu // this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileMenuItem}); this.MainMenu.Location = new System.Drawing.Point(0, 0); this.MainMenu.Name = "MainMenu"; this.MainMenu.Size = new System.Drawing.Size(872, 24); this.MainMenu.TabIndex = 11; this.MainMenu.Text = "menuStrip1"; // // fileMenuItem // this.fileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newMenuItem,
file:///D|/1/final/BBL0116.html (65 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.openMenuItem, this.toolStripMenuItem1, this.saveMenuItem, this.toolStripMenuItem2, this.printMenuItem, this.toolStripMenuItem3, this.exitMenuItem}); this.fileMenuItem.Name = "fileMenuItem"; this.fileMenuItem.Size = new System.Drawing.Size(35, 20); this.fileMenuItem.Text = "&File"; // // newMenuItem // this.newMenuItem.Name = "newMenuItem"; this.newMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newMenuItem.Size = new System.Drawing.Size(151, 22); this.newMenuItem.Text = "&New"; this.newMenuItem.Click += new System.EventHandler(this.newMenuItem_Click); // // openMenuItem // this.openMenuItem.Name = "openMenuItem"; this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openMenuItem.Size = new System.Drawing.Size(151, 22); this.openMenuItem.Text = "&Open"; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(148, 6); // // saveMenuItem // this.saveMenuItem.Enabled = false; this.saveMenuItem.Name = "saveMenuItem"; this.saveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveMenuItem.Size = new System.Drawing.Size(151, 22); this.saveMenuItem.Text = "&Save"; this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(148, 6); // // printMenuItem // this.printMenuItem.Enabled = false; this.printMenuItem.Name = "printMenuItem"; this.printMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printMenuItem.Size = new System.Drawing.Size(151, 22); this.printMenuItem.Text = "&Print"; this.printMenuItem.Click += new System.EventHandler(this.printMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(148, 6); // // exitMenuItem // this.exitMenuItem.Name = "exitMenuItem"; this.exitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.exitMenuItem.Size = new System.Drawing.Size(151, 22); this.exitMenuItem.Text = "E&xit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt"; this.saveFileDialog.InitialDirectory = "c:\\"; this.saveFileDialog.Title = "Invoices"; // // openFileDialog //
file:///D|/1/final/BBL0116.html (66 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.openFileDialog.DefaultExt = "txt"; this.openFileDialog.InitialDirectory = "c:\\"; this.openFileDialog.Title = "Invoice.txt"; // // printDialog // this.printDialog.Document = this.printDocument; this.printDialog.UseEXDialog = true; // // printDocument // this.printDocument.DocumentName = ""; this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printPage); // // toolStrip // this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripNew, this.toolStripOpen, this.toolStripSave, this.toolStripPrint}); this.toolStrip.Location = new System.Drawing.Point(0, 24); this.toolStrip.Name = "toolStrip"; this.toolStrip.Size = new System.Drawing.Size(872, 25); this.toolStrip.TabIndex = 12; // // toolStripNew // this.toolStripNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripNew.Image = ((System.Drawing.Image)(resources.GetObject("toolStripNew.Image"))); this.toolStripNew.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripNew.Name = "toolStripNew"; this.toolStripNew.Size = new System.Drawing.Size(23, 22); this.toolStripNew.Text = "New"; this.toolStripNew.Click += new System.EventHandler(this.toolStripNew_Click); // // toolStripOpen // this.toolStripOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripOpen.Image = ((System.Drawing.Image)(resources.GetObject("toolStripOpen.Image"))); this.toolStripOpen.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripOpen.Name = "toolStripOpen"; this.toolStripOpen.Size = new System.Drawing.Size(23, 22); this.toolStripOpen.Text = "Open"; this.toolStripOpen.Click += new System.EventHandler(this.toolStripOpen_Click); // // toolStripSave // this.toolStripSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripSave.Enabled = false; this.toolStripSave.Image = ((System.Drawing.Image)(resources.GetObject("toolStripSave.Image"))); this.toolStripSave.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripSave.Name = "toolStripSave"; this.toolStripSave.Size = new System.Drawing.Size(23, 22); this.toolStripSave.Text = "Save"; this.toolStripSave.Click += new System.EventHandler(this.toolStripSave_Click); // // toolStripPrint // this.toolStripPrint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripPrint.Enabled = false; this.toolStripPrint.Image = ((System.Drawing.Image)(resources.GetObject("toolStripPrint.Image"))); this.toolStripPrint.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripPrint.Name = "toolStripPrint"; this.toolStripPrint.Size = new System.Drawing.Size(23, 22); this.toolStripPrint.Text = "Print"; this.toolStripPrint.Click += new System.EventHandler(this.toolStripPrint_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(872, 522); this.Controls.Add(this.toolStrip);
file:///D|/1/final/BBL0116.html (67 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.Controls.Add(this.btnClear); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.btnEnter); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.txtName); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtID); this.Controls.Add(this.MainMenu); this.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MainMenuStrip = this.MainMenu; this.Margin = new System.Windows.Forms.Padding(4); this.MaximumSize = new System.Drawing.Size(880, 550); this.MinimumSize = new System.Drawing.Size(880, 550); this.Name = "Form1"; this.Text = "Tool Bar Invoices"; this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.toolStrip.ResumeLayout(false); this.toolStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.MenuStrip MainMenu; private System.Windows.Forms.ToolStripMenuItem fileMenuItem; private System.Windows.Forms.ToolStripMenuItem newMenuItem; private System.Windows.Forms.ToolStripMenuItem openMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem printMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem exitMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.PrintDialog printDialog; private System.Drawing.Printing.PrintDocument printDocument; private System.Windows.Forms.ToolStrip toolStrip; private System.Windows.Forms.ToolStripButton toolStripNew; private System.Windows.Forms.ToolStripButton toolStripOpen; private System.Windows.Forms.ToolStripButton toolStripSave; private System.Windows.Forms.ToolStripButton toolStripPrint; } }
// program_id Form1.cs // written_by don voils // date_written 10/13/2006 // description This file along with Form1.Designer.cs // and Program.cs creates a program with // a menu strip. // using System;
file:///D|/1/final/BBL0116.html (68 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO;
namespace menuInvoices { public partial class Form1 : Form { private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList(); public Form1() { InitializeComponent(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; txtID.Focus(); } private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); txtDisplayInvoice.Clear(); } private void btnEnter_Click(object sender, EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); btnDisplay.Enabled = true; btnClear.Enabled = true; ClearBoxes(); txtID.Focus(); } private void btnDisplay_Click(object sender, EventArgs e) { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { theOutput += String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index])) + "\r\n";
file:///D|/1/final/BBL0116.html (69 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } txtDisplayInvoice.Text = theOutput + "\r\n" + String.Format("{0,-20}", "Total") + String.Format("{0,60:c}", invoiceTotal); } private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); saveMenuItem.Enabled = false; printMenuItem.Enabled = false; } private void exitMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void newMenuItem_Click(object sender, EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; btnEnter.Enabled = true; txtID.Focus(); } private void saveMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); //used to find the number of elements in each // of the arrays. int numberItems = productID.Count; // loops through each array and extracts the // elements and then writes them to the file. // for (int index = 0; index < numberItems; ++index) { fileWriter.WriteLine(String.Format("{0}", productID[index])); fileWriter.WriteLine(String.Format("{0}", productName[index])); fileWriter.WriteLine(String.Format("{0}", numberOrdered[index])); fileWriter.WriteLine(String.Format("{0}", itemPrice[index])); } // closes the file to empty the output buffer. // fileWriter.Close(); // sends a message to the user that the file // has been saved. // MessageBox.Show("Invoice details were saved", "Saved"); // clears all of the textboxes. // ClearBoxes(); // clears the data from the arrays so that they // are empty in case // the user wants to work on another invoice.
file:///D|/1/final/BBL0116.html (70 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); // disables all of the textboxes // and the buttons. txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for Save and Print since // there is no more data contained in memory. // saveMenuItem.Enabled = false; printMenuItem.Enabled = false; } } private void openMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { // Clear the arrays and the form of all data. // ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; // Reads the data from the file one // record at a time and then closes // the reader when completed. // string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while (theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void printMenuItem_Click(object sender, EventArgs e) { if(productID.Count!=0) { DialogResult buttonClicked = printDialog.ShowDialog(); if(buttonClicked.Equals(DialogResult.OK))
file:///D|/1/final/BBL0116.html (71 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ printDocument.Print(); } } else MessageBox.Show("There was no data to be printed.","Error"); } private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { StringBuilder data = new StringBuilder(); StringWriter writer = new StringWriter(data); writer.WriteLine("Producet ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"); decimal invoiceTotal = 0.00m; int numberItems = productID.Count; for(int index = 0;index
// program_id Form1.cs // written_by don voils // date_written 10/13/2006 // description This file along with Form1.cs // and Program.cs creates a program with // a menu strip. // namespace menuInvoices { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary>
file:///D|/1/final/BBL0116.html (72 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
/// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnDisplay = new System.Windows.Forms.Button(); this.MainMenu = new System.Windows.Forms.MenuStrip(); this.fileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.saveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.printMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.exitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.printDocument = new System.Drawing.Printing.PrintDocument(); this.MainMenu.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.Location = new System.Drawing.Point(27, 49); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(179, 20); this.label1.TabIndex = 0; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.Location = new System.Drawing.Point(27, 98); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(129, 20); this.label2.TabIndex = 1; this.label2.Text = "Product Name"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)
file:///D|/1/final/BBL0116.html (73 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
(0))); this.label3.Location = new System.Drawing.Point(394, 46); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(259, 20); this.label3.TabIndex = 2; this.label3.Text = "Number of Items Purchased"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.Location = new System.Drawing.Point(394, 98); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(149, 20); this.label4.TabIndex = 3; this.label4.Text = "Price per Item"; // // txtID // this.txtID.Location = new System.Drawing.Point(212, 43); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(100, 26); this.txtID.TabIndex = 1; // // txtName // this.txtName.Location = new System.Drawing.Point(212, 92); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(156, 26); this.txtName.TabIndex = 2; // // txtNumber // this.txtNumber.Location = new System.Drawing.Point(717, 43); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(100, 26); this.txtNumber.TabIndex = 3; this.txtNumber.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(717, 92); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(100, 26); this.txtPrice.TabIndex = 4; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 267); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(860, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.btnEnter.Location = new System.Drawing.Point(61, 160); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(172, 23); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnClear // this.btnClear.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.btnClear.Location = new System.Drawing.Point(501, 195);
file:///D|/1/final/BBL0116.html (74 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(177, 23); this.btnClear.TabIndex = 7; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Invoice"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnDisplay // this.btnDisplay.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnDisplay.Location = new System.Drawing.Point(61, 224); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(172, 23); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // MainMenu // this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileMenuItem}); this.MainMenu.Location = new System.Drawing.Point(0, 0); this.MainMenu.Name = "MainMenu"; this.MainMenu.Size = new System.Drawing.Size(892, 26); this.MainMenu.TabIndex = 8; this.MainMenu.Text = "menuStrip1"; // // fileMenuItem // this.fileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newMenuItem, this.openMenuItem, this.toolStripMenuItem1, this.saveMenuItem, this.toolStripMenuItem3, this.printMenuItem, this.toolStripMenuItem4, this.exitMenuItem}); this.fileMenuItem.Name = "fileMenuItem"; this.fileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.fileMenuItem.Size = new System.Drawing.Size(40, 22); this.fileMenuItem.Text = "&File"; // // newMenuItem // this.newMenuItem.Name = "newMenuItem"; this.newMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newMenuItem.Size = new System.Drawing.Size(177, 22); this.newMenuItem.Text = "&New"; this.newMenuItem.Click += new System.EventHandler(this.newMenuItem_Click); // // openMenuItem // this.openMenuItem.Name = "openMenuItem"; this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openMenuItem.Size = new System.Drawing.Size(177, 22); this.openMenuItem.Text = "&Open"; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(174, 6); // // saveMenuItem // this.saveMenuItem.Enabled = false; this.saveMenuItem.Name = "saveMenuItem"; this.saveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveMenuItem.Size = new System.Drawing.Size(177, 22); this.saveMenuItem.Text = "&Save";
file:///D|/1/final/BBL0116.html (75 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(174, 6); // // printMenuItem // this.printMenuItem.Enabled = false; this.printMenuItem.Name = "printMenuItem"; this.printMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printMenuItem.Size = new System.Drawing.Size(177, 22); this.printMenuItem.Text = "&Print"; this.printMenuItem.Click += new System.EventHandler(this.printMenuItem_Click); // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(174, 6); // // exitMenuItem // this.exitMenuItem.Name = "exitMenuItem"; this.exitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.exitMenuItem.Size = new System.Drawing.Size(177, 22); this.exitMenuItem.Text = "E&xit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt"; this.saveFileDialog.InitialDirectory = "C:\\"; this.saveFileDialog.Title = "Invoices"; // // openFileDialog // this.openFileDialog.DefaultExt = "txt"; this.openFileDialog.InitialDirectory = "C:\\"; this.openFileDialog.Title = "Invoices.txt"; // // printDialog // this.printDialog.Document = this.printDocument; this.printDialog.UseEXDialog = true; // // printDocument // this.printDocument.DocumentName = ""; this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printPage); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(892, 517); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.MainMenu); this.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MainMenuStrip = this.MainMenu; this.Margin = new System.Windows.Forms.Padding(4); this.MaximumSize = new System.Drawing.Size(900, 550); this.MinimumSize = new System.Drawing.Size(900, 550); this.Name = "Form1";
file:///D|/1/final/BBL0116.html (76 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Menu Invoices"; this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.MenuStrip MainMenu; private System.Windows.Forms.ToolStripMenuItem fileMenuItem; private System.Windows.Forms.ToolStripMenuItem newMenuItem; private System.Windows.Forms.ToolStripMenuItem openMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem printMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem exitMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.PrintDialog printDialog; private System.Drawing.Printing.PrintDocument printDocument; } }
// program_id Program.cs // written_by don voils // date_written 10/13/2006 // description This file along with Form1.Designer.cs // and Form1.cs creates a program with // a menu strip. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace menuInvoices { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id message1.cs // written_by don voils // date_written 3/13/2006 // description This program demonstrates one of the // 12 overloaded versions of the show()
file:///D|/1/final/BBL0116.html (77 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// method of the class MessageBox. using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace message1 { /// <summary> /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // MessageBox.Show("The program saved the data."); } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.Size = new System.Drawing.Size(300,300); this.Text = "Form1"; } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 8/25/2006
file:///D|/1/final/BBL0116.html (78 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// description This file along with Form1.cs and // Program.cs demonstrate one of the // 12 overloaded versions of the show() // method of the class MessageBox. // namespace Message1 { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.btnSave = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnSave // this.btnSave.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnSave.Location = new System.Drawing.Point(106, 135); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(100, 30); this.btnSave.TabIndex = 0; this.btnSave.Text = "Save"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // Form1 // this.ClientSize = new System.Drawing.Size(292, 267); this.Controls.Add(this.btnSave); this.Name = "Form1"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnSave; } }
// program_id Form1.cs // written_by don voils // date_written 8/25/2006 // description This file along with Form1.Design.cs and // Program.cs demonstrate one of the // 12 overloaded versions of the show() // method of the class MessageBox. using System; using System.Collections.Generic;
file:///D|/1/final/BBL0116.html (79 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Message1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { MessageBox.Show("The program saved the data."); } } }
// program_id Program.cs // written_by don voils // date_written 8/25/2006 // description This file along with Form1.Design.cs and // Form1.cs demonstrate one of the // 12 overloaded versions of the show() // method of the class MessageBox. using System; using System.Collections.Generic; using System.Windows.Forms; namespace Message1 { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id message2.cs // written_by don voils // date_written 3/13/2006 // description This program demonstrates one of the // 12 overloaded versions of the show() // method of the class MessageBox. This version // has two arguments that are both strings. One // of the strings appears in the body of the // window while the second appears in the title bar. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace message1 { /// <summary> /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form
file:///D|/1/final/BBL0116.html (80 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // MessageBox.Show("There is no data to be printed","Error"); } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.Size = new System.Drawing.Size(300,300); this.Text = "Form1"; } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 8/25/2006 // description This file along with Form1.cs and // Program.cs demonstrate one of the // 12 overloaded versions of the show() // method of the class MessageBox. // namespace Message2 { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null;
file:///D|/1/final/BBL0116.html (81 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
/// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.btnPrint = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnPrint // this.btnPrint.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnPrint.Location = new System.Drawing.Point(106, 135); this.btnPrint.Name = "btnPrint"; this.btnPrint.Size = new System.Drawing.Size(100, 30); this.btnPrint.TabIndex = 0; this.btnPrint.Text = "Print"; this.btnPrint.UseVisualStyleBackColor = true; this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click); // // Form1 // this.ClientSize = new System.Drawing.Size(292, 267); this.Controls.Add(this.btnPrint); this.Name = "Form1"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnPrint; } }
// program_id Form1.cs // written_by don voils // date_written 8/25/2006 // description This file along with Form1.Design.cs and // Program.cs demonstrate one of the // 12 overloaded versions of the show() // method of the class MessageBox. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Message2 { public partial class Form1 : Form { public Form1() { InitializeComponent();
file:///D|/1/final/BBL0116.html (82 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
} private void btnPrint_Click(object sender, EventArgs e) { MessageBox.Show("There is no data to be printed", "Error"); } } }
// program_id Program.cs // written_by don voils // date_written 8/25/2006 // description This file along with Form1.Design.cs and // Form1.cs demonstrate one of the // 12 overloaded versions of the show() // method of the class MessageBox. using System; using System.Collections.Generic; using System.Windows.Forms; namespace Message2 { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id OrderForm.cs // written_by Don Voils // date_written 1/15/2006 // description This program processes orders for the Alligators. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using thePeople; namespace theAlligators { /// <summary> /// Summary description for Form1. /// public class OrderForm : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtAddress; private System.Windows.Forms.TextBox txtCity; private System.Windows.Forms.TextBox txtZip; private System.Windows.Forms.ComboBox creditCo; private System.Windows.Forms.ComboBox txtState;
file:///D|/1/final/BBL0116.html (83 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox txtNoTickets; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.ComboBox txtColor; private System.Windows.Forms.ComboBox txtSize; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label label16; private System.Windows.Forms.Button btnCheck; private System.Windows.Forms.Button btnSend; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.DateTimePicker dateOrdered; private System.Windows.Forms.DateTimePicker dateGame; private System.Windows.Forms.RadioButton rBtn15; private System.Windows.Forms.RadioButton rBtn10; private System.Windows.Forms.RadioButton rBtn5; private System.Windows.Forms.TextBox txtAmount; private System.Windows.Forms.TextBox txtNoJersey; private System.Windows.Forms.GroupBox shippingGroup; private System.Windows.Forms.CheckBox chkCap; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public OrderForm() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // }
// //
private void ClearForm() { // Could not find way to set these dates to current date. // dateOrdered = ??????; dateGame = ??????; // // Notice that some of the entries may be cleared by // the Clear() method while others may be cleared // by using an empty string or a string with 0 as // a character. // creditCo.Text=" "; txtID.Clear(); txtName.Clear(); txtAddress.Clear(); txtCity.Clear(); txtState.Text=" "; txtZip.Clear(); txtNoTickets.Text="0"; txtColor.Text=" "; txtSize.Text=" "; txtNoJersey.Text="0"; txtAmount.Clear(); chkCap.Checked= false; rBtn5.Checked = false; rBtn10.Checked= false; rBtn15.Checked= false; } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing)
file:///D|/1/final/BBL0116.html (84 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(OrderForm)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtAddress = new System.Windows.Forms.TextBox(); this.txtCity = new System.Windows.Forms.TextBox(); this.txtZip = new System.Windows.Forms.TextBox(); this.creditCo = new System.Windows.Forms.ComboBox(); this.txtState = new System.Windows.Forms.ComboBox(); this.dateOrdered = new System.Windows.Forms.DateTimePicker(); this.label9 = new System.Windows.Forms.Label(); this.txtNoTickets = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.txtColor = new System.Windows.Forms.ComboBox(); this.txtSize = new System.Windows.Forms.ComboBox(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.shippingGroup = new System.Windows.Forms.GroupBox(); this.rBtn5 = new System.Windows.Forms.RadioButton(); this.rBtn10 = new System.Windows.Forms.RadioButton(); this.rBtn15 = new System.Windows.Forms.RadioButton(); this.txtNoJersey = new System.Windows.Forms.TextBox(); this.label16 = new System.Windows.Forms.Label(); this.btnCheck = new System.Windows.Forms.Button(); this.btnSend = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.dateGame = new System.Windows.Forms.DateTimePicker(); this.txtAmount = new System.Windows.Forms.TextBox(); this.chkCap = new System.Windows.Forms.CheckBox(); this.shippingGroup.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(40, 40); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(170, 20); this.label1.TabIndex = 0; this.label1.Text = "Customer Information"; // // label2 // this.label2.Location = new System.Drawing.Point(50, 70); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(130, 20); this.label2.TabIndex = 1; this.label2.Text = "Credit Card:"; //
file:///D|/1/final/BBL0116.html (85 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// label3 // this.label3.Location = new System.Drawing.Point(50, 95); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(120, 20); this.label3.TabIndex = 2; this.label3.Text = "Credit Number:"; // // label4 // this.label4.Location = new System.Drawing.Point(50, 120); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(100, 20); this.label4.TabIndex = 3; this.label4.Text = "Name:"; // // label5 // this.label5.Location = new System.Drawing.Point(50, 145); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(100, 20); this.label5.TabIndex = 4; this.label5.Text = "Address:"; // // label6 // this.label6.Location = new System.Drawing.Point(50, 170); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(100, 20); this.label6.TabIndex = 5; this.label6.Text = "City"; // // label7 // this.label7.Location = new System.Drawing.Point(50, 200); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(100, 20); this.label7.TabIndex = 6; this.label7.Text = "State"; // // label8 // this.label8.Location = new System.Drawing.Point(50, 225); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(100, 20); this.label8.TabIndex = 7; this.label8.Text = "Zip"; // // txtID // this.txtID.Location = new System.Drawing.Point(200, 95); this.txtID.Name = "txtID"; this.txtID.TabIndex = 3; this.txtID.Text = ""; // // txtName // this.txtName.Location = new System.Drawing.Point(200, 120); this.txtName.Name = "txtName"; this.txtName.TabIndex = 4; this.txtName.Text = ""; // // txtAddress // this.txtAddress.Location = new System.Drawing.Point(200, 145); this.txtAddress.Name = "txtAddress"; this.txtAddress.TabIndex = 5; this.txtAddress.Text = ""; // // txtCity // this.txtCity.Location = new System.Drawing.Point(200, 170); this.txtCity.Name = "txtCity"; this.txtCity.TabIndex = 6; this.txtCity.Text = "";
file:///D|/1/final/BBL0116.html (86 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// // txtZip // this.txtZip.Location = new System.Drawing.Point(200, 225); this.txtZip.Name = "txtZip"; this.txtZip.TabIndex = 8; this.txtZip.Text = ""; // // creditCo // this.creditCo.Items.AddRange(new object[] { "", "Diners", "Master Card", "Visa"}); this.creditCo.Location = new System.Drawing.Point(200, 65); this.creditCo.Name = "creditCo"; this.creditCo.Size = new System.Drawing.Size(170, 27); this.creditCo.TabIndex = 2; // // txtState // this.txtState.Items.AddRange(new object[] { "", "AL", "AK", "AR", "AZ", "CA", "CO", "CN", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "LA", "KS", "KY", "MA", "MI", "MN", "MO", "MR", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "TN", "TX", "SC", "SD", "UT", "VA", "VT", "WA", "WI", "WV", "WY"}); this.txtState.Location = new System.Drawing.Point(200, 195); this.txtState.Name = "txtState"; this.txtState.Size = new System.Drawing.Size(50, 27);
file:///D|/1/final/BBL0116.html (87 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtState.TabIndex = 7; // // dateOrdered // this.dateOrdered.Location = new System.Drawing.Point(320, 20); this.dateOrdered.Name = "dateOrdered"; this.dateOrdered.Size = new System.Drawing.Size(260, 26); this.dateOrdered.TabIndex = 1; // // label9 // this.label9.Location = new System.Drawing.Point(50, 280); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(130, 20); this.label9.TabIndex = 17; this.label9.Text = "Number Tickets:"; // // txtNoTickets // this.txtNoTickets.Location = new System.Drawing.Point(200, 280); this.txtNoTickets.Name = "txtNoTickets"; this.txtNoTickets.Size = new System.Drawing.Size(30, 26); this.txtNoTickets.TabIndex = 9; this.txtNoTickets.Text = "0"; // // label10 // this.label10.Location = new System.Drawing.Point(190, 20); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(110, 20); this.label10.TabIndex = 19; this.label10.Text = "Date Ordered:"; // // label11 // this.label11.Location = new System.Drawing.Point(240, 255); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(130, 20); this.label11.TabIndex = 20; this.label11.Text = "Game Date:"; // // label12 // this.label12.Location = new System.Drawing.Point(50, 360); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(100, 20); this.label12.TabIndex = 22; this.label12.Text = "Team Jersey:"; // // txtColor // this.txtColor.Items.AddRange(new object[] { "", "Red", "Green", "Blue", "Yellow"}); this.txtColor.Location = new System.Drawing.Point(200, 380); this.txtColor.Name = "txtColor"; this.txtColor.Size = new System.Drawing.Size(120, 27); this.txtColor.TabIndex = 13; // // txtSize // this.txtSize.Items.AddRange(new object[] { "", "Small", "Medium", "Large", "Extra Large"}); this.txtSize.Location = new System.Drawing.Point(330, 380); this.txtSize.Name = "txtSize"; this.txtSize.Size = new System.Drawing.Size(120, 27); this.txtSize.TabIndex = 14; // // label13
file:///D|/1/final/BBL0116.html (88 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.label13.Location = new System.Drawing.Point(50, 390); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(100, 20); this.label13.TabIndex = 25; this.label13.Text = "$50.00 each"; // // label14 // this.label14.Location = new System.Drawing.Point(210, 350); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(100, 20); this.label14.TabIndex = 26; this.label14.Text = "Color"; // // label15 // this.label15.Location = new System.Drawing.Point(340, 350); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(100, 20); this.label15.TabIndex = 27; this.label15.Text = "Size"; // // shippingGroup // this.shippingGroup.Controls.Add(this.rBtn5); this.shippingGroup.Controls.Add(this.rBtn10); this.shippingGroup.Controls.Add(this.rBtn15); this.shippingGroup.Location = new System.Drawing.Point(50, 420); this.shippingGroup.Name = "shippingGroup"; this.shippingGroup.Size = new System.Drawing.Size(220, 100); this.shippingGroup.TabIndex = 15; this.shippingGroup.TabStop = false; this.shippingGroup.Text = "Select Shipping:"; // // rBtn5 // this.rBtn5.Location = new System.Drawing.Point(30, 70); this.rBtn5.Name = "rBtn5"; this.rBtn5.Size = new System.Drawing.Size(180, 20); this.rBtn5.TabIndex = 17; this.rBtn5.TabStop = true; this.rBtn5.Text = "5 days $10.00 Charge"; // // rBtn10 // this.rBtn10.Location = new System.Drawing.Point(30, 45); this.rBtn10.Name = "rBtn10"; this.rBtn10.Size = new System.Drawing.Size(180, 20); this.rBtn10.TabIndex = 16; this.rBtn10.TabStop = true; this.rBtn10.Text = "10 days $5.00 Charge"; // // rBtn15 // this.rBtn15.Location = new System.Drawing.Point(30, 20); this.rBtn15.Name = "rBtn15"; this.rBtn15.Size = new System.Drawing.Size(170, 20); this.rBtn15.TabIndex = 15; this.rBtn15.TabStop = true; this.rBtn15.Text = "15 days No Charge"; // // txtNoJersey // this.txtNoJersey.Location = new System.Drawing.Point(150, 380); this.txtNoJersey.Name = "txtNoJersey"; this.txtNoJersey.Size = new System.Drawing.Size(30, 26); this.txtNoJersey.TabIndex = 12; this.txtNoJersey.Text = "0"; // // label16 // this.label16.Location = new System.Drawing.Point(50, 300); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(100, 20);
file:///D|/1/final/BBL0116.html (89 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label16.TabIndex = 32; this.label16.Text = "$75.00 each"; // // btnCheck // this.btnCheck.Location = new System.Drawing.Point(400, 410); this.btnCheck.Name = "btnCheck"; this.btnCheck.Size = new System.Drawing.Size(140, 23); this.btnCheck.TabIndex = 18; this.btnCheck.Text = "Check Amount"; this.btnCheck.Click += new System.EventHandler(this.btnCheck_Click); // // btnSend // this.btnSend.Location = new System.Drawing.Point(30, 570); this.btnSend.Name = "btnSend"; this.btnSend.Size = new System.Drawing.Size(110, 20); this.btnSend.TabIndex = 19; this.btnSend.TabStop = false; this.btnSend.Text = "Send Order"; this.btnSend.Click += new System.EventHandler(this.btnSend_Click); // // btnClear // this.btnClear.Location = new System.Drawing.Point(170, 570); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(110, 20); this.btnClear.TabIndex = 20; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Order"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // dateGame // this.dateGame.Location = new System.Drawing.Point(250, 280); this.dateGame.Name = "dateGame"; this.dateGame.Size = new System.Drawing.Size(250, 26); this.dateGame.TabIndex = 10; // // txtAmount // this.txtAmount.Location = new System.Drawing.Point(415, 440); this.txtAmount.Name = "txtAmount"; this.txtAmount.TabIndex = 37; this.txtAmount.TabStop = false; this.txtAmount.Text = ""; // // chkCap // this.chkCap.Location = new System.Drawing.Point(50, 330); this.chkCap.Name = "chkCap"; this.chkCap.Size = new System.Drawing.Size(215, 24); this.chkCap.TabIndex = 11; this.chkCap.Text = "Select a team cap at $15.00"; // // OrderForm // this.AutoScaleBaseSize = new System.Drawing.Size(8, 19); this.BackColor = System.Drawing.SystemColors.Window; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(692, 632); this.Controls.Add(this.chkCap); this.Controls.Add(this.txtAmount); this.Controls.Add(this.dateGame); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnSend); this.Controls.Add(this.btnCheck); this.Controls.Add(this.label16); this.Controls.Add(this.txtNoJersey); this.Controls.Add(this.shippingGroup); this.Controls.Add(this.label15); this.Controls.Add(this.label14); this.Controls.Add(this.label13); this.Controls.Add(this.txtSize); this.Controls.Add(this.txtColor); this.Controls.Add(this.label12);
file:///D|/1/final/BBL0116.html (90 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.txtNoTickets); this.Controls.Add(this.label9); this.Controls.Add(this.dateOrdered); this.Controls.Add(this.txtState); this.Controls.Add(this.creditCo); this.Controls.Add(this.txtZip); this.Controls.Add(this.txtCity); this.Controls.Add(this.txtAddress); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Name = "OrderForm"; this.Text = "The Alligators OrderForm"; this.shippingGroup.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new OrderForm()); } private void btnSend_Click(object sender, System.EventArgs e) { // The following would prepare the People object to be // send to the Alligators. It would be sent to a file // or a database. // People theCustomer = new People(); theCustomer.setCreditCompany(creditCo.Text); theCustomer.setPeopleID(txtID.Text); theCustomer.setPeopleName(txtName.Text); theCustomer.setPeopleAddress(txtAddress.Text); theCustomer.setPeopleCity(txtCity.Text); theCustomer.setPeopleState(txtState.Text); theCustomer.setPeopleZipCode(txtZip.Text); string theOrderedDate = dateOrdered.ToString(); string theGameDate = dateGame.ToString(); // Below this point would be the preparation of the other data to be sent // to the Aligators as well. // ClearForm(); } private void btnClear_Click(object sender, System.EventArgs e) { ClearForm(); } private void btnCheck_Click(object sender, System.EventArgs e) { decimal theAmount = 0.00m; theAmount += Convert.ToDecimal(txtNoTickets.Text)*75.00m; theAmount += Convert.ToDecimal(txtNoJersey.Text)*50.00m;
file:///D|/1/final/BBL0116.html (91 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
if(chkCap.Checked) theAmount += 15.00m; if(rBtn15.Checked) theAmount += 0.00m; else if(rBtn10.Checked) theAmount += 5.00m; else theAmount += 10.00m; txtAmount.Text = String.Format("{0:c}",theAmount); } } }
// program_id People.cs // written_by don voils // date_written 1/3/2006 // description This file contains the definition of the class: People namespace thePeople { public class People { private string CreditCompany; private string PeopleID; private string PeopleName; private string PeopleAddress; private string PeopleCity; private string PeopleState; private string PeopleZipCode; public string TheCompany { get { return CreditCompany; } set { CreditCompany = value; } } public string TheID { get { return PeopleID; } set { PeopleID = value; } } public string TheName { get { return PeopleName; } set { PeopleName = value; } } public string TheAddress { get { return PeopleAddress; } set
file:///D|/1/final/BBL0116.html (92 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ PeopleAddress = value; } } public string TheCity { get { return PeopleCity; } set { PeopleCity = value; } } public string TheState { get { return PeopleState; } set { PeopleState = value; } } public string TheZipCode { get { return PeopleZipCode; } set { PeopleZipCode = value; } } public override string ToString() { string theValue = "Credit Card:" + TheCompany + "\n" + "ID: " + TheID + "\n" + "Name: " + TheName + "\n" + "Address: " + TheAddress + "\n" + "City: " + TheCity + "\n" + "State: " + TheState + "\n" + "Zip: " + TheZipCode + "\n"; return theValue; } } }
// ProfitandLoss.Designer.cs // namespace Accounting { partial class ProfitandLoss { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) {
file:///D|/1/final/BBL0116.html (93 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (ProfitandLoss)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.plFileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.plOpenMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.plPrintMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.plExitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.plFileMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(592, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // plFileMenuItem // this.plFileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.plOpenMenuItem, this.toolStripMenuItem2, this.plPrintMenuItem, this.toolStripMenuItem1, this.plExitMenuItem}); this.plFileMenuItem.Name = "plFileMenuItem"; this.plFileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.plFileMenuItem.Size = new System.Drawing.Size(35, 20); this.plFileMenuItem.Text = "&File"; // // plOpenMenuItem // this.plOpenMenuItem.Name = "plOpenMenuItem"; this.plOpenMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.plOpenMenuItem.Size = new System.Drawing.Size(151, 22); this.plOpenMenuItem.Text = "&Open"; // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(148, 6); // // plPrintMenuItem // this.plPrintMenuItem.Name = "plPrintMenuItem"; this.plPrintMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.plPrintMenuItem.Size = new System.Drawing.Size(151, 22); this.plPrintMenuItem.Text = "&Print"; // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(148, 6); // // plExitMenuItem
file:///D|/1/final/BBL0116.html (94 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.plExitMenuItem.Name = "plExitMenuItem"; this.plExitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.plExitMenuItem.Size = new System.Drawing.Size(151, 22); this.plExitMenuItem.Text = "E&xit"; this.plExitMenuItem.Click += new System.EventHandler(this.plExitMenuItem_Click); // // ProfitandLoss // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(592, 572); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.MaximumSize = new System.Drawing.Size(600, 600); this.MinimumSize = new System.Drawing.Size(600, 600); this.Name = "ProfitandLoss"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Profit and Loss"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem plFileMenuItem; private System.Windows.Forms.ToolStripMenuItem plOpenMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem plPrintMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem plExitMenuItem; } }
// program_id ProfitandLoss.cs // written_by don voils // date_written 1/20/2005 // description This file is a subfile of the program: Accounting.cs // It is a subform to the file: Form1.cs // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace Accounting { /// <summary> /// Summary description for ProfitandLoss. /// public class ProfitandLoss : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu ProfitandLossMenu; private System.Windows.Forms.MenuItem menuItem3; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem PLFileMenuItem; private System.Windows.Forms.MenuItem PLOpenMenuItem; private System.Windows.Forms.MenuItem PLPrintMenuItem; private System.Windows.Forms.MenuItem PLExitMenuItem; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public ProfitandLoss() { // // Required for Windows Form Designer support
file:///D|/1/final/BBL0116.html (95 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.ProfitandLossMenu = new System.Windows.Forms.MainMenu(); this.PLFileMenuItem = new System.Windows.Forms.MenuItem(); this.PLOpenMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.PLPrintMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.PLExitMenuItem = new System.Windows.Forms.MenuItem(); // // ProfitandLossMenu // this.ProfitandLossMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.PLFileMenuItem}); // // PLFileMenuItem // this.PLFileMenuItem.Index = 0; this.PLFileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.PLOpenMenuItem, this.menuItem3, this.PLPrintMenuItem, this.menuItem5, this.PLExitMenuItem}); this.PLFileMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF; this.PLFileMenuItem.Text = "&File"; // // PLOpenMenuItem // this.PLOpenMenuItem.Index = 0; this.PLOpenMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF; this.PLOpenMenuItem.Text = "&Open"; // // menuItem3 // this.menuItem3.Index = 1; this.menuItem3.Text = "-"; // // PLPrintMenuItem // this.PLPrintMenuItem.Index = 2; this.PLPrintMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlP; this.PLPrintMenuItem.Text = "&Print"; // // menuItem5 //
file:///D|/1/final/BBL0116.html (96 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.menuItem5.Index = 3; this.menuItem5.Text = "-"; // // PLExitMenuItem // this.PLExitMenuItem.Index = 4; this.PLExitMenuItem.Shortcut = System.Windows.Forms.Shortcut.AltF4; this.PLExitMenuItem.Text = "E&xit"; this.PLExitMenuItem.Click += new System.EventHandler(this.PLExitMenuItem_Click); // // ProfitandLoss // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(592, 541); this.Menu = this.ProfitandLossMenu; this.Name = "ProfitandLoss"; this.Text = "ProfitandLoss"; } #endregion private void PLExitMenuItem_Click(object sender, System.EventArgs e) { Close(); } } }
// ProfitandLoss.cs // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Accounting { public partial class ProfitandLoss : Form { public ProfitandLoss() { InitializeComponent(); } private void plExitMenuItem_Click(object sender, EventArgs e) { Close(); } } }
// Sales.Designer.cs //
namespace Accounting { partial class Sales { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) {
file:///D|/1/final/BBL0116.html (97 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Sales)); this.salesMenu = new System.Windows.Forms.MenuStrip(); this.sFileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sNewMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sOpenMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.sSaveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.sPrintMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.sExitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.salesMenu.SuspendLayout(); this.SuspendLayout(); // // salesMenu // this.salesMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sFileMenuItem}); this.salesMenu.Location = new System.Drawing.Point(0, 0); this.salesMenu.Name = "salesMenu"; this.salesMenu.Size = new System.Drawing.Size(592, 24); this.salesMenu.TabIndex = 0; this.salesMenu.Text = "menuStrip1"; // // sFileMenuItem // this.sFileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sNewMenuItem, this.sOpenMenuItem, this.toolStripMenuItem1, this.sSaveMenuItem, this.toolStripMenuItem3, this.sPrintMenuItem, this.toolStripMenuItem4, this.sExitMenuItem}); this.sFileMenuItem.Name = "sFileMenuItem"; this.sFileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.sFileMenuItem.Size = new System.Drawing.Size(35, 20); this.sFileMenuItem.Text = "&File"; // // sNewMenuItem // this.sNewMenuItem.Name = "sNewMenuItem"; this.sNewMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.sNewMenuItem.Size = new System.Drawing.Size(151, 22); this.sNewMenuItem.Text = "&New"; // // sOpenMenuItem // this.sOpenMenuItem.Name = "sOpenMenuItem"; this.sOpenMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.sOpenMenuItem.Size = new System.Drawing.Size(151, 22); this.sOpenMenuItem.Text = "&Open"; // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(148, 6); // // sSaveMenuItem
file:///D|/1/final/BBL0116.html (98 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.sSaveMenuItem.Name = "sSaveMenuItem"; this.sSaveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.sSaveMenuItem.Size = new System.Drawing.Size(151, 22); this.sSaveMenuItem.Text = "&Save"; // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(148, 6); // // sPrintMenuItem // this.sPrintMenuItem.Name = "sPrintMenuItem"; this.sPrintMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.sPrintMenuItem.Size = new System.Drawing.Size(151, 22); this.sPrintMenuItem.Text = "&Print"; // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(148, 6); // // sExitMenuItem // this.sExitMenuItem.Name = "sExitMenuItem"; this.sExitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.sExitMenuItem.Size = new System.Drawing.Size(151, 22); this.sExitMenuItem.Text = "E&xit"; this.sExitMenuItem.Click += new System.EventHandler(this.sExitMenuItem_Click); // // Sales // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(592, 572); this.Controls.Add(this.salesMenu); this.MainMenuStrip = this.salesMenu; this.MaximumSize = new System.Drawing.Size(600, 600); this.MinimumSize = new System.Drawing.Size(600, 600); this.Name = "Sales"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Sales"; this.salesMenu.ResumeLayout(false); this.salesMenu.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip salesMenu; private System.Windows.Forms.ToolStripMenuItem sFileMenuItem; private System.Windows.Forms.ToolStripMenuItem sNewMenuItem; private System.Windows.Forms.ToolStripMenuItem sOpenMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem sSaveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem sPrintMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem sExitMenuItem; } }
// program_id Sales.cs // written_by don voils // date_written 1/20/2005 // description This file is a subfile of the program: Accounting.cs // It is a subform to the file: Form1.cs // using System;
file:///D|/1/final/BBL0116.html (99 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace Accounting { /// <summary> /// Summary description for Sales. /// public class Sales : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu SalesMenu; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem menuItem7; private System.Windows.Forms.MenuItem SFileMenuItem; private System.Windows.Forms.MenuItem SNewMenuItem; private System.Windows.Forms.MenuItem SOpenMenuItem; private System.Windows.Forms.MenuItem SSaveMenuItem; private System.Windows.Forms.MenuItem SPrintMenuItem; private System.Windows.Forms.MenuItem SExitMenuItem; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Sales() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.SalesMenu = new System.Windows.Forms.MainMenu(); this.SFileMenuItem = new System.Windows.Forms.MenuItem(); this.SNewMenuItem = new System.Windows.Forms.MenuItem(); this.SOpenMenuItem = new System.Windows.Forms.MenuItem(); this.SSaveMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.SPrintMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem7 = new System.Windows.Forms.MenuItem(); this.SExitMenuItem = new System.Windows.Forms.MenuItem(); // // SalesMenu // this.SalesMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.SFileMenuItem}); // // SFileMenuItem
file:///D|/1/final/BBL0116.html (100 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.SFileMenuItem.Index = 0; this.SFileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.SNewMenuItem, this.SOpenMenuItem, this.SSaveMenuItem, this.menuItem5, this.SPrintMenuItem, this.menuItem7, this.SExitMenuItem}); this.SFileMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF; this.SFileMenuItem.Text = "&File"; // // SNewMenuItem // this.SNewMenuItem.Index = 0; this.SNewMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlN; this.SNewMenuItem.Text = "&New"; // // SOpenMenuItem // this.SOpenMenuItem.Index = 1; this.SOpenMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlO; this.SOpenMenuItem.Text = "&Open"; // // SSaveMenuItem // this.SSaveMenuItem.Index = 2; this.SSaveMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlS; this.SSaveMenuItem.Text = "&Save"; // // menuItem5 // this.menuItem5.Index = 3; this.menuItem5.Text = "-"; // // SPrintMenuItem // this.SPrintMenuItem.Index = 4; this.SPrintMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlP; this.SPrintMenuItem.Text = "&Print"; // // menuItem7 // this.menuItem7.Index = 5; this.menuItem7.Text = "-"; // // SExitMenuItem // this.SExitMenuItem.Index = 6; this.SExitMenuItem.Shortcut = System.Windows.Forms.Shortcut.AltF4; this.SExitMenuItem.Text = "E&xit"; this.SExitMenuItem.Click += new System.EventHandler(this.SExitMenuItem_Click); // // Sales // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(592, 541); this.Menu = this.SalesMenu; this.Name = "Sales"; this.Text = "Sales"; } #endregion private void SExitMenuItem_Click(object sender, System.EventArgs e) { Close(); } } }
// Sales.cs //
file:///D|/1/final/BBL0116.html (101 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Accounting { public partial class Sales : Form { public Sales() { InitializeComponent(); } private void sExitMenuItem_Click(object sender, EventArgs e) { Close(); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 8/17/2006 // date_modified 9/19/2006 // description This file along the the file: Form1.cs // and Program.cs create a Windows program that // implements a program to handle invoices entry. // // This modification includes the addtion // of a menu bar and a status bar. namespace Invoices { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.txtID = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.btnEnter = new System.Windows.Forms.Button();
file:///D|/1/final/BBL0116.html (102 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.btnDisplay = new System.Windows.Forms.Button(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnClear = new System.Windows.Forms.Button(); this.MainMenu = new System.Windows.Forms.MenuStrip(); this.fileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.saveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.printMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.exitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.printDocument = new System.Drawing.Printing.PrintDocument(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.statusbarMessages = new System.Windows.Forms.ToolStripStatusLabel(); this.MainMenu.SuspendLayout(); this.statusStrip.SuspendLayout(); this.SuspendLayout(); // // txtID // this.txtID.Location = new System.Drawing.Point(250, 50); this.txtID.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(110, 27); this.txtID.TabIndex = 1; // // txtNumber // this.txtNumber.Location = new System.Drawing.Point(710, 50); this.txtNumber.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(110, 27); this.txtNumber.TabIndex = 3; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(710, 80); this.txtPrice.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(110, 27); this.txtPrice.TabIndex = 4; // // txtName // this.txtName.Location = new System.Drawing.Point(250, 80); this.txtName.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(146, 27); this.txtName.TabIndex = 2; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(35, 50); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(179, 20); this.label1.TabIndex = 5; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(35, 80); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(129, 20); this.label2.TabIndex = 6; this.label2.Text = "Product Name"; //
file:///D|/1/final/BBL0116.html (103 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(420, 50); this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(259, 20); this.label3.TabIndex = 7; this.label3.Text = "Number of Items Purchased"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(530, 80); this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(149, 20); this.label4.TabIndex = 8; this.label4.Text = "Price per Item"; // // btnEnter // this.btnEnter.Location = new System.Drawing.Point(35, 150); this.btnEnter.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(125, 25); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnDisplay // this.btnDisplay.Location = new System.Drawing.Point(32, 212); this.btnDisplay.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(175, 25); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 265); this.txtDisplayInvoice.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(840, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnClear // this.btnClear.Location = new System.Drawing.Point(475, 179); this.btnClear.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(160, 25); this.btnClear.TabIndex = 10; this.btnClear.Text = "Clear Invoice"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // MainMenu // this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileMenuItem}); this.MainMenu.Location = new System.Drawing.Point(0, 0); this.MainMenu.Name = "MainMenu"; this.MainMenu.Size = new System.Drawing.Size(872, 26); this.MainMenu.TabIndex = 11; this.MainMenu.Text = "menuStrip1"; //
file:///D|/1/final/BBL0116.html (104 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// fileMenuItem // this.fileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newMenuItem, this.openMenuItem, this.toolStripMenuItem1, this.saveMenuItem, this.toolStripMenuItem2, this.printMenuItem, this.toolStripMenuItem3, this.exitMenuItem}); this.fileMenuItem.Name = "fileMenuItem"; this.fileMenuItem.Size = new System.Drawing.Size(40, 22); this.fileMenuItem.Text = "&File"; // // newMenuItem // this.newMenuItem.Name = "newMenuItem"; this.newMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newMenuItem.Size = new System.Drawing.Size(177, 22); this.newMenuItem.Text = "&New"; this.newMenuItem.Click += new System.EventHandler(this.newMenuItem_Click); // // openMenuItem // this.openMenuItem.Name = "openMenuItem"; this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openMenuItem.Size = new System.Drawing.Size(177, 22); this.openMenuItem.Text = "&Open"; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(174, 6); // // saveMenuItem // this.saveMenuItem.Enabled = false; this.saveMenuItem.Name = "saveMenuItem"; this.saveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveMenuItem.Size = new System.Drawing.Size(177, 22); this.saveMenuItem.Text = "&Save"; this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(174, 6); // // printMenuItem // this.printMenuItem.Enabled = false; this.printMenuItem.Name = "printMenuItem"; this.printMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printMenuItem.Size = new System.Drawing.Size(177, 22); this.printMenuItem.Text = "&Print"; this.printMenuItem.Click += new System.EventHandler(this.printMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(174, 6); // // exitMenuItem // this.exitMenuItem.Name = "exitMenuItem"; this.exitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.exitMenuItem.Size = new System.Drawing.Size(177, 22); this.exitMenuItem.Text = "E&xit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt";
file:///D|/1/final/BBL0116.html (105 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.saveFileDialog.InitialDirectory = "c:\\"; this.saveFileDialog.Title = "Invoices"; // // openFileDialog // this.openFileDialog.DefaultExt = "txt"; this.openFileDialog.InitialDirectory = "c:\\"; this.openFileDialog.Title = "Invoice.txt"; // // printDialog // this.printDialog.Document = this.printDocument; this.printDialog.UseEXDialog = true; // // printDocument // this.printDocument.DocumentName = ""; this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printPage); // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.statusbarMessages}); this.statusStrip.Location = new System.Drawing.Point(0, 495); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(872, 22); this.statusStrip.TabIndex = 12; // // statusbarMessages // this.statusbarMessages.Font = new System.Drawing.Font("Arial", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.statusbarMessages.Name = "statusbarMessages"; this.statusbarMessages.Size = new System.Drawing.Size(0, 17); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(872, 517); this.Controls.Add(this.statusStrip); this.Controls.Add(this.btnClear); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.btnEnter); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.txtName); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtID); this.Controls.Add(this.MainMenu); this.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MainMenuStrip = this.MainMenu; this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.MaximumSize = new System.Drawing.Size(880, 550); this.MinimumSize = new System.Drawing.Size(880, 550); this.Name = "Form1"; this.Text = "Status Strip Invoices"; this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtName;
file:///D|/1/final/BBL0116.html (106 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.MenuStrip MainMenu; private System.Windows.Forms.ToolStripMenuItem fileMenuItem; private System.Windows.Forms.ToolStripMenuItem newMenuItem; private System.Windows.Forms.ToolStripMenuItem openMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem printMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem exitMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.PrintDialog printDialog; private System.Drawing.Printing.PrintDocument printDocument; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ToolStripStatusLabel statusbarMessages; } }
// program_id Form1.cs // written_by don voils // date_written 8/17/2006 // date_modified 9/19/2006 // description This file along the the file: Form1.Designer.cs // and Program.cs create a Windows program that // implements a program to handle invoices entry. // // This modification includes the addtion // of a menu bar and a status bar. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO; namespace Invoices { public partial class Form1 : Form { private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList(); private double InvoiceTotal = 0.00; public Form1() { InitializeComponent(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; txtID.Focus(); } private void ClearBoxes()
file:///D|/1/final/BBL0116.html (107 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); txtDisplayInvoice.Clear(); } private void btnEnter_Click(object sender, EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); statusbarMessages.ForeColor = Color.Black; InvoiceTotal += double.Parse(txtNumber.Text) * double.Parse(txtPrice.Text); statusbarMessages.Text = string.Format("Number Invoice Items:"+ "{0} Invoice Total: {1:c}", productID.Count,InvoiceTotal); btnDisplay.Enabled = true; btnClear.Enabled = true; ClearBoxes(); txtID.Focus(); } private void btnDisplay_Click(object sender, EventArgs e) { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { theOutput += String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index])) + "\r\n"; invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } txtDisplayInvoice.Text = theOutput + "\r\n" + String.Format("{0,-20}", "Total:") + String.Format("{0,60:c}", invoiceTotal); } private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); saveMenuItem.Enabled = false; printMenuItem.Enabled = false; statusbarMessages.Text = ""; } private void exitMenuItem_Click(object sender, EventArgs e) { Application.Exit(); }
file:///D|/1/final/BBL0116.html (108 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private void newMenuItem_Click(object sender, EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; btnEnter.Enabled = true; txtID.Focus(); } private void saveMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); // used to find the number of elements in each // of the arrays. int numberItems = productID.Count; // loops through each array and extracts the // elements and then writes them to the file. // for (int index = 0; index < numberItems; ++index) { fileWriter.WriteLine(String.Format("{0}", productID[index])); fileWriter.WriteLine(String.Format("{0}", productName[index])); fileWriter.WriteLine(String.Format("{0}", numberOrdered[index])); fileWriter.WriteLine(String.Format("{0}", itemPrice[index])); } // closes the file to empty the output buffer. // fileWriter.Close(); // sends a message to the user that the file // has beensaved. // MessageBox.Show("Invoice details were saved", "Saved"); // clears all of the textboxes and the listbox. // ClearBoxes(); // clears the data from the arrays so that they are // empty in case // the user wants to work on another invoice. // productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); // disables all of the textboxes and the listbox // and the bottons // txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Clear(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for save and print since // there is no more data contained in memory. //
file:///D|/1/final/BBL0116.html (109 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
saveMenuItem.Enabled = false; printMenuItem.Enabled = false; } } private void openMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while (theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void printMenuItem_Click(object sender, EventArgs e) { if (productID.Count != 0) { DialogResult buttonClicked = printDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { printDocument.Print(); } } else MessageBox.Show("There is no data to be printed", "Error"); } private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { StringBuilder data = new StringBuilder(); StringWriter writer = new StringWriter(data); writer.WriteLine("Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"); decimal invoiceTotal = 0.00m; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) {
file:///D|/1/final/BBL0116.html (110 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
writer.WriteLine(String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]))); invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } writer.WriteLine("\r\n" + String.Format("{0,-20}", "Total:") + String.Format("{0,60:c}", invoiceTotal)); writer.Close(); float leftMargin = e.MarginBounds.Left; float topMargin = e.MarginBounds.Top; float yPos = 0; Font printFont = null; printFont = new Font("Courier New", 10); yPos = topMargin + printFont.GetHeight(e.Graphics); e.HasMorePages = false; e.Graphics.DrawString(data.ToString(), printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); } } }
// program_id Program.cs // written_by don voils // date_written 8/17/2006 // date_modified 9/19/2006 // description This file along the the file: Form1.Designer.cs // and Form1.cs create a Windows program that // implements a program to handle invoices entry. // // This modification includes the addtion // of a menu bar and a status bar. using System; using System.Collections.Generic; using System.Windows.Forms; namespace Invoices { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO;
file:///D|/1/final/BBL0116.html (111 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
namespace menuInvoices { public partial class Form1 : Form { private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList(); private double InvoiceTotal = 0.00; public Form1() { InitializeComponent(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; txtID.Focus(); } private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); txtDisplayInvoice.Clear(); } private void btnEnter_Click(object sender, EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); statusbarMessages.ForeColor = Color.Black; InvoiceTotal += double.Parse(txtNumber.Text) * double.Parse(txtPrice.Text); statusbarMessages.Text = string.Format("Number Invoice Items: {0} Invoice Total: {1:c}", productID.Count, InvoiceTotal); btnDisplay.Enabled = true; btnClear.Enabled = true; ClearBoxes(); txtID.Focus(); } private void btnDisplay_Click(object sender, EventArgs e) { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { theOutput += String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index])) + "\r\n"; invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]);
file:///D|/1/final/BBL0116.html (112 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
} txtDisplayInvoice.Text = theOutput + "\r\n" + String.Format("{0,-20}", "Total") + String.Format("{0,60:c}", invoiceTotal); } private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); saveMenuItem.Enabled = false; printMenuItem.Enabled = false; statusbarMessages.Text = ""; } private void exitMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void newMenuItem_Click(object sender, EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; btnEnter.Enabled = true; txtID.Focus(); } private void saveMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); //used to find the number of elements in each // of the arrays. int numberItems = productID.Count; // loops through each array and extracts the // elements and then writes them to the file. // for (int index = 0; index < numberItems; ++index) { fileWriter.WriteLine(String.Format("{0}", productID[index])); fileWriter.WriteLine(String.Format("{0}", productName[index])); fileWriter.WriteLine(String.Format("{0}", numberOrdered[index])); fileWriter.WriteLine(String.Format("{0}", itemPrice[index])); } // closes the file to empty the output buffer. // fileWriter.Close(); // sends a message to the user that the file // has been saved. // MessageBox.Show("Invoice details were saved", "Saved"); // clears all of the textboxes. // ClearBoxes(); // clears the data from the arrays so that they // are empty in case // the user wants to work on another invoice. // productID.Clear();
file:///D|/1/final/BBL0116.html (113 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); // disables all of the textboxes // and the buttons. txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for Save and Print since // there is no more data contained in memory. // saveMenuItem.Enabled = false; printMenuItem.Enabled = false; } } private void openMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { // Clear the arrays and the form of all data. // ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; // Reads the data from the file one // record at a time and then closes // the reader when completed. // string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while (theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void printMenuItem_Click(object sender, EventArgs e) { if (productID.Count != 0) { DialogResult buttonClicked = printDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { printDocument.Print();
file:///D|/1/final/BBL0116.html (114 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
} } else MessageBox.Show("There was no data to be printed.", "Error"); } private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { StringBuilder data = new StringBuilder(); StringWriter writer = new StringWriter(data); writer.WriteLine("Producet ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"); decimal invoiceTotal = 0.00m; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { writer.WriteLine(String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]))); invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } writer.WriteLine("\r\n" + String.Format("{0,-20}", "Total") + String.Format("{0,60:c}", invoiceTotal)); writer.Close(); float leftMargin = e.MarginBounds.Left; float topMargin = e.MarginBounds.Top; float yPos = 0; Font printFont = null; printFont = new Font("Courier New", 10); yPos = topMargin + printFont.GetHeight(e.Graphics); e.HasMorePages = false; e.Graphics.DrawString(data.ToString(), printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); } } }
namespace menuInvoices { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); }
file:///D|/1/final/BBL0116.html (115 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnDisplay = new System.Windows.Forms.Button(); this.MainMenu = new System.Windows.Forms.MenuStrip(); this.fileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.saveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.printMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.exitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.printDocument = new System.Drawing.Printing.PrintDocument(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.statusbarMessages = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripMessages = new System.Windows.Forms.ToolStripStatusLabel(); this.MainMenu.SuspendLayout(); this.statusStrip.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.Location = new System.Drawing.Point(27, 49); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(179, 20); this.label1.TabIndex = 0; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.Location = new System.Drawing.Point(27, 98); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(129, 20); this.label2.TabIndex = 1; this.label2.Text = "Product Name"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label3.Location = new System.Drawing.Point(394, 46); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(259, 20); this.label3.TabIndex = 2;
file:///D|/1/final/BBL0116.html (116 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label3.Text = "Number of Items Purchased"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.Location = new System.Drawing.Point(394, 98); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(149, 20); this.label4.TabIndex = 3; this.label4.Text = "Price per Item"; // // txtID // this.txtID.Location = new System.Drawing.Point(212, 43); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(100, 26); this.txtID.TabIndex = 1; // // txtName // this.txtName.Location = new System.Drawing.Point(212, 92); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(156, 26); this.txtName.TabIndex = 2; // // txtNumber // this.txtNumber.Location = new System.Drawing.Point(717, 43); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(100, 26); this.txtNumber.TabIndex = 3; this.txtNumber.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(717, 92); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(100, 26); this.txtPrice.TabIndex = 4; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 267); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(860, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnEnter.Location = new System.Drawing.Point(61, 160); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(172, 23); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnClear // this.btnClear.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnClear.Location = new System.Drawing.Point(501, 195); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(177, 23); this.btnClear.TabIndex = 7; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Invoice";
file:///D|/1/final/BBL0116.html (117 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnDisplay // this.btnDisplay.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnDisplay.Location = new System.Drawing.Point(61, 224); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(172, 23); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // MainMenu // this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileMenuItem}); this.MainMenu.Location = new System.Drawing.Point(0, 0); this.MainMenu.Name = "MainMenu"; this.MainMenu.Size = new System.Drawing.Size(892, 26); this.MainMenu.TabIndex = 8; this.MainMenu.Text = "menuStrip1"; // // fileMenuItem // this.fileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newMenuItem, this.openMenuItem, this.toolStripMenuItem1, this.saveMenuItem, this.toolStripMenuItem3, this.printMenuItem, this.toolStripMenuItem4, this.exitMenuItem}); this.fileMenuItem.Name = "fileMenuItem"; this.fileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.fileMenuItem.Size = new System.Drawing.Size(40, 22); this.fileMenuItem.Text = "&File"; // // newMenuItem // this.newMenuItem.Name = "newMenuItem"; this.newMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newMenuItem.Size = new System.Drawing.Size(177, 22); this.newMenuItem.Text = "&New"; this.newMenuItem.Click += new System.EventHandler(this.newMenuItem_Click); // // openMenuItem // this.openMenuItem.Name = "openMenuItem"; this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openMenuItem.Size = new System.Drawing.Size(177, 22); this.openMenuItem.Text = "&Open"; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(174, 6); // // saveMenuItem // this.saveMenuItem.Enabled = false; this.saveMenuItem.Name = "saveMenuItem"; this.saveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveMenuItem.Size = new System.Drawing.Size(177, 22); this.saveMenuItem.Text = "&Save"; this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3";
file:///D|/1/final/BBL0116.html (118 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.toolStripMenuItem3.Size = new System.Drawing.Size(174, 6); // // printMenuItem // this.printMenuItem.Enabled = false; this.printMenuItem.Name = "printMenuItem"; this.printMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printMenuItem.Size = new System.Drawing.Size(177, 22); this.printMenuItem.Text = "&Print"; this.printMenuItem.Click += new System.EventHandler(this.printMenuItem_Click); // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(174, 6); // // exitMenuItem // this.exitMenuItem.Name = "exitMenuItem"; this.exitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.exitMenuItem.Size = new System.Drawing.Size(177, 22); this.exitMenuItem.Text = "E&xit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt"; this.saveFileDialog.InitialDirectory = "C:\\"; this.saveFileDialog.Title = "Invoices"; // // openFileDialog // this.openFileDialog.DefaultExt = "txt"; this.openFileDialog.InitialDirectory = "C:\\"; this.openFileDialog.Title = "Invoices.txt"; // // printDialog // this.printDialog.Document = this.printDocument; this.printDialog.UseEXDialog = true; // // printDocument // this.printDocument.DocumentName = ""; this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printPage); // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.statusbarMessages, this.toolStripMessages}); this.statusStrip.Location = new System.Drawing.Point(0, 495); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(892, 22); this.statusStrip.TabIndex = 9; // // statusbarMessages // this.statusbarMessages.Font = new System.Drawing.Font("Arial", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.statusbarMessages.Name = "statusbarMessages"; this.statusbarMessages.Size = new System.Drawing.Size(0, 17); // // toolStripMessages // this.toolStripMessages.Name = "toolStripMessages"; this.toolStripMessages.Size = new System.Drawing.Size(0, 17); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(892, 517); this.Controls.Add(this.statusStrip); this.Controls.Add(this.btnDisplay);
file:///D|/1/final/BBL0116.html (119 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.Controls.Add(this.btnClear); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.MainMenu); this.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MainMenuStrip = this.MainMenu; this.Margin = new System.Windows.Forms.Padding(4); this.MaximumSize = new System.Drawing.Size(900, 550); this.MinimumSize = new System.Drawing.Size(900, 550); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Status Strip Invoices"; this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.MenuStrip MainMenu; private System.Windows.Forms.ToolStripMenuItem fileMenuItem; private System.Windows.Forms.ToolStripMenuItem newMenuItem; private System.Windows.Forms.ToolStripMenuItem openMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem printMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem exitMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.PrintDialog printDialog; private System.Drawing.Printing.PrintDocument printDocument; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ToolStripStatusLabel statusbarMessages; private System.Windows.Forms.ToolStripStatusLabel toolStripMessages; } }
using System; using System.Collections.Generic; using System.Windows.Forms; namespace menuInvoices { static class Program { /// <summary> /// The main entry point for the application. ///
file:///D|/1/final/BBL0116.html (120 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Form1.cs // written_by don voils // date_written 10/13/2006 // description This file along with Form1.Designer.cs // and Program.cs add a status strip to // the Menu Invoices program. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO;
namespace menuInvoices { public partial class Form1 : Form { private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList(); private double InvoiceTotal = 0.00; public Form1() { InitializeComponent(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; txtID.Focus(); } private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); txtDisplayInvoice.Clear(); } private void btnEnter_Click(object sender, EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); statusbarMessages.ForeColor = Color.Black; InvoiceTotal += double.Parse(txtNumber.Text) * double.Parse(txtPrice.Text); statusbarMessages.Text = string.Format("Number Invoice Items: {0} Invoice Total: {1:c}", productID.Count, InvoiceTotal); btnDisplay.Enabled = true;
file:///D|/1/final/BBL0116.html (121 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
btnClear.Enabled = true; ClearBoxes(); txtID.Focus(); } private void btnDisplay_Click(object sender, EventArgs e) { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { theOutput += String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index])) + "\r\n"; invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } txtDisplayInvoice.Text = theOutput + "\r\n" + String.Format("{0,-20}", "Total") + String.Format("{0,60:c}", invoiceTotal); } private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); saveMenuItem.Enabled = false; printMenuItem.Enabled = false; statusbarMessages.Text = ""; } private void exitMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void newMenuItem_Click(object sender, EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; btnEnter.Enabled = true; txtID.Focus(); } private void saveMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); //used to find the number of elements in each // of the arrays. int numberItems = productID.Count;
file:///D|/1/final/BBL0116.html (122 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// loops through each array and extracts the // elements and then writes them to the file. // for (int index = 0; index < numberItems; ++index) { fileWriter.WriteLine(String.Format("{0}", productID[index])); fileWriter.WriteLine(String.Format("{0}", productName[index])); fileWriter.WriteLine(String.Format("{0}", numberOrdered[index])); fileWriter.WriteLine(String.Format("{0}", itemPrice[index])); } // closes the file to empty the output buffer. // fileWriter.Close(); // sends a message to the user that the file // has been saved. // MessageBox.Show("Invoice details were saved", "Saved"); // clears all of the textboxes. // ClearBoxes(); // clears the data from the arrays so that they // are empty in case // the user wants to work on another invoice. // productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); // disables all of the textboxes // and the buttons. txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for Save and Print since // there is no more data contained in memory. // saveMenuItem.Enabled = false; printMenuItem.Enabled = false; } } private void openMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { // Clear the arrays and the form of all data. // ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; // Reads the data from the file one
file:///D|/1/final/BBL0116.html (123 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// record at a time and then closes // the reader when completed. // string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while (theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void printMenuItem_Click(object sender, EventArgs e) { if (productID.Count != 0) { DialogResult buttonClicked = printDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { printDocument.Print(); } } else MessageBox.Show("There was no data to be printed.", "Error"); } private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { StringBuilder data = new StringBuilder(); StringWriter writer = new StringWriter(data); writer.WriteLine("Producet ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"); decimal invoiceTotal = 0.00m; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { writer.WriteLine(String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]))); invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } writer.WriteLine("\r\n" + String.Format("{0,-20}", "Total") + String.Format("{0,60:c}", invoiceTotal)); writer.Close(); float leftMargin = e.MarginBounds.Left; float topMargin = e.MarginBounds.Top; float yPos = 0; Font printFont = null; printFont = new Font("Courier New", 10); yPos = topMargin + printFont.GetHeight(e.Graphics); e.HasMorePages = false; e.Graphics.DrawString(data.ToString(),
file:///D|/1/final/BBL0116.html (124 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 10/13/2006 // description This file along with Form1.cs // and Program.cs add a status strip to // the Menu Invoices program. // namespace menuInvoices { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnDisplay = new System.Windows.Forms.Button(); this.MainMenu = new System.Windows.Forms.MenuStrip(); this.fileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.saveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.printMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.exitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.printDocument = new System.Drawing.Printing.PrintDocument(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.statusbarMessages = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripMessages = new System.Windows.Forms.ToolStripStatusLabel();
file:///D|/1/final/BBL0116.html (125 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.MainMenu.SuspendLayout(); this.statusStrip.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.Location = new System.Drawing.Point(27, 49); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(179, 20); this.label1.TabIndex = 0; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.Location = new System.Drawing.Point(27, 98); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(129, 20); this.label2.TabIndex = 1; this.label2.Text = "Product Name"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label3.Location = new System.Drawing.Point(394, 46); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(259, 20); this.label3.TabIndex = 2; this.label3.Text = "Number of Items Purchased"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.Location = new System.Drawing.Point(394, 98); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(149, 20); this.label4.TabIndex = 3; this.label4.Text = "Price per Item"; // // txtID // this.txtID.Location = new System.Drawing.Point(212, 43); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(100, 26); this.txtID.TabIndex = 1; // // txtName // this.txtName.Location = new System.Drawing.Point(212, 92); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(156, 26); this.txtName.TabIndex = 2; // // txtNumber // this.txtNumber.Location = new System.Drawing.Point(717, 43); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(100, 26); this.txtNumber.TabIndex = 3; this.txtNumber.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(717, 92); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(100, 26);
file:///D|/1/final/BBL0116.html (126 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtPrice.TabIndex = 4; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 267); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(860, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.btnEnter.Location = new System.Drawing.Point(61, 160); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(172, 23); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnClear // this.btnClear.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.btnClear.Location = new System.Drawing.Point(501, 195); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(177, 23); this.btnClear.TabIndex = 7; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Invoice"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnDisplay // this.btnDisplay.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnDisplay.Location = new System.Drawing.Point(61, 224); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(172, 23); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // MainMenu // this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileMenuItem}); this.MainMenu.Location = new System.Drawing.Point(0, 0); this.MainMenu.Name = "MainMenu"; this.MainMenu.Size = new System.Drawing.Size(892, 26); this.MainMenu.TabIndex = 8; this.MainMenu.Text = "menuStrip1"; // // fileMenuItem // this.fileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newMenuItem, this.openMenuItem, this.toolStripMenuItem1, this.saveMenuItem, this.toolStripMenuItem3, this.printMenuItem, this.toolStripMenuItem4, this.exitMenuItem}); this.fileMenuItem.Name = "fileMenuItem"; this.fileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.fileMenuItem.Size = new System.Drawing.Size(40, 22);
file:///D|/1/final/BBL0116.html (127 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.fileMenuItem.Text = "&File"; // // newMenuItem // this.newMenuItem.Name = "newMenuItem"; this.newMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newMenuItem.Size = new System.Drawing.Size(177, 22); this.newMenuItem.Text = "&New"; this.newMenuItem.Click += new System.EventHandler(this.newMenuItem_Click); // // openMenuItem // this.openMenuItem.Name = "openMenuItem"; this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openMenuItem.Size = new System.Drawing.Size(177, 22); this.openMenuItem.Text = "&Open"; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(174, 6); // // saveMenuItem // this.saveMenuItem.Enabled = false; this.saveMenuItem.Name = "saveMenuItem"; this.saveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveMenuItem.Size = new System.Drawing.Size(177, 22); this.saveMenuItem.Text = "&Save"; this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(174, 6); // // printMenuItem // this.printMenuItem.Enabled = false; this.printMenuItem.Name = "printMenuItem"; this.printMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printMenuItem.Size = new System.Drawing.Size(177, 22); this.printMenuItem.Text = "&Print"; this.printMenuItem.Click += new System.EventHandler(this.printMenuItem_Click); // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(174, 6); // // exitMenuItem // this.exitMenuItem.Name = "exitMenuItem"; this.exitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.exitMenuItem.Size = new System.Drawing.Size(177, 22); this.exitMenuItem.Text = "E&xit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt"; this.saveFileDialog.InitialDirectory = "C:\\"; this.saveFileDialog.Title = "Invoices"; // // openFileDialog // this.openFileDialog.DefaultExt = "txt"; this.openFileDialog.InitialDirectory = "C:\\"; this.openFileDialog.Title = "Invoices.txt"; // // printDialog // this.printDialog.Document = this.printDocument; this.printDialog.UseEXDialog = true;
file:///D|/1/final/BBL0116.html (128 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// // printDocument // this.printDocument.DocumentName = ""; this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printPage); // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.statusbarMessages, this.toolStripMessages}); this.statusStrip.Location = new System.Drawing.Point(0, 495); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(892, 22); this.statusStrip.TabIndex = 9; // // statusbarMessages // this.statusbarMessages.Font = new System.Drawing.Font("Arial", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.statusbarMessages.Name = "statusbarMessages"; this.statusbarMessages.Size = new System.Drawing.Size(0, 17); // // toolStripMessages // this.toolStripMessages.Name = "toolStripMessages"; this.toolStripMessages.Size = new System.Drawing.Size(0, 17); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(892, 517); this.Controls.Add(this.statusStrip); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.MainMenu); this.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MainMenuStrip = this.MainMenu; this.Margin = new System.Windows.Forms.Padding(4); this.MaximumSize = new System.Drawing.Size(900, 550); this.MinimumSize = new System.Drawing.Size(900, 550); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Status Strip Invoices"; this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnClear;
file:///D|/1/final/BBL0116.html (129 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.MenuStrip MainMenu; private System.Windows.Forms.ToolStripMenuItem fileMenuItem; private System.Windows.Forms.ToolStripMenuItem newMenuItem; private System.Windows.Forms.ToolStripMenuItem openMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem printMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem exitMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog DopenFileDialog; private System.Windows.Forms.PrintDialog printDialog; private System.Drawing.Printing.PrintDocument printDocument; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ToolStripStatusLabel statusbarMessages; private System.Windows.Forms.ToolStripStatusLabel toolStripMessages; } }
// program_id Program.cs // written_by don voils // date_written 10/13/2006 // description This file along with Form1.Designer.cs // and Form1.cs add a status strip to // the Menu Invoices program. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace menuInvoices { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Form1.Designer.cs // written_by don Voils // date_written 8/25/2006 // description This file along with Program.cs, Form1.cs, Chalk.jpg and // the class file. People.cs make up the program: theAligator.exe. // namespace theAlligators { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose();
file:///D|/1/final/BBL0116.html (130 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
} base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (Form1)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtAddress = new System.Windows.Forms.TextBox(); this.txtCity = new System.Windows.Forms.TextBox(); this.txtZip = new System.Windows.Forms.TextBox(); this.txtNoTickets = new System.Windows.Forms.TextBox(); this.txtNoJersey = new System.Windows.Forms.TextBox(); this.txtAmount = new System.Windows.Forms.TextBox(); this.dateOrdered = new System.Windows.Forms.DateTimePicker(); this.dateGame = new System.Windows.Forms.DateTimePicker(); this.creditCo = new System.Windows.Forms.ComboBox(); this.txtState = new System.Windows.Forms.ComboBox(); this.txtColor = new System.Windows.Forms.ComboBox(); this.txtSize = new System.Windows.Forms.ComboBox(); this.btnSend = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnCheck = new System.Windows.Forms.Button(); this.shippingGroup = new System.Windows.Forms.GroupBox(); this.rBtn5 = new System.Windows.Forms.RadioButton(); this.rBtn10 = new System.Windows.Forms.RadioButton(); this.rBtn15 = new System.Windows.Forms.RadioButton(); this.chkCap = new System.Windows.Forms.CheckBox(); this.shippingGroup.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(225, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(128, 23); this.label1.TabIndex = 0; this.label1.Text = "Date Ordered"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(20, 45); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(196, 23); this.label2.TabIndex = 1; this.label2.Text = "Customer Information"; // // label3 //
file:///D|/1/final/BBL0116.html (131 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(50, 75); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(111, 23); this.label3.TabIndex = 2; this.label3.Text = "Credit Card"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(50, 105); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(136, 23); this.label4.TabIndex = 3; this.label4.Text = "Credit Number"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(50, 135); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(59, 23); this.label5.TabIndex = 4; this.label5.Text = "Name"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(50, 165); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(78, 23); this.label6.TabIndex = 5; this.label6.Text = "Address"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(50, 195); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(46, 23); this.label7.TabIndex = 6; this.label7.Text = "City"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(50, 227); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(55, 23); this.label8.TabIndex = 7; this.label8.Text = "State"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(50, 255); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(37, 23); this.label9.TabIndex = 8; this.label9.Text = "Zip"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(75, 290); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(145, 23); this.label10.TabIndex = 9; this.label10.Text = "Number Tickets"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(90, 315); this.label11.Name = "label11";
file:///D|/1/final/BBL0116.html (132 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label11.Size = new System.Drawing.Size(109, 23); this.label11.TabIndex = 10; this.label11.Text = "$75.00 each"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(75, 390); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(119, 23); this.label12.TabIndex = 11; this.label12.Text = "Team Jersey"; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(95, 415); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(109, 23); this.label13.TabIndex = 12; this.label13.Text = "$50.00 each"; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(355, 285); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(107, 23); this.label14.TabIndex = 13; this.label14.Text = "Game Date"; // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(285, 380); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(57, 23); this.label15.TabIndex = 14; this.label15.Text = "Color"; // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(430, 380); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(46, 23); this.label16.TabIndex = 15; this.label16.Text = "Size"; // // txtID // this.txtID.Location = new System.Drawing.Point(200, 105); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(140, 30); this.txtID.TabIndex = 3; // // txtName // this.txtName.Location = new System.Drawing.Point(200, 135); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(160, 30); this.txtName.TabIndex = 4; // // txtAddress // this.txtAddress.Location = new System.Drawing.Point(200, 165); this.txtAddress.Name = "txtAddress"; this.txtAddress.Size = new System.Drawing.Size(160, 30); this.txtAddress.TabIndex = 5; // // txtCity // this.txtCity.Location = new System.Drawing.Point(200, 195); this.txtCity.Name = "txtCity"; this.txtCity.Size = new System.Drawing.Size(160, 30);
file:///D|/1/final/BBL0116.html (133 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtCity.TabIndex = 6; // // txtZip // this.txtZip.Location = new System.Drawing.Point(200, 255); this.txtZip.Name = "txtZip"; this.txtZip.Size = new System.Drawing.Size(109, 30); this.txtZip.TabIndex = 8; // // txtNoTickets // this.txtNoTickets.Location = new System.Drawing.Point(230, 310); this.txtNoTickets.Name = "txtNoTickets"; this.txtNoTickets.Size = new System.Drawing.Size(30, 30); this.txtNoTickets.TabIndex = 9; // // txtNoJersey // this.txtNoJersey.Location = new System.Drawing.Point(215, 405); this.txtNoJersey.Name = "txtNoJersey"; this.txtNoJersey.Size = new System.Drawing.Size(30, 30); this.txtNoJersey.TabIndex = 12; // // txtAmount // this.txtAmount.Location = new System.Drawing.Point(455, 520); this.txtAmount.Name = "txtAmount"; this.txtAmount.Size = new System.Drawing.Size(100, 30); this.txtAmount.TabIndex = 23; // // dateOrdered // this.dateOrdered.Location = new System.Drawing.Point(365, 15); this.dateOrdered.Name = "dateOrdered"; this.dateOrdered.Size = new System.Drawing.Size(310, 30); this.dateOrdered.TabIndex = 1; // // dateGame // this.dateGame.Location = new System.Drawing.Point(280, 310); this.dateGame.Name = "dateGame"; this.dateGame.Size = new System.Drawing.Size(310, 30); this.dateGame.TabIndex = 10; // // creditCo // this.creditCo.FormattingEnabled = true; this.creditCo.Items.AddRange(new object[] { "", "Diners", "Master Card", "Visa"}); this.creditCo.Location = new System.Drawing.Point(200, 75); this.creditCo.Name = "creditCo"; this.creditCo.Size = new System.Drawing.Size(170, 31); this.creditCo.TabIndex = 2; // // txtState // this.txtState.FormattingEnabled = true; this.txtState.Items.AddRange(new object[] { "", "AL", "AK", "AR", "AZ", "CA", "CO", "CN", "DE", "FL", "GA", "HI", "IA", "ID", "IN",
file:///D|/1/final/BBL0116.html (134 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
"IL", "LA", "KS", "KY", "MA", "MI", "MN", "MO", "MR", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "TN", "TX", "SC", "SD", "UT", "VA", "VT", "WA", "WI", "WV", "WY"}); this.txtState.Location = new System.Drawing.Point(200, 225); this.txtState.Name = "txtState"; this.txtState.Size = new System.Drawing.Size(55, 31); this.txtState.TabIndex = 7; // // txtColor // this.txtColor.FormattingEnabled = true; this.txtColor.Items.AddRange(new object[] { "", "Red", "Green", "Blue", "Yellow"}); this.txtColor.Location = new System.Drawing.Point(260, 405); this.txtColor.Name = "txtColor"; this.txtColor.Size = new System.Drawing.Size(120, 31); this.txtColor.TabIndex = 13; // // txtSize // this.txtSize.FormattingEnabled = true; this.txtSize.Items.AddRange(new object[] { "", "Small", "Medium", "Large", "Extra Large"}); this.txtSize.Location = new System.Drawing.Point(390, 405); this.txtSize.Name = "txtSize"; this.txtSize.Size = new System.Drawing.Size(150, 31); this.txtSize.TabIndex = 14; // // btnSend // this.btnSend.Location = new System.Drawing.Point(30, 580); this.btnSend.Name = "btnSend"; this.btnSend.Size = new System.Drawing.Size(120, 30); this.btnSend.TabIndex = 32; this.btnSend.TabStop = false;
file:///D|/1/final/BBL0116.html (135 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.btnSend.Text = "Send Order"; this.btnSend.UseVisualStyleBackColor = true; this.btnSend.Click += new System.EventHandler(this.btnSend_Click); // // btnClear // this.btnClear.Location = new System.Drawing.Point(170, 580); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(130, 30); this.btnClear.TabIndex = 33; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Order"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnCheck // this.btnCheck.Location = new System.Drawing.Point(430, 480); this.btnCheck.Name = "btnCheck"; this.btnCheck.Size = new System.Drawing.Size(150, 30); this.btnCheck.TabIndex = 18; this.btnCheck.Text = "Check Amount"; this.btnCheck.UseVisualStyleBackColor = true; this.btnCheck.Click += new System.EventHandler(this.btnCheck_Click); // // shippingGroup // this.shippingGroup.Controls.Add(this.rBtn5); this.shippingGroup.Controls.Add(this.rBtn10); this.shippingGroup.Controls.Add(this.rBtn15); this.shippingGroup.Location = new System.Drawing.Point(110, 450); this.shippingGroup.Name = "shippingGroup"; this.shippingGroup.Size = new System.Drawing.Size(250, 120); this.shippingGroup.TabIndex = 15; this.shippingGroup.TabStop = false; this.shippingGroup.Text = "Select Shipping:"; // // rBtn5 // this.rBtn5.AutoSize = true; this.rBtn5.Location = new System.Drawing.Point(30, 80); this.rBtn5.Name = "rBtn5"; this.rBtn5.Size = new System.Drawing.Size(208, 27); this.rBtn5.TabIndex = 17; this.rBtn5.TabStop = true; this.rBtn5.Text = "5 days $10.00 Charge"; this.rBtn5.UseVisualStyleBackColor = true; // // rBtn10 // this.rBtn10.AutoSize = true; this.rBtn10.Location = new System.Drawing.Point(30, 50); this.rBtn10.Name = "rBtn10"; this.rBtn10.Size = new System.Drawing.Size(208, 27); this.rBtn10.TabIndex = 16; this.rBtn10.TabStop = true; this.rBtn10.Text = "10 days $5.00 Charge"; this.rBtn10.UseVisualStyleBackColor = true; // // rBtn15 // this.rBtn15.AutoSize = true; this.rBtn15.Location = new System.Drawing.Point(30, 20); this.rBtn15.Name = "rBtn15"; this.rBtn15.Size = new System.Drawing.Size(187, 27); this.rBtn15.TabIndex = 15; this.rBtn15.TabStop = true; this.rBtn15.Text = "15 days No Charge"; this.rBtn15.UseVisualStyleBackColor = true; // // chkCap // this.chkCap.AutoSize = true; this.chkCap.Location = new System.Drawing.Point(95, 355); this.chkCap.Name = "chkCap";
file:///D|/1/final/BBL0116.html (136 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.chkCap.Size = new System.Drawing.Size(259, 27); this.chkCap.TabIndex = 11; this.chkCap.Text = "Select a team cap at $15.00"; this.chkCap.UseVisualStyleBackColor = true; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 23F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(692, 637); this.Controls.Add(this.chkCap); this.Controls.Add(this.shippingGroup); this.Controls.Add(this.btnCheck); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnSend); this.Controls.Add(this.txtSize); this.Controls.Add(this.txtColor); this.Controls.Add(this.txtState); this.Controls.Add(this.creditCo); this.Controls.Add(this.dateGame); this.Controls.Add(this.dateOrdered); this.Controls.Add(this.txtAmount); this.Controls.Add(this.txtNoJersey); this.Controls.Add(this.txtNoTickets); this.Controls.Add(this.txtZip); this.Controls.Add(this.txtCity); this.Controls.Add(this.txtAddress); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label16); this.Controls.Add(this.label15); this.Controls.Add(this.label14); this.Controls.Add(this.label13); this.Controls.Add(this.label12); this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(4); this.Name = "Form1"; this.Text = "The Alligators Order Form"; this.shippingGroup.ResumeLayout(false); this.shippingGroup.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label15;
file:///D|/1/final/BBL0116.html (137 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.Label label16; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtAddress; private System.Windows.Forms.TextBox txtCity; private System.Windows.Forms.TextBox txtZip; private System.Windows.Forms.TextBox txtNoTickets; private System.Windows.Forms.TextBox txtNoJersey; private System.Windows.Forms.TextBox txtAmount; private System.Windows.Forms.DateTimePicker dateOrdered; private System.Windows.Forms.DateTimePicker dateGame; private System.Windows.Forms.ComboBox creditCo; private System.Windows.Forms.ComboBox txtState; private System.Windows.Forms.ComboBox txtColor; private System.Windows.Forms.ComboBox txtSize; private System.Windows.Forms.Button btnSend; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnCheck; private System.Windows.Forms.GroupBox shippingGroup; private System.Windows.Forms.RadioButton rBtn10; private System.Windows.Forms.RadioButton rBtn15; private System.Windows.Forms.RadioButton rBtn5; private System.Windows.Forms.CheckBox chkCap; } }
// program_id Form1.cs // written_by don voils // date_written 8/25/2006 // description This file along with Program.cs, Form1.Design.cs, Chalk.jpg and // the class file. People.cs make up the program: theAligator.exe. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using thePeople; namespace theAlligators { public partial class Form1 : Form { public Form1() { InitializeComponent(); ClearForm(); } private void ClearForm() { // Notice that some of the entries may be cleared by // the Clear() method while others may be cleared // by using an empty string or a string with 0 as // a character. // creditCo.Text = " "; txtID.Clear(); txtName.Clear(); txtAddress.Clear(); txtCity.Clear(); txtState.Text = " "; txtZip.Clear(); txtNoTickets.Text = "0"; txtColor.Text = " "; txtSize.Text = " "; txtNoJersey.Text = "0"; txtAmount.Clear(); // Notice that the checkbox and the radio button are reset by // using the Checked attribute and setting it to false. chkCap.Checked = false; rBtn5.Checked = false; rBtn10.Checked = false;
file:///D|/1/final/BBL0116.html (138 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
rBtn15.Checked = false; } private void btnSend_Click(object sender, EventArgs e) { // The following would prepare the People object to be // sent to the Alligators. It would be sent to a file // or a database. // People theCustomer = new People(); theCustomer.TheCompany = creditCo.Text; theCustomer.TheID = txtID.Text ; theCustomer.TheName = txtName.Text; theCustomer.TheAddress = txtAddress.Text; theCustomer.TheCity = txtCity.Text; theCustomer.TheState = txtState.Text; theCustomer.TheZipCode = txtZip.Text; string theOrderedDate = dateOrdered.ToString(); string theGameDate = dateGame.ToString(); // Below this point would be the preparation of the other data // to be sent to the Aligators as well either to a file or to a // database. // ClearForm(); } private void btnClear_Click(object sender, EventArgs e) { ClearForm(); } private void btnCheck_Click(object sender, EventArgs e) { decimal theAmount = 0.00m; theAmount += Convert.ToDecimal(txtNoTickets.Text) * 75.00m; theAmount += Convert.ToDecimal(txtNoJersey.Text) * 50.00m; if (chkCap.Checked) theAmount += 15.00m; if (rBtn5.Checked) theAmount += 10.00m; else if (rBtn10.Checked) theAmount += 5.00m; else theAmount += 0.00m; txtAmount.Text = String.Format("{0:c}", theAmount); } } }
// program_id Program.cs // written_by don Voils // date_written 8/25/2006 // description This file along with Form1.Designer.cs, Form1.cs, Chalk.jpg and // the class file. People.cs make up the program: theAligator.exe. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace theAlligators { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread]
file:///D|/1/final/BBL0116.html (139 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 8/17/2006 // date_modified 9/19/2006 // date_modified 9/20/2006 // description This file along the the file: Form1.cs // and Program.cs create a Windows program that // implements a program to handle invoices entry. // // This modification includes the addition // of a menu bar. // The second modification include the addition // of a tool bar to emulate the menu bar.
namespace Invoices { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (Form1)); this.txtID = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.btnEnter = new System.Windows.Forms.Button(); this.btnDisplay = new System.Windows.Forms.Button(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnClear = new System.Windows.Forms.Button(); this.MainMenu = new System.Windows.Forms.MenuStrip(); this.fileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
file:///D|/1/final/BBL0116.html (140 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.saveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.printMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.exitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.printDocument = new System.Drawing.Printing.PrintDocument(); this.toolStrip = new System.Windows.Forms.ToolStrip(); this.toolStripNew = new System.Windows.Forms.ToolStripButton(); this.toolStripOpen = new System.Windows.Forms.ToolStripButton(); this.toolStripSave = new System.Windows.Forms.ToolStripButton(); this.toolStripPrint = new System.Windows.Forms.ToolStripButton(); this.MainMenu.SuspendLayout(); this.toolStrip.SuspendLayout(); this.SuspendLayout(); // // txtID // this.txtID.Location = new System.Drawing.Point(250, 55); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(110, 23); this.txtID.TabIndex = 1; // // txtNumber // this.txtNumber.Location = new System.Drawing.Point(710, 55); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(110, 23); this.txtNumber.TabIndex = 3; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(710, 85); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(110, 23); this.txtPrice.TabIndex = 4; // // txtName // this.txtName.Location = new System.Drawing.Point(250, 85); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(146, 23); this.txtName.TabIndex = 2; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(50, 55); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 16); this.label1.TabIndex = 5; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(50, 85); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(104, 16); this.label2.TabIndex = 6; this.label2.Text = "Product Name"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(410, 55); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(208, 16); this.label3.TabIndex = 7; this.label3.Text = "Number of Items Purchased"; // // label4 //
file:///D|/1/final/BBL0116.html (141 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(410, 85); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(120, 16); this.label4.TabIndex = 8; this.label4.Text = "Price per Item"; // // btnEnter // this.btnEnter.Location = new System.Drawing.Point(34, 150); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(125, 25); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnDisplay // this.btnDisplay.Location = new System.Drawing.Point(33, 212); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(175, 25); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 265); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(840, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnClear // this.btnClear.Location = new System.Drawing.Point(475, 179); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(160, 25); this.btnClear.TabIndex = 10; this.btnClear.Text = "Clear Invoice"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // MainMenu // this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileMenuItem}); this.MainMenu.Location = new System.Drawing.Point(0, 0); this.MainMenu.Name = "MainMenu"; this.MainMenu.Size = new System.Drawing.Size(872, 24); this.MainMenu.TabIndex = 11; this.MainMenu.Text = "menuStrip1"; // // fileMenuItem // this.fileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newMenuItem, this.openMenuItem, this.toolStripMenuItem1, this.saveMenuItem, this.toolStripMenuItem2, this.printMenuItem, this.toolStripMenuItem3, this.exitMenuItem}); this.fileMenuItem.Name = "fileMenuItem"; this.fileMenuItem.Size = new System.Drawing.Size(35, 20); this.fileMenuItem.Text = "&File"; // // newMenuItem
file:///D|/1/final/BBL0116.html (142 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.newMenuItem.Name = "newMenuItem"; this.newMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newMenuItem.Size = new System.Drawing.Size(151, 22); this.newMenuItem.Text = "&New"; this.newMenuItem.Click += new System.EventHandler(this.newMenuItem_Click); // // openMenuItem // this.openMenuItem.Name = "openMenuItem"; this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openMenuItem.Size = new System.Drawing.Size(151, 22); this.openMenuItem.Text = "&Open"; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(148, 6); // // saveMenuItem // this.saveMenuItem.Enabled = false; this.saveMenuItem.Name = "saveMenuItem"; this.saveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveMenuItem.Size = new System.Drawing.Size(151, 22); this.saveMenuItem.Text = "&Save"; this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(148, 6); // // printMenuItem // this.printMenuItem.Enabled = false; this.printMenuItem.Name = "printMenuItem"; this.printMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printMenuItem.Size = new System.Drawing.Size(151, 22); this.printMenuItem.Text = "&Print"; this.printMenuItem.Click += new System.EventHandler(this.printMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(148, 6); // // exitMenuItem // this.exitMenuItem.Name = "exitMenuItem"; this.exitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.exitMenuItem.Size = new System.Drawing.Size(151, 22); this.exitMenuItem.Text = "E&xit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt"; this.saveFileDialog.InitialDirectory = "c:\\"; this.saveFileDialog.Title = "Invoices"; // // openFileDialog // this.openFileDialog.DefaultExt = "txt"; this.openFileDialog.InitialDirectory = "c:\\"; this.openFileDialog.Title = "Invoice.txt"; // // printDialog // this.printDialog.Document = this.printDocument; this.printDialog.UseEXDialog = true; // // printDocument //
file:///D|/1/final/BBL0116.html (143 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.printDocument.DocumentName = ""; this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printPage); // // toolStrip // this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripNew, this.toolStripOpen, this.toolStripSave, this.toolStripPrint}); this.toolStrip.Location = new System.Drawing.Point(0, 24); this.toolStrip.Name = "toolStrip"; this.toolStrip.Size = new System.Drawing.Size(872, 25); this.toolStrip.TabIndex = 12; // // toolStripNew // this.toolStripNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripNew.Image = ((System.Drawing.Image)(resources.GetObject("toolStripNew.Image"))); this.toolStripNew.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripNew.Name = "toolStripNew"; this.toolStripNew.Size = new System.Drawing.Size(23, 22); this.toolStripNew.Text = "New"; this.toolStripNew.Click += new System.EventHandler(this.toolStripNew_Click); // // toolStripOpen // this.toolStripOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripOpen.Image = ((System.Drawing.Image)(resources.GetObject("toolStripOpen.Image"))); this.toolStripOpen.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripOpen.Name = "toolStripOpen"; this.toolStripOpen.Size = new System.Drawing.Size(23, 22); this.toolStripOpen.Text = "Open"; this.toolStripOpen.Click += new System.EventHandler(this.toolStripOpen_Click); // // toolStripSave // this.toolStripSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripSave.Enabled = false; this.toolStripSave.Image = ((System.Drawing.Image)(resources.GetObject("toolStripSave.Image"))); this.toolStripSave.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripSave.Name = "toolStripSave"; this.toolStripSave.Size = new System.Drawing.Size(23, 22); this.toolStripSave.Text = "Save"; this.toolStripSave.Click += new System.EventHandler(this.toolStripSave_Click); // // toolStripPrint // this.toolStripPrint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripPrint.Enabled = false; this.toolStripPrint.Image = ((System.Drawing.Image)(resources.GetObject("toolStripPrint.Image"))); this.toolStripPrint.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripPrint.Name = "toolStripPrint"; this.toolStripPrint.Size = new System.Drawing.Size(23, 22); this.toolStripPrint.Text = "Print"; this.toolStripPrint.Click += new System.EventHandler(this.toolStripPrint_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(872, 522); this.Controls.Add(this.toolStrip); this.Controls.Add(this.btnClear); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.btnEnter); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.txtName); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber);
file:///D|/1/final/BBL0116.html (144 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.Controls.Add(this.txtID); this.Controls.Add(this.MainMenu); this.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MainMenuStrip = this.MainMenu; this.Margin = new System.Windows.Forms.Padding(4); this.MaximumSize = new System.Drawing.Size(880, 550); this.MinimumSize = new System.Drawing.Size(880, 550); this.Name = "Form1"; this.Text = "Tool Bar Invoices"; this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.toolStrip.ResumeLayout(false); this.toolStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.MenuStrip MainMenu; private System.Windows.Forms.ToolStripMenuItem fileMenuItem; private System.Windows.Forms.ToolStripMenuItem newMenuItem; private System.Windows.Forms.ToolStripMenuItem openMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem printMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem exitMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.PrintDialog printDialog; private System.Drawing.Printing.PrintDocument printDocument; private System.Windows.Forms.ToolStrip toolStrip; private System.Windows.Forms.ToolStripButton toolStripNew; private System.Windows.Forms.ToolStripButton toolStripOpen; private System.Windows.Forms.ToolStripButton toolStripSave; private System.Windows.Forms.ToolStripButton toolStripPrint; } }
// program_id Form1.cs // written_by don voils // date_written 8/17/2006 // date_modified 9/19/2006 // date_modified 9/20/2006 // description This file along the the file: Form1.Designer.cs // and Program.cs create a Windows program that // implements a program to handle invoices entry. // // This modification includes the addition // of a menu bar. // The second modification include the addition // of a tool bar to emulate the menu bar. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing;
file:///D|/1/final/BBL0116.html (145 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
using System.Text; using System.Windows.Forms; using System.Collections; using System.IO; namespace Invoices { public partial class Form1 : Form { private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList(); public Form1() { InitializeComponent(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; txtID.Focus(); } private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); txtDisplayInvoice.Clear(); } private void btnEnter_Click(object sender, EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); btnDisplay.Enabled = true; btnClear.Enabled = true; ClearBoxes(); txtID.Focus(); } private void btnDisplay_Click(object sender, EventArgs e) { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { theOutput += String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index])) + "\r\n";
file:///D|/1/final/BBL0116.html (146 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } txtDisplayInvoice.Text = theOutput + "\r\n" + String.Format("{0,-20}", "Total:") + String.Format("{0,60:c}", invoiceTotal); } private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; btnEnter.Enabled = false; txtID.Focus(); txtID.Enabled = false; txtName.Enabled = false; txtPrice.Enabled = false; txtNumber.Enabled = false; saveMenuItem.Enabled = false; printMenuItem.Enabled = false; toolStripPrint.Enabled = false; toolStripSave.Enabled = false; } private void exitMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void newMenuItem_Click(object sender, EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveMenuItem.Enabled = true; toolStripSave.Enabled = true; printMenuItem.Enabled = true; toolStripPrint.Enabled = true; btnEnter.Enabled = true; txtID.Focus(); } private void saveMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); // used to find the number of elements in each // of the arrays. int numberItems = productID.Count; // loops through each array and extracts the // elements and then writes them to the file. // for (int index = 0; index < numberItems; ++index) { fileWriter.WriteLine(String.Format("{0}", productID[index])); fileWriter.WriteLine(String.Format("{0}", productName[index])); fileWriter.WriteLine(String.Format("{0}", numberOrdered[index])); fileWriter.WriteLine(String.Format("{0}", itemPrice[index])); } // closes the file to empty the output buffer.
file:///D|/1/final/BBL0116.html (147 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// fileWriter.Close(); // sends a message to the user that the file // has beensaved. // MessageBox.Show("Invoice details were saved", "Saved"); // clears all of the textboxes and the listbox. // ClearBoxes(); // clears the data from the arrays so that they are // empty in case // the user wants to work on another invoice. // productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); // disables all of the textboxes and the listbox // and the bottons // txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Clear(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for save and print since // there is no more data contained in memory. // saveMenuItem.Enabled = false; printMenuItem.Enabled = false; toolStripSave.Enabled = false; toolStripPrint.Enabled = false; } } private void openMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; toolStripSave.Enabled = true; toolStripPrint.Enabled = true; string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while (theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData);
file:///D|/1/final/BBL0116.html (148 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void printMenuItem_Click(object sender, EventArgs e) { if (productID.Count != 0) { DialogResult buttonClicked = printDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { printDocument.Print(); } } else MessageBox.Show("There is no data to be printed", "Error"); } private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { StringBuilder data = new StringBuilder(); StringWriter writer = new StringWriter(data); writer.WriteLine("Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"); decimal invoiceTotal = 0.00m; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { writer.WriteLine(String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]))); invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } writer.WriteLine("\r\n" + String.Format("{0,-20}", "Total:") + String.Format("{0,60:c}", invoiceTotal)); writer.Close(); float leftMargin = e.MarginBounds.Left; float topMargin = e.MarginBounds.Top; float yPos = 0; Font printFont = null; printFont = new Font("Courier New", 10); yPos = topMargin + printFont.GetHeight(e.Graphics); e.HasMorePages = false; e.Graphics.DrawString(data.ToString(), printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); } private void toolStripNew_Click(object sender, EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true;
file:///D|/1/final/BBL0116.html (149 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
txtPrice.Enabled = true; saveMenuItem.Enabled = true; toolStripSave.Enabled = true; printMenuItem.Enabled = true; toolStripPrint.Enabled = true; btnEnter.Enabled = true; txtID.Focus(); } private void toolStripOpen_Click(object sender, EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; toolStripSave.Enabled = true; toolStripPrint.Enabled = true; string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while (theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void toolStripSave_Click(object sender, EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); // used to find the number of elements in each // of the arrays. int numberItems = productID.Count; // loops through each array and extracts the // elements and then writes them to the file. // for (int index = 0; index < numberItems; ++index) { fileWriter.WriteLine(String.Format("{0}", productID[index])); fileWriter.WriteLine(String.Format("{0}", productName[index])); fileWriter.WriteLine(String.Format("{0}", numberOrdered[index])); fileWriter.WriteLine(String.Format("{0}", itemPrice[index])); }
file:///D|/1/final/BBL0116.html (150 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// closes the file to empty the output buffer. // fileWriter.Close(); // sends a message to the user that the file // has beensaved. // MessageBox.Show("Invoice details were saved", "Saved"); // clears all of the textboxes and the listbox. // ClearBoxes(); // clears the data from the arrays so that they are // empty in case // the user wants to work on another invoice. // productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); // disables all of the textboxes and the listbox // and the bottons // txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Clear(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for save and print since // there is no more data contained in memory. // saveMenuItem.Enabled = false; printMenuItem.Enabled = false; toolStripSave.Enabled = false; toolStripPrint.Enabled = false; } } private void toolStripPrint_Click(object sender, EventArgs e) { if (productID.Count != 0) { DialogResult buttonClicked = printDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { printDocument.Print(); } } else MessageBox.Show("There is no data to be printed", "Error"); } } }
// program_id Program.cs // written_by don voils // date_written 8/17/2006 // date_modified 9/19/2006 // date_modified 9/20/2006 // description This file along the the file: Form1.Designer.cs // and Form1.cs create a Windows program that // implements a program to handle invoices entry. // // This modification includes the addition // of a menu bar.
file:///D|/1/final/BBL0116.html (151 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// //
The second modification include the addition of a tool bar to emulate the menu bar.
using System; using System.Collections.Generic; using System.Windows.Forms; namespace Invoices { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Form1.cs // written_by don voils // date_written 10/13/2006 // description This file along with Form1.Designer.cs and // Program.cs create a program with a tool // strip. It is a modification of the invoice // menu program. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO;
namespace menuInvoices { public partial class Form1 : Form { private ArrayList productID = new ArrayList(); private ArrayList productName = new ArrayList(); private ArrayList numberOrdered = new ArrayList(); private ArrayList itemPrice = new ArrayList(); public Form1() { InitializeComponent(); btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; txtID.Focus(); } private void ClearBoxes() { txtID.Clear(); txtName.Clear(); txtNumber.Clear(); txtPrice.Clear(); txtDisplayInvoice.Clear(); }
file:///D|/1/final/BBL0116.html (152 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private void btnEnter_Click(object sender, EventArgs e) { productID.Add(txtID.Text); productName.Add(txtName.Text); numberOrdered.Add(txtNumber.Text); itemPrice.Add(txtPrice.Text); btnDisplay.Enabled = true; btnClear.Enabled = true; ClearBoxes(); txtID.Focus(); } private void btnDisplay_Click(object sender, EventArgs e) { decimal invoiceTotal = 0.00m; string theOutput = "Product ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { theOutput += String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) + String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index])) + "\r\n"; invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } txtDisplayInvoice.Text = theOutput + "\r\n" + String.Format("{0,-20}", "Total") + String.Format("{0,60:c}", invoiceTotal); } private void btnClear_Click(object sender, EventArgs e) { txtDisplayInvoice.Clear(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); btnDisplay.Enabled = false; btnClear.Enabled = false; txtID.Focus(); txtID.Enabled = false; txtName.Enabled = false; txtPrice.Enabled = false; txtNumber.Enabled = false; saveMenuItem.Enabled = false; printMenuItem.Enabled = false; toolStripPrint.Enabled = false; toolStripSave.Enabled = false; } private void exitMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void newMenuItem_Click(object sender, EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveMenuItem.Enabled = true;
file:///D|/1/final/BBL0116.html (153 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
printMenuItem.Enabled = true; toolStripSave.Enabled = true; toolStripPrint.Enabled = true; btnEnter.Enabled = true; txtID.Focus(); } private void saveMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); //used to find the number of elements in each // of the arrays. int numberItems = productID.Count; // loops through each array and extracts the // elements and then writes them to the file. // for (int index = 0; index < numberItems; ++index) { fileWriter.WriteLine(String.Format("{0}", productID[index])); fileWriter.WriteLine(String.Format("{0}", productName[index])); fileWriter.WriteLine(String.Format("{0}", numberOrdered[index])); fileWriter.WriteLine(String.Format("{0}", itemPrice[index])); } // closes the file to empty the output buffer. // fileWriter.Close(); // sends a message to the user that the file // has been saved. // MessageBox.Show("Invoice details were saved", "Saved"); // clears all of the textboxes. // ClearBoxes(); // clears the data from the arrays so that they // are empty in case // the user wants to work on another invoice. // productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); // disables all of the textboxes // and the buttons. txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for Save and Print since // there is no more data contained in memory. // saveMenuItem.Enabled = false; printMenuItem.Enabled = false; toolStripSave.Enabled = false; toolStripPrint.Enabled = false; } } private void openMenuItem_Click(object sender, EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { // Clear the arrays and the form of all data.
file:///D|/1/final/BBL0116.html (154 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; toolStripSave.Enabled = true; toolStripPrint.Enabled = true; // Reads the data from the file one // record at a time and then closes // the reader when completed. // string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while (theData != null) { productID.Add(theData); theData = fileReader.ReadLine(); productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void printMenuItem_Click(object sender, EventArgs e) { if (productID.Count != 0) { DialogResult buttonClicked = printDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { printDocument.Print(); } } else MessageBox.Show("There was no data to be printed.", "Error"); } private void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { StringBuilder data = new StringBuilder(); StringWriter writer = new StringWriter(data); writer.WriteLine("Producet ID".PadRight(20) + "Product Name".PadRight(20) + "Number".PadRight(15) + "Price".PadRight(20) + "Total".PadRight(20) + "\r\n"); decimal invoiceTotal = 0.00m; int numberItems = productID.Count; for (int index = 0; index < numberItems; ++index) { writer.WriteLine(String.Format("{0,-20}", productID[index]) + String.Format("{0,-20}", productName[index]) + String.Format("{0,10}", numberOrdered[index]) +
file:///D|/1/final/BBL0116.html (155 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
String.Format("{0,15:c}", Convert.ToDecimal(itemPrice[index])) + String.Format("{0,15:c}", Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]))); invoiceTotal += Convert.ToDecimal(numberOrdered[index]) * Convert.ToDecimal(itemPrice[index]); } writer.WriteLine("\r\n" + String.Format("{0,-20}", "Total") + String.Format("{0,60:c}", invoiceTotal)); writer.Close(); float leftMargin = e.MarginBounds.Left; float topMargin = e.MarginBounds.Top; float yPos = 0; Font printFont = null; printFont = new Font("Courier New", 10); yPos = topMargin + printFont.GetHeight(e.Graphics); e.HasMorePages = false; e.Graphics.DrawString(data.ToString(), printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); } private void toolStripNew_Click(object sender, EventArgs e) { ClearBoxes(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; toolStripSave.Enabled = true; toolStripPrint.Enabled = true; btnEnter.Enabled = true; txtID.Focus(); } private void toolStripOpen_Click(object sender, EventArgs e) { DialogResult buttonClicked = openFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { // Clear the arrays and the form of all data. // ClearBoxes(); productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); txtID.Enabled = true; txtName.Enabled = true; txtNumber.Enabled = true; txtPrice.Enabled = true; btnEnter.Enabled = true; btnDisplay.Enabled = true; btnClear.Enabled = true; saveMenuItem.Enabled = true; printMenuItem.Enabled = true; toolStripSave.Enabled = true; toolStripPrint.Enabled = true; // Reads the data from the file one // record at a time and then closes // the reader when completed. // string theData; StreamReader fileReader = new StreamReader(openFileDialog.FileName); theData = fileReader.ReadLine(); while (theData != null) { productID.Add(theData); theData = fileReader.ReadLine();
file:///D|/1/final/BBL0116.html (156 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
productName.Add(theData); theData = fileReader.ReadLine(); numberOrdered.Add(theData); theData = fileReader.ReadLine(); itemPrice.Add(theData); theData = fileReader.ReadLine(); } fileReader.Close(); } } private void toolStripSave_Click(object sender, EventArgs e) { DialogResult buttonClicked = saveFileDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { StreamWriter fileWriter = new StreamWriter(saveFileDialog.FileName); //used to find the number of elements in each // of the arrays. int numberItems = productID.Count; // loops through each array and extracts the // elements and then writes them to the file. // for (int index = 0; index < numberItems; ++index) { fileWriter.WriteLine(String.Format("{0}", productID[index])); fileWriter.WriteLine(String.Format("{0}", productName[index])); fileWriter.WriteLine(String.Format("{0}", numberOrdered[index])); fileWriter.WriteLine(String.Format("{0}", itemPrice[index])); } // closes the file to empty the output buffer. // fileWriter.Close(); // sends a message to the user that the file // has been saved. // MessageBox.Show("Invoice details were saved", "Saved"); // clears all of the textboxes. // ClearBoxes(); // clears the data from the arrays so that they // are empty in case // the user wants to work on another invoice. // productID.Clear(); productName.Clear(); numberOrdered.Clear(); itemPrice.Clear(); // disables all of the textboxes // and the buttons. txtID.Enabled = false; txtName.Enabled = false; txtNumber.Enabled = false; txtPrice.Enabled = false; txtDisplayInvoice.Enabled = false; btnEnter.Enabled = false; btnDisplay.Enabled = false; btnClear.Enabled = false; // disables the menu options for Save and Print since // there is no more data contained in memory. // saveMenuItem.Enabled = false; printMenuItem.Enabled = false; toolStripSave.Enabled = false; toolStripPrint.Enabled = false; } }
file:///D|/1/final/BBL0116.html (157 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private void toolStripPrint_Click(object sender, EventArgs e) { if (productID.Count != 0) { DialogResult buttonClicked = printDialog.ShowDialog(); if (buttonClicked.Equals(DialogResult.OK)) { printDocument.Print(); } } else MessageBox.Show("There was no data to be printed.", "Error"); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 10/13/2006 // description This file along with Form1.cs and // Program.cs create a program with a tool // strip. It is a modification of the invoice // menu program. // namespace menuInvoices { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (Form1)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtID = new System.Windows.Forms.TextBox(); this.txtName = new System.Windows.Forms.TextBox(); this.txtNumber = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtDisplayInvoice = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnDisplay = new System.Windows.Forms.Button(); this.MainMenu = new System.Windows.Forms.MenuStrip(); this.fileMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.saveMenuItem = new System.Windows.Forms.ToolStripMenuItem();
file:///D|/1/final/BBL0116.html (158 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.printMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.exitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.printDocument = new System.Drawing.Printing.PrintDocument(); this.toolStrip = new System.Windows.Forms.ToolStrip(); this.toolStripNew = new System.Windows.Forms.ToolStripButton(); this.toolStripOpen = new System.Windows.Forms.ToolStripButton(); this.toolStripSave = new System.Windows.Forms.ToolStripButton(); this.toolStripPrint = new System.Windows.Forms.ToolStripButton(); this.MainMenu.SuspendLayout(); this.toolStrip.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.Location = new System.Drawing.Point(27, 60); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(179, 20); this.label1.TabIndex = 0; this.label1.Text = "Product ID Number"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.Location = new System.Drawing.Point(27, 98); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(129, 20); this.label2.TabIndex = 1; this.label2.Text = "Product Name"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label3.Location = new System.Drawing.Point(394, 58); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(259, 20); this.label3.TabIndex = 2; this.label3.Text = "Number of Items Purchased"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.Location = new System.Drawing.Point(394, 98); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(149, 20); this.label4.TabIndex = 3; this.label4.Text = "Price per Item"; // // txtID // this.txtID.Location = new System.Drawing.Point(212, 54); this.txtID.Name = "txtID"; this.txtID.Size = new System.Drawing.Size(100, 26); this.txtID.TabIndex = 1; // // txtName // this.txtName.Location = new System.Drawing.Point(212, 92); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(156, 26); this.txtName.TabIndex = 2; //
file:///D|/1/final/BBL0116.html (159 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// txtNumber // this.txtNumber.Location = new System.Drawing.Point(717, 52); this.txtNumber.Name = "txtNumber"; this.txtNumber.Size = new System.Drawing.Size(100, 26); this.txtNumber.TabIndex = 3; this.txtNumber.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtPrice // this.txtPrice.Location = new System.Drawing.Point(717, 92); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(100, 26); this.txtPrice.TabIndex = 4; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtDisplayInvoice // this.txtDisplayInvoice.Location = new System.Drawing.Point(15, 267); this.txtDisplayInvoice.Multiline = true; this.txtDisplayInvoice.Name = "txtDisplayInvoice"; this.txtDisplayInvoice.ReadOnly = true; this.txtDisplayInvoice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDisplayInvoice.Size = new System.Drawing.Size(860, 230); this.txtDisplayInvoice.TabIndex = 7; this.txtDisplayInvoice.TabStop = false; // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnEnter.Location = new System.Drawing.Point(61, 160); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(172, 23); this.btnEnter.TabIndex = 5; this.btnEnter.Text = "Enter Data"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnClear // this.btnClear.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnClear.Location = new System.Drawing.Point(501, 195); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(177, 23); this.btnClear.TabIndex = 7; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Invoice"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnDisplay // this.btnDisplay.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnDisplay.Location = new System.Drawing.Point(61, 224); this.btnDisplay.Name = "btnDisplay"; this.btnDisplay.Size = new System.Drawing.Size(172, 23); this.btnDisplay.TabIndex = 6; this.btnDisplay.TabStop = false; this.btnDisplay.Text = "Display Invoice"; this.btnDisplay.UseVisualStyleBackColor = true; this.btnDisplay.Click += new System.EventHandler(this.btnDisplay_Click); // // MainMenu // this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileMenuItem}); this.MainMenu.Location = new System.Drawing.Point(0, 0); this.MainMenu.Name = "MainMenu"; this.MainMenu.Size = new System.Drawing.Size(892, 26); this.MainMenu.TabIndex = 8; this.MainMenu.Text = "menuStrip1"; // // fileMenuItem
file:///D|/1/final/BBL0116.html (160 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.fileMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newMenuItem, this.openMenuItem, this.toolStripMenuItem1, this.saveMenuItem, this.toolStripMenuItem3, this.printMenuItem, this.toolStripMenuItem4, this.exitMenuItem}); this.fileMenuItem.Name = "fileMenuItem"; this.fileMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F))); this.fileMenuItem.Size = new System.Drawing.Size(40, 22); this.fileMenuItem.Text = "&File"; // // newMenuItem // this.newMenuItem.Name = "newMenuItem"; this.newMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newMenuItem.Size = new System.Drawing.Size(177, 22); this.newMenuItem.Text = "&New"; this.newMenuItem.Click += new System.EventHandler(this.newMenuItem_Click); // // openMenuItem // this.openMenuItem.Name = "openMenuItem"; this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openMenuItem.Size = new System.Drawing.Size(177, 22); this.openMenuItem.Text = "&Open"; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(174, 6); // // saveMenuItem // this.saveMenuItem.Enabled = false; this.saveMenuItem.Name = "saveMenuItem"; this.saveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveMenuItem.Size = new System.Drawing.Size(177, 22); this.saveMenuItem.Text = "&Save"; this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(174, 6); // // printMenuItem // this.printMenuItem.Enabled = false; this.printMenuItem.Name = "printMenuItem"; this.printMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printMenuItem.Size = new System.Drawing.Size(177, 22); this.printMenuItem.Text = "&Print"; this.printMenuItem.Click += new System.EventHandler(this.printMenuItem_Click); // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(174, 6); // // exitMenuItem // this.exitMenuItem.Name = "exitMenuItem"; this.exitMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.exitMenuItem.Size = new System.Drawing.Size(177, 22); this.exitMenuItem.Text = "E&xit"; this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt";
file:///D|/1/final/BBL0116.html (161 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.saveFileDialog.InitialDirectory = "C:\\"; this.saveFileDialog.Title = "Invoices"; // // openFileDialog // this.openFileDialog.DefaultExt = "txt"; this.openFileDialog.InitialDirectory = "C:\\"; this.openFileDialog.Title = "Invoices.txt"; // // printDialog // this.printDialog.Document = this.printDocument; this.printDialog.UseEXDialog = true; // // printDocument // this.printDocument.DocumentName = ""; this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printPage); // // toolStrip // this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripNew, this.toolStripOpen, this.toolStripSave, this.toolStripPrint}); this.toolStrip.Location = new System.Drawing.Point(0, 26); this.toolStrip.Name = "toolStrip"; this.toolStrip.Size = new System.Drawing.Size(892, 25); this.toolStrip.TabIndex = 9; // // toolStripNew // this.toolStripNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripNew.Image = ((System.Drawing.Image)(resources.GetObject("toolStripNew.Image"))); this.toolStripNew.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripNew.Name = "toolStripNew"; this.toolStripNew.Size = new System.Drawing.Size(23, 22); this.toolStripNew.Text = "New"; this.toolStripNew.Click += new System.EventHandler(this.toolStripNew_Click); // // toolStripOpen // this.toolStripOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripOpen.Image = ((System.Drawing.Image)(resources.GetObject("toolStripOpen.Image"))); this.toolStripOpen.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripOpen.Name = "toolStripOpen"; this.toolStripOpen.Size = new System.Drawing.Size(23, 22); this.toolStripOpen.Text = "Open"; this.toolStripOpen.Click += new System.EventHandler(this.toolStripOpen_Click); // // toolStripSave // this.toolStripSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripSave.Enabled = false; this.toolStripSave.Image = ((System.Drawing.Image)(resources.GetObject("toolStripSave.Image"))); this.toolStripSave.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripSave.Name = "toolStripSave"; this.toolStripSave.Size = new System.Drawing.Size(23, 22); this.toolStripSave.Text = "Save"; this.toolStripSave.Click += new System.EventHandler(this.toolStripSave_Click); // // toolStripPrint // this.toolStripPrint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripPrint.Enabled = false; this.toolStripPrint.Image = ((System.Drawing.Image)(resources.GetObject("toolStripPrint.Image"))); this.toolStripPrint.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripPrint.Name = "toolStripPrint"; this.toolStripPrint.Size = new System.Drawing.Size(23, 22); this.toolStripPrint.Text = "Print"; this.toolStripPrint.Click += new System.EventHandler(this.toolStripPrint_Click); // // Form1
file:///D|/1/final/BBL0116.html (162 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(892, 517); this.Controls.Add(this.toolStrip); this.Controls.Add(this.btnDisplay); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtDisplayInvoice); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtNumber); this.Controls.Add(this.txtName); this.Controls.Add(this.txtID); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.MainMenu); this.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MainMenuStrip = this.MainMenu; this.Margin = new System.Windows.Forms.Padding(4); this.MaximumSize = new System.Drawing.Size(900, 550); this.MinimumSize = new System.Drawing.Size(900, 550); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Tool Strip Invoices"; this.MainMenu.ResumeLayout(false); this.MainMenu.PerformLayout(); this.toolStrip.ResumeLayout(false); this.toolStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtNumber; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtDisplayInvoice; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnDisplay; private System.Windows.Forms.MenuStrip MainMenu; private System.Windows.Forms.ToolStripMenuItem fileMenuItem; private System.Windows.Forms.ToolStripMenuItem newMenuItem; private System.Windows.Forms.ToolStripMenuItem openMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem printMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem exitMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.PrintDialog printDialog; private System.Drawing.Printing.PrintDocument printDocument; private System.Windows.Forms.ToolStrip toolStrip; private System.Windows.Forms.ToolStripButton toolStripNew; private System.Windows.Forms.ToolStripButton toolStripOpen; private System.Windows.Forms.ToolStripButton toolStripSave; private System.Windows.Forms.ToolStripButton toolStripPrint; } }
// program_id Program.cs // written_by don voils // date_written 10/13/2006
file:///D|/1/final/BBL0116.html (163 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// description This file along with Form1.Designer.cs and // Form1.cs create a program with a tool // strip. It is a modification of the invoice // menu program. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace menuInvoices { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id useCashRegister2.cs // written_by don voils // date_written 4/15/2003 // description This program is a maintenance program // of useCashRegister.cs. It adds messageboxes // to make the program more robust. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using ViewCashRegister; namespace MonthlySales { /// <summary> /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { private CashRegister[] dailySales = new CashRegister[31]; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txtCategory1; private System.Windows.Forms.TextBox txtDailyTotals; private System.Windows.Forms.TextBox txtReport; private System.Windows.Forms.TextBox txtCategory3; private System.Windows.Forms.TextBox txtCategory2; private System.Windows.Forms.TextBox txtCategory5; private System.Windows.Forms.TextBox txtCategory4; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnReport; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txtMonth; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtDay; private System.Windows.Forms.TextBox txtYear; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Button btnViewDaily; private System.Windows.Forms.Button btnClear;
file:///D|/1/final/BBL0116.html (164 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.Button btnClose; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // txtMonth.Focus(); for(int day = 1;day <= 31;++day) dailySales[day-1] = new CashRegister(); } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if(disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.txtCategory1 = new System.Windows.Forms.TextBox(); this.txtDailyTotals = new System.Windows.Forms.TextBox(); this.txtReport = new System.Windows.Forms.TextBox(); this.txtCategory3 = new System.Windows.Forms.TextBox(); this.txtCategory2 = new System.Windows.Forms.TextBox(); this.txtCategory5 = new System.Windows.Forms.TextBox(); this.txtCategory4 = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.btnReport = new System.Windows.Forms.Button(); this.label6 = new System.Windows.Forms.Label(); this.txtMonth = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.txtDay = new System.Windows.Forms.TextBox(); this.txtYear = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.btnViewDaily = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(8, 25); this.label1.Name = "label1";
file:///D|/1/final/BBL0116.html (165 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label1.Size = new System.Drawing.Size(72, 23); this.label1.TabIndex = 0; this.label1.Text = "Category 1"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label2.Location = new System.Drawing.Point(8, 85); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(64, 23); this.label2.TabIndex = 1; this.label2.Text = "Category 3"; // // label3 // this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label3.Location = new System.Drawing.Point(8, 55); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 23); this.label3.TabIndex = 2; this.label3.Text = "Category 2"; // // label4 // this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label4.Location = new System.Drawing.Point(8, 145); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(64, 23); this.label4.TabIndex = 3; this.label4.Text = "Category 5"; // // label5 // this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label5.Location = new System.Drawing.Point(8, 115); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(64, 23); this.label5.TabIndex = 4; this.label5.Text = "Category 4"; // // txtCategory1 // this.txtCategory1.Location = new System.Drawing.Point(88, 20); this.txtCategory1.Name = "txtCategory1"; this.txtCategory1.TabIndex = 4; this.txtCategory1.Text = ""; // // txtDailyTotals // this.txtDailyTotals.Location = new System.Drawing.Point(88, 180); this.txtDailyTotals.Name = "txtDailyTotals"; this.txtDailyTotals.ReadOnly = true; this.txtDailyTotals.TabIndex = 20; this.txtDailyTotals.TabStop = false; this.txtDailyTotals.Text = ""; // // txtReport // this.txtReport.Location = new System.Drawing.Point(24, 280); this.txtReport.Multiline = true; this.txtReport.Name = "txtReport"; this.txtReport.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtReport.Size = new System.Drawing.Size(752, 80); this.txtReport.TabIndex = 7; this.txtReport.TabStop = false; this.txtReport.Text = ""; // // txtCategory3 // this.txtCategory3.Location = new System.Drawing.Point(88, 80); this.txtCategory3.Name = "txtCategory3"; this.txtCategory3.TabIndex = 6;
file:///D|/1/final/BBL0116.html (166 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtCategory3.Text = ""; // // txtCategory2 // this.txtCategory2.Location = new System.Drawing.Point(88, 50); this.txtCategory2.Name = "txtCategory2"; this.txtCategory2.TabIndex = 5; this.txtCategory2.Text = ""; // // txtCategory5 // this.txtCategory5.Location = new System.Drawing.Point(88, 140); this.txtCategory5.Name = "txtCategory5"; this.txtCategory5.TabIndex = 8; this.txtCategory5.Text = ""; // // txtCategory4 // this.txtCategory4.Location = new System.Drawing.Point(88, 110); this.txtCategory4.Name = "txtCategory4"; this.txtCategory4.TabIndex = 7; this.txtCategory4.Text = ""; // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnEnter.Location = new System.Drawing.Point(220, 200); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(110, 25); this.btnEnter.TabIndex = 10; this.btnEnter.Text = "Enter Daily Sales"; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnReport // this.btnReport.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnReport.Location = new System.Drawing.Point(30, 240); this.btnReport.Name = "btnReport"; this.btnReport.Size = new System.Drawing.Size(140, 20); this.btnReport.TabIndex = 13; this.btnReport.TabStop = false; this.btnReport.Text = "View Monthly Report"; this.btnReport.Click += new System.EventHandler(this.btnReport_Click); // // label6 // this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label6.Location = new System.Drawing.Point(8, 185); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(72, 23); this.label6.TabIndex = 14; this.label6.Text = "Daily Totals"; // // txtMonth // this.txtMonth.Location = new System.Drawing.Point(290, 40); this.txtMonth.Name = "txtMonth"; this.txtMonth.Size = new System.Drawing.Size(20, 20); this.txtMonth.TabIndex = 1; this.txtMonth.Text = ""; // // label7 // this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label7.Location = new System.Drawing.Point(248, 40); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(32, 15); this.label7.TabIndex = 16; this.label7.Text = "Date:"; // // txtDay
file:///D|/1/final/BBL0116.html (167 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// this.txtDay.Location = new System.Drawing.Point(320, 40); this.txtDay.Name = "txtDay"; this.txtDay.Size = new System.Drawing.Size(20, 20); this.txtDay.TabIndex = 2; this.txtDay.Text = ""; // // txtYear // this.txtYear.Location = new System.Drawing.Point(350, 40); this.txtYear.Name = "txtYear"; this.txtYear.Size = new System.Drawing.Size(50, 20); this.txtYear.TabIndex = 3; this.txtYear.Text = ""; // // label8 // this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label8.Location = new System.Drawing.Point(310, 43); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(8, 20); this.label8.TabIndex = 20; this.label8.Text = "/"; // // label9 // this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label9.Location = new System.Drawing.Point(340, 43); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(8, 20); this.label9.TabIndex = 20; this.label9.Text = "/"; // // btnViewDaily // this.btnViewDaily.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing. GraphicsUnit.Point, ((System.Byte)(0))); this.btnViewDaily.Location = new System.Drawing.Point(210, 130); this.btnViewDaily.Name = "btnViewDaily"; this.btnViewDaily.Size = new System.Drawing.Size(150, 25); this.btnViewDaily.TabIndex = 9; this.btnViewDaily.Text = "View Daily Sales Total"; this.btnViewDaily.Click += new System.EventHandler(this.btnViewDaily_Click); // // btnClear // this.btnClear.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnClear.Location = new System.Drawing.Point(500, 240); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(90, 20); this.btnClear.TabIndex = 21; this.btnClear.Text = "Clear Report"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnClose // this.btnClose.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnClose.Location = new System.Drawing.Point(590, 40); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(100, 20); this.btnClose.TabIndex = 22; this.btnClose.Text = "Close Program"; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(7, 13); this.ClientSize = new System.Drawing.Size(800, 402); this.Controls.Add(this.btnClose); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnViewDaily); this.Controls.Add(this.label9);
file:///D|/1/final/BBL0116.html (168 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.Controls.Add(this.label8); this.Controls.Add(this.txtYear); this.Controls.Add(this.txtDay); this.Controls.Add(this.label7); this.Controls.Add(this.txtMonth); this.Controls.Add(this.label6); this.Controls.Add(this.btnReport); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtCategory4); this.Controls.Add(this.txtCategory5); this.Controls.Add(this.txtCategory2); this.Controls.Add(this.txtCategory3); this.Controls.Add(this.txtReport); this.Controls.Add(this.txtDailyTotals); this.Controls.Add(this.txtCategory1); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Name = "Form1"; this.Text = "The Cash Register"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void ClearForm() { txtMonth.Clear(); txtDay.Clear(); txtYear.Clear(); txtCategory1.Clear(); txtCategory2.Clear(); txtCategory3.Clear(); txtCategory4.Clear(); txtCategory5.Clear(); txtDailyTotals.Clear(); txtReport.Clear(); } private void Form1_Load(object sender, System.EventArgs e) { ClearForm(); txtMonth.Focus(); } private void btnEnter_Click(object sender, System.EventArgs e) { if((txtMonth.Text=="") || (txtDay.Text=="") || (txtYear.Text=="")) MessageBox.Show("Part of the date was not entered correctly.","Date Missing"); else if(txtCategory1.Text=="") MessageBox.Show("No amount was entered for Category 1","Data Missing"); else if(txtCategory2.Text=="") MessageBox.Show("No amount was entered for Category 2","Data Missing"); else if(txtCategory3.Text=="") MessageBox.Show("No amount was entered for Category 3","Data Missing"); else if(txtCategory4.Text=="") MessageBox.Show("No amount was entered for Category 4","Data Missing"); else
file:///D|/1/final/BBL0116.html (169 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
if(txtCategory5.Text=="") MessageBox.Show("No amount was entered for Category 5","Data Missing"); else { int day = Convert.ToInt16(txtDay.Text); dailySales[day-1].enterCategoryAmount(1,Convert.ToDecimal(txtCategory1.Text)); dailySales[day-1].enterCategoryAmount(2,Convert.ToDecimal(txtCategory2.Text)); dailySales[day-1].enterCategoryAmount(3,Convert.ToDecimal(txtCategory3.Text)); dailySales[day-1].enterCategoryAmount(4,Convert.ToDecimal(txtCategory4.Text)); dailySales[day-1].enterCategoryAmount(5,Convert.ToDecimal(txtCategory5.Text)); ClearForm(); txtMonth.Focus(); } } private void btnViewDaily_Click(object sender, System.EventArgs e) { if((txtMonth.Text=="") || (txtDay.Text=="") || (txtYear.Text=="")) MessageBox.Show("Part of the date was not entered correctly.","Date Missing"); else if(txtCategory1.Text=="") MessageBox.Show("No amount was entered for Category 1","Data Missing"); else if(txtCategory2.Text=="") MessageBox.Show("No amount was entered for Category 2","Data Missing"); else if(txtCategory3.Text=="") MessageBox.Show("No amount was entered for Category 3","Data Missing"); else if(txtCategory4.Text=="") MessageBox.Show("No amount was entered for Category 4","Data Missing"); else if(txtCategory5.Text=="") MessageBox.Show("No amount was entered for Category 5","Data Missing"); else { decimal theTotal = 0.00m; theTotal = Convert.ToDecimal(txtCategory1.Text); theTotal += Convert.ToDecimal(txtCategory2.Text); theTotal += Convert.ToDecimal(txtCategory3.Text); theTotal += Convert.ToDecimal(txtCategory4.Text); theTotal += Convert.ToDecimal(txtCategory5.Text); txtDailyTotals.Text = String.Format("{0:c}",theTotal); } } private void btnReport_Click(object sender, System.EventArgs e) { decimal dailyTotal; decimal monthlyTotal = 0.00m; decimal[] categoryTotal = new decimal[5]; for(int cat = 1;cat<=5;++cat) categoryTotal[cat-1] = 0.00m; string output = String.Format("{0}\t{1}\t\t{2}\t\t{3}\t\t{4}\t\t{5}\t\t{6}\r\n", "Day","Cat1","Cat2","Cat3","Cat4","Cat5","Daily Total"); for(int day = 1;day <= 31;++day) { dailyTotal = 0.00m; output += String.Format("{0,2}",(day)); for(int cat = 1;cat <= 5;++cat) { dailyTotal += dailySales[day-1].returnCategoryAmount(cat); categoryTotal[cat-1] += dailySales[day-1].returnCategoryAmount(cat); output += String.Format("\t{0,15:c}",dailySales[day-1].returnCategoryAmount(cat)); } monthlyTotal += dailyTotal; output += String.Format("\t{0,15:c}",dailyTotal)+"\r\n"; } output += "\r\nTotals"; for(int cat = 1;cat <=5;++cat) output += String.Format("\t{0,15:c}",categoryTotal[cat-1]); output += String.Format("\t{0,15:c}",monthlyTotal)+"\r\n"; txtReport.Text = output; }
file:///D|/1/final/BBL0116.html (170 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private void btnClear_Click(object sender, System.EventArgs e) { ClearForm(); txtMonth.Focus(); } private void btnClose_Click(object sender, System.EventArgs e) { Application.Exit(); } } }
// program_id useCashRegister.cs // written_by don voils // date_written 4/15/2003 // description This program uses the class CashRegister to // simulate an income program taking data from // the data entry and storing it into objects // of the class CashRegister. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using ViewCashRegister; namespace MonthlySales { /// <summary> /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { private CashRegister[] dailySales = new CashRegister[31]; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txtCategory1; private System.Windows.Forms.TextBox txtDailyTotals; private System.Windows.Forms.TextBox txtReport; private System.Windows.Forms.TextBox txtCategory3; private System.Windows.Forms.TextBox txtCategory2; private System.Windows.Forms.TextBox txtCategory5; private System.Windows.Forms.TextBox txtCategory4; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnReport; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txtMonth; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtDay; private System.Windows.Forms.TextBox txtYear; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Button btnViewDaily; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnClose; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent();
file:///D|/1/final/BBL0116.html (171 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// // TODO: Add any constructor code after InitializeComponent call // txtMonth.Focus(); for(int day = 1;day <= 31;++day) dailySales[day-1] = new CashRegister(); } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if(disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.txtCategory1 = new System.Windows.Forms.TextBox(); this.txtDailyTotals = new System.Windows.Forms.TextBox(); this.txtReport = new System.Windows.Forms.TextBox(); this.txtCategory3 = new System.Windows.Forms.TextBox(); this.txtCategory2 = new System.Windows.Forms.TextBox(); this.txtCategory5 = new System.Windows.Forms.TextBox(); this.txtCategory4 = new System.Windows.Forms.TextBox(); this.btnEnter = new System.Windows.Forms.Button(); this.btnReport = new System.Windows.Forms.Button(); this.label6 = new System.Windows.Forms.Label(); this.txtMonth = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.txtDay = new System.Windows.Forms.TextBox(); this.txtYear = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.btnViewDaily = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(8, 25); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(72, 23); this.label1.TabIndex = 0; this.label1.Text = "Category 1"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label2.Location = new System.Drawing.Point(8, 85); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(64, 23); this.label2.TabIndex = 1;
file:///D|/1/final/BBL0116.html (172 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.label2.Text = "Category 3"; // // label3 // this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label3.Location = new System.Drawing.Point(8, 55); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 23); this.label3.TabIndex = 2; this.label3.Text = "Category 2"; // // label4 // this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label4.Location = new System.Drawing.Point(8, 145); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(64, 23); this.label4.TabIndex = 3; this.label4.Text = "Category 5"; // // label5 // this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label5.Location = new System.Drawing.Point(8, 115); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(64, 23); this.label5.TabIndex = 4; this.label5.Text = "Category 4"; // // txtCategory1 // this.txtCategory1.Location = new System.Drawing.Point(88, 20); this.txtCategory1.Name = "txtCategory1"; this.txtCategory1.TabIndex = 4; this.txtCategory1.Text = ""; // // txtDailyTotals // this.txtDailyTotals.Location = new System.Drawing.Point(88, 180); this.txtDailyTotals.Name = "txtDailyTotals"; this.txtDailyTotals.ReadOnly = true; this.txtDailyTotals.TabIndex = 20; this.txtDailyTotals.TabStop = false; this.txtDailyTotals.Text = ""; // // txtReport // this.txtReport.Location = new System.Drawing.Point(24, 280); this.txtReport.Multiline = true; this.txtReport.Name = "txtReport"; this.txtReport.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtReport.Size = new System.Drawing.Size(752, 80); this.txtReport.TabIndex = 7; this.txtReport.TabStop = false; this.txtReport.Text = ""; // // txtCategory3 // this.txtCategory3.Location = new System.Drawing.Point(88, 80); this.txtCategory3.Name = "txtCategory3"; this.txtCategory3.TabIndex = 6; this.txtCategory3.Text = ""; // // txtCategory2 // this.txtCategory2.Location = new System.Drawing.Point(88, 50); this.txtCategory2.Name = "txtCategory2"; this.txtCategory2.TabIndex = 5; this.txtCategory2.Text = ""; // // txtCategory5 //
file:///D|/1/final/BBL0116.html (173 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtCategory5.Location = new System.Drawing.Point(88, 140); this.txtCategory5.Name = "txtCategory5"; this.txtCategory5.TabIndex = 8; this.txtCategory5.Text = ""; // // txtCategory4 // this.txtCategory4.Location = new System.Drawing.Point(88, 110); this.txtCa tegory4.Name = "txtCategory4"; this.txtCategory4.TabIndex = 7; this.txtCategory4.Text = ""; // // btnEnter // this.btnEnter.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnEnter.Location = new System.Drawing.Point(220, 200); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(110, 25); this.btnEnter.TabIndex = 10; this.btnEnter.Text = "Enter Daily Sales"; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnReport // this.btnReport.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnReport.Location = new System.Drawing.Point(30, 240); this.btnReport.Name = "btnReport"; this.btnReport.Size = new System.Drawing.Size(140, 20); this.btnReport.TabIndex = 13; this.btnReport.TabStop = false; this.btnReport.Text = "View Monthly Report"; this.btnReport.Click += new System.EventHandler(this.btnReport_Click); // // label6 // this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label6.Location = new System.Drawing.Point(8, 185); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(72, 23); this.label6.TabIndex = 14; this.label6.Text = "Daily Totals"; // // txtMonth // this.txtMonth.Location = new System.Drawing.Point(290, 40); this.txtMonth.Name = "txtMonth"; this.txtMonth.Size = new System.Drawing.Size(20, 20); this.txtMonth.TabIndex = 1; this.txtMonth.Text = ""; // // label7 // this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label7.Location = new System.Drawing.Point(248, 40); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(32, 15); this.label7.TabIndex = 16; this.label7.Text = "Date:"; // // txtDay // this.txtDay.Location = new System.Drawing.Point(320, 40); this.txtDay.Name = "txtDay"; this.txtDay.Size = new System.Drawing.Size(20, 20); this.txtDay.TabIndex = 2; this.txtDay.Text = ""; // // txtYear // this.txtYear.Location = new System.Drawing.Point(350, 40); this.txtYear.Name = "txtYear";
file:///D|/1/final/BBL0116.html (174 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtYear.Size = new System.Drawing.Size(50, 20); this.txtYear.TabIndex = 3; this.txtYear.Text = ""; // // label8 // this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label8.Location = new System.Drawing.Point(310, 43); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(8, 20); this.label8.TabIndex = 20; this.label8.Text = "/"; // // label9 // this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.label9.Location = new System.Drawing.Point(340, 43); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(8, 20); this.label9.TabIndex = 20; this.label9.Text = "/"; // // btnViewDaily // this.btnViewDaily.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing. GraphicsUnit.Point, ((System.Byte)(0))); this.btnViewDaily.Location = new System.Drawing.Point(210, 130); this.btnViewDaily.Name = "btnViewDaily"; this.btnViewDaily.Size = new System.Drawing.Size(150, 25); this.btnViewDaily.TabIndex = 9; this.btnViewDaily.Text = "View Daily Sales Total"; this.btnViewDaily.Click += new System.EventHandler(this.btnViewDaily_Click); // // btnClear // this.btnClear.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnClear.Location = new System.Drawing.Point(500, 240); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(90, 20); this.btnClear.TabIndex = 21; this.btnClear.Text = "Clear Report"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnClose // this.btnClose.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((System.Byte)(0))); this.btnClose.Location = new System.Drawing.Point(590, 40); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(100, 20); this.btnClose.TabIndex = 22; this.btnClose.Text = "Close Program"; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(7, 13); this.ClientSize = new System.Drawing.Size(800, 402); this.Controls.Add(this.btnClose); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnViewDaily); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.txtYear); this.Controls.Add(this.txtDay); this.Controls.Add(this.label7); this.Controls.Add(this.txtMonth); this.Controls.Add(this.label6); this.Controls.Add(this.btnReport); this.Controls.Add(this.btnEnter); this.Controls.Add(this.txtCategory4); this.Controls.Add(this.txtCategory5); this.Controls.Add(this.txtCategory2);
file:///D|/1/final/BBL0116.html (175 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.Controls.Add(this.txtCategory3); this.Controls.Add(this.txtReport); this.Controls.Add(this.txtDailyTotals); this.Controls.Add(this.txtCategory1); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Name = "Form1"; this.Text = "The Cash Register"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void ClearForm() { txtMonth.Clear(); txtDay.Clear(); txtYear.Clear(); txtCategory1.Clear(); txtCategory2.Clear(); txtCategory3.Clear(); txtCategory4.Clear(); txtCategory5.Clear(); txtDailyTotals.Clear(); txtReport.Clear(); } private void Form1_Load(object sender, System.EventArgs e) { ClearForm(); txtMonth.Focus(); } private void btnEnter_Click(object sender, System.EventArgs e) { int day = Convert.ToInt16(txtDay.Text); dailySales[day-1].enterCategoryAmount(1,Convert.ToDecimal(txtCategory1.Text)); dailySales[day-1].enterCategoryAmount(2,Convert.ToDecimal(txtCategory2.Text)); dailySales[day-1].enterCategoryAmount(3,Convert.ToDecimal(txtCategory3.Text)); dailySales[day-1].enterCategoryAmount(4,Convert.ToDecimal(txtCategory4.Text)); dailySales[day-1].enterCategoryAmount(5,Convert.ToDecimal(txtCategory5.Text)); ClearForm(); txtMonth.Focus(); } private void btnViewDaily_Click(object sender, System.EventArgs e) { decimal theTotal = 0.00m; theTotal = Convert.ToDecimal(txtCategory1.Text); theTotal += Convert.ToDecimal(txtCategory2.Text); theTotal += Convert.ToDecimal(txtCategory3.Text); theTotal += Convert.ToDecimal(txtCategory4.Text); theTotal += Convert.ToDecimal(txtCategory5.Text); txtDailyTotals.Text = String.Format("{0:c}",theTotal); } private void btnReport_Click(object sender, System.EventArgs e) { decimal dailyTotal; decimal monthlyTotal = 0.00m; decimal[] categoryTotal = new decimal[5];
file:///D|/1/final/BBL0116.html (176 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
for(int cat = 1;cat<=5;++cat) categoryTotal[cat-1] = 0.00m; string output = String.Format("{0}\t{1}\t\t{2}\t\t{3}\t\t{4}\t\t{5}\t\t{6}\r\n", "Day","Cat1","Cat2","Cat3","Cat4","Cat5","Daily Total"); for(int day = 1;day <= 31;++day) { dailyTotal = 0.00m; output += String.Format("{0,2}",(day)); for(int cat = 1;cat <= 5;++cat) { dailyTotal += dailySales[day-1].returnCategoryAmount(cat); categoryTotal[cat-1] += dailySales[day-1].returnCategoryAmount(cat); output += String.Format("\t{0,15:c}",dailySales[day-1].returnCategoryAmount(cat)); } monthlyTotal += dailyTotal; output += String.Format("\t{0,15:c}",dailyTotal)+"\r\n"; } output += "\r\nTotals"; for(int cat = 1;cat <=5;++cat) output += String.Format("\t{0,15:c}",categoryTotal[cat-1]); output += String.Format("\t{0,15:c}",monthlyTotal)+"\r\n"; txtReport.Text = output; } private void btnClear_Click(object sender, System.EventArgs e) { ClearForm(); txtMonth.Focus(); } private void btnClose_Click(object sender, System.EventArgs e) { Application.Exit(); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 8/18/2006 // description This file along with CashRegister.cs, Form1.cs and // Program.cs form the program useCashRegister.exe. // namespace useCashRegister { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent()
file:///D|/1/final/BBL0116.html (177 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
{ this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.txtMonth = new System.Windows.Forms.TextBox(); this.txtDay = new System.Windows.Forms.TextBox(); this.txtYear = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.txtCategory1 = new System.Windows.Forms.TextBox(); this.txtCategory2 = new System.Windows.Forms.TextBox(); this.txtCategory3 = new System.Windows.Forms.TextBox(); this.txtCategory4 = new System.Windows.Forms.TextBox(); this.txtCategory5 = new System.Windows.Forms.TextBox(); this.txtDailyTotals = new System.Windows.Forms.TextBox(); this.btnClose = new System.Windows.Forms.Button(); this.btnViewDaily = new System.Windows.Forms.Button(); this.btnEnter = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnReport = new System.Windows.Forms.Button(); this.txtReport = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.Location = new System.Drawing.Point(40, 45); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(109, 20); this.label1.TabIndex = 0; this.label1.Text = "Category 1"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.Location = new System.Drawing.Point(40, 85); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(109, 20); this.label2.TabIndex = 1; this.label2.Text = "Category 2"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label3.Location = new System.Drawing.Point(40, 125); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(109, 20); this.label3.TabIndex = 2; this.label3.Text = "Category 3"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.Location = new System.Drawing.Point(40, 165); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(109, 20); this.label4.TabIndex = 3; this.label4.Text = "Category 4"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)
file:///D|/1/final/BBL0116.html (178 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
(0))); this.label5.Location = new System.Drawing.Point(40, 205); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(109, 20); this.label5.TabIndex = 4; this.label5.Text = "Category 5"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label6.Location = new System.Drawing.Point(40, 245); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(129, 20); this.label6.TabIndex = 5; this.label6.Text = "Daily Totals"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label7.Location = new System.Drawing.Point(392, 37); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(49, 20); this.label7.TabIndex = 6; this.label7.Text = "Date"; // // txtMonth // this.txtMonth.Location = new System.Drawing.Point(466, 37); this.txtMonth.Name = "txtMonth"; this.txtMonth.Size = new System.Drawing.Size(30, 27); this.txtMonth.TabIndex = 1; // // txtDay // this.txtDay.Location = new System.Drawing.Point(536, 37); this.txtDay.Name = "txtDay"; this.txtDay.Size = new System.Drawing.Size(30, 27); this.txtDay.TabIndex = 2; // // txtYear // this.txtYear.Location = new System.Drawing.Point(597, 38); this.txtYear.Name = "txtYear"; this.txtYear.Size = new System.Drawing.Size(70, 27); this.txtYear.TabIndex = 3; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label8.Location = new System.Drawing.Point(502, 41); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(19, 20); this.label8.TabIndex = 10; this.label8.Text = "/"; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label9.Location = new System.Drawing.Point(572, 40); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(19, 20); this.label9.TabIndex = 11; this.label9.Text = "/"; // // txtCategory1 // this.txtCategory1.Location = new System.Drawing.Point(215, 45);
file:///D|/1/final/BBL0116.html (179 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.txtCategory1.Name = "txtCategory1"; this.txtCategory1.Size = new System.Drawing.Size(100, 27); this.txtCategory1.TabIndex = 4; // // txtCategory2 // this.txtCategory2.Location = new System.Drawing.Point(215, 85); this.txtCategory2.Name = "txtCategory2"; this.txtCategory2.Size = new System.Drawing.Size(100, 27); this.txtCategory2.TabIndex = 5; // // txtCategory3 // this.txtCategory3.Location = new System.Drawing.Point(215, 125); this.txtCategory3.Name = "txtCategory3"; this.txtCategory3.Size = new System.Drawing.Size(100, 27); this.txtCategory3.TabIndex = 6; // // txtCategory4 // this.txtCategory4.Location = new System.Drawing.Point(215, 165); this.txtCategory4.Name = "txtCategory4"; this.txtCategory4.Size = new System.Drawing.Size(100, 27); this.txtCategory4.TabIndex = 7; // // txtCategory5 // this.txtCategory5.Location = new System.Drawing.Point(215, 205); this.txtCategory5.Name = "txtCategory5"; this.txtCategory5.Size = new System.Drawing.Size(100, 27); this.txtCategory5.TabIndex = 8; // // txtDailyTotals // this.txtDailyTotals.Location = new System.Drawing.Point(185, 245); this.txtDailyTotals.Name = "txtDailyTotals"; this.txtDailyTotals.ReadOnly = true; this.txtDailyTotals.Size = new System.Drawing.Size(130, 27); this.txtDailyTotals.TabIndex = 17; this.txtDailyTotals.TabStop = false; // // btnClose // this.btnClose.Location = new System.Drawing.Point(830, 65); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(162, 23); this.btnClose.TabIndex = 13; this.btnClose.TabStop = false; this.btnClose.Text = "Close Program"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnViewDaily // this.btnViewDaily.Location = new System.Drawing.Point(345, 240); this.btnViewDaily.Name = "btnViewDaily"; this.btnViewDaily.Size = new System.Drawing.Size(251, 23); this.btnViewDaily.TabIndex = 9; this.btnViewDaily.Text = "View Daily Sales Total"; this.btnViewDaily.UseVisualStyleBackColor = true; this.btnViewDaily.Click += new System.EventHandler(this.btnViewDaily_Click); // // btnEnter // this.btnEnter.Location = new System.Drawing.Point(345, 300); this.btnEnter.Name = "btnEnter"; this.btnEnter.Size = new System.Drawing.Size(251, 23); this.btnEnter.TabIndex = 10; this.btnEnter.Text = "Enter Daily Sales"; this.btnEnter.UseVisualStyleBackColor = true; this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click); // // btnClear // this.btnClear.Location = new System.Drawing.Point(830, 280); this.btnClear.Name = "btnClear";
file:///D|/1/final/BBL0116.html (180 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
this.btnClear.Size = new System.Drawing.Size(162, 23); this.btnClear.TabIndex = 12; this.btnClear.TabStop = false; this.btnClear.Text = "Clear Report"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnReport // this.btnReport.Location = new System.Drawing.Point(45, 300); this.btnReport.Name = "btnReport"; this.btnReport.Size = new System.Drawing.Size(225, 23); this.btnReport.TabIndex = 11; this.btnReport.TabStop = false; this.btnReport.Text = "View Monthly Report"; this.btnReport.UseVisualStyleBackColor = true; this.btnReport.Click += new System.EventHandler(this.btnReport_Click); // // txtReport // this.txtReport.Location = new System.Drawing.Point(20, 345); this.txtReport.Multiline = true; this.txtReport.Name = "txtReport"; this.txtReport.ReadOnly = true; this.txtReport.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtReport.Size = new System.Drawing.Size(1030, 250); this.txtReport.TabIndex = 18; this.txtReport.TabStop = false; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1087, 617); this.Controls.Add(this.txtReport); this.Controls.Add(this.btnReport); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnEnter); this.Controls.Add(this.btnViewDaily); this.Controls.Add(this.btnClose); this.Controls.Add(this.txtDailyTotals); this.Controls.Add(this.txtCategory5); this.Controls.Add(this.txtCategory4); this.Controls.Add(this.txtCategory3); this.Controls.Add(this.txtCategory2); this.Controls.Add(this.txtCategory1); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.txtYear); this.Controls.Add(this.txtDay); this.Controls.Add(this.txtMonth); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(4); this.Name = "Form1"; this.Text = "The Cash Register"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6;
file:///D|/1/final/BBL0116.html (181 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtMonth; private System.Windows.Forms.TextBox txtDay; private System.Windows.Forms.TextBox txtYear; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox txtCategory1; private System.Windows.Forms.TextBox txtCategory2; private System.Windows.Forms.TextBox txtCategory3; private System.Windows.Forms.TextBox txtCategory4; private System.Windows.Forms.TextBox txtCategory5; private System.Windows.Forms.TextBox txtDailyTotals; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Button btnViewDaily; private System.Windows.Forms.Button btnEnter; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnReport; private System.Windows.Forms.TextBox txtReport; } }
// program_id Form1.cs // written_by don voils // date_written 8/18/2006 // description This file along with CashRegister.cs, Form1.Designer.cs and // Program.cs form the program useCashRegister.exe. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using ViewCashRegister; namespace useCashRegister { public partial class Form1 : Form { private CashRegister[] dailySales = new CashRegister[31]; public Form1() { InitializeComponent(); txtMonth.Focus(); for (int day = 1; day <= 31; ++day) dailySales[day - 1] = new CashRegister(); } private void ClearForm() { txtMonth.Clear(); txtDay.Clear(); txtYear.Clear(); txtCategory1.Clear(); txtCategory2.Clear(); txtCategory3.Clear(); txtCategory4.Clear(); txtCategory5.Clear(); txtDailyTotals.Clear(); txtReport.Clear(); } private void btnViewDaily_Click(object sender, EventArgs e) { decimal theTotal = 0.00m; theTotal = Convert.ToDecimal(txtCategory1.Text); theTotal += Convert.ToDecimal(txtCategory2.Text); theTotal += Convert.ToDecimal(txtCategory3.Text); theTotal += Convert.ToDecimal(txtCategory4.Text); theTotal += Convert.ToDecimal(txtCategory5.Text);
file:///D|/1/final/BBL0116.html (182 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
txtDailyTotals.Text = String.Format("{0:c}", theTotal); } private void btnEnter_Click(object sender, EventArgs e) { int day = Convert.ToInt16(txtDay.Text); dailySales[day-1].enterCategoryAmount(1, Convert.ToDecimal(txtCategory1.Text)); dailySales[day-1].enterCategoryAmount(2, Convert.ToDecimal(txtCategory2.Text)); dailySales[day-1].enterCategoryAmount(3, Convert.ToDecimal(txtCategory3.Text)); dailySales[day-1].enterCategoryAmount(4, Convert.ToDecimal(txtCategory4.Text)); dailySales[day-1].enterCategoryAmount(5, Convert.ToDecimal(txtCategory5.Text)); ClearForm(); txtMonth.Focus(); } private void btnReport_Click(object sender, EventArgs e) { decimal dailyTotal; decimal monthlyTotal = 0.00m; decimal[] categoryTotal = new decimal[5]; for(int cat = 1;cat<=5;++cat) categoryTotal[cat-1] = 0.00m; string output = String.Format("{0}\t{1}\t\t{2}\t\t{3}\t\t{4}\t\t{5}\t\t{6}\r\n", "Day","Cat1","Cat2","Cat3","Cat4","Cat5", "Daily Total"); for(int day = 1;day <= 31;++day) { dailyTotal = 0.00m; output += String.Format("{0,2}",(day)); for(int cat = 1;cat <= 5;++cat) { dailyTotal += dailySales[day-1].returnCategoryAmount(cat); categoryTotal[cat-1] += dailySales[day-1].returnCategoryAmount(cat); output += String.Format("\t{0,11:c}", dailySales[day-1].returnCategoryAmount(cat)); } monthlyTotal += dailyTotal; output += String.Format("\t{0,11:c}",dailyTotal)+"\r\n"; } output += "\r\nTotals"; for(int cat = 1;cat <=5;++cat) output += String.Format("\t{0,11:c}",categoryTotal[cat-1]); output += String.Format("\t{0,11:c}",monthlyTotal)+"\r\n"; txtReport.Text = output; } private void btnClear_Click(object sender, EventArgs e) { ClearForm(); txtMonth.Focus(); } private void btnClose_Click(object sender, EventArgs e) { Application.Exit(); } } }
// program_id Program.cs // written_by don voils // date_written 8/18/2006 // description This file along with the CashRegister.cs, Form1.cs and // Form1.Designer.cs form the program useCashRegister.exe. // using System;
file:///D|/1/final/BBL0116.html (183 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
using System.Collections.Generic; using System.Windows.Forms; namespace useCashRegister { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id window1.cs // written_by don voils // date_written 1/11/2006 // description This is a windows form that simulates // an accounts receivable system. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace Window1 { /// <summary> /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox theAmount; private System.Windows.Forms.TextBox theBalance; private System.Windows.Forms.Button theCharge; private System.Windows.Forms.Button thePayment; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // theBalance.Text = "0.00"; theAmount.Text = ""; } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if(disposing) {
file:///D|/1/final/BBL0116.html (184 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.theAmount = new System.Windows.Forms.TextBox(); this.theBalance = new System.Windows.Forms.TextBox(); this.theCharge = new System.Windows.Forms.Button(); this.thePayment = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(65, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(150, 20); this.label1.TabIndex = 0; this.label1.Text = "Accounts Receivable"; // // label2 // this.label2.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label2.Location = new System.Drawing.Point(50, 70); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(65, 20); this.label2.TabIndex = 1; this.label2.Text = "Amount"; // // label3 // this.label3.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label3.Location = new System.Drawing.Point(50, 105); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(65, 20); this.label3.TabIndex = 2; this.label3.Text = "Balance"; // // theAmount // this.theAmount.Location = new System.Drawing.Point(160, 70); this.theAmount.Name = "theAmount"; this.theAmount.TabIndex = 1; this.theAmount.Text = ""; // // theBalance // this.theBalance.Location = new System.Drawing.Point(160, 105); this.theBalance.Name = "theBalance"; this.theBalance.TabIndex = 4; this.theBalance.TabStop = false; this.theBalance.Text = ""; //
file:///D|/1/final/BBL0116.html (185 von 186) [01.12.2007 04:50:10]
Lecture 13 Examples
// theCharge // this.theCharge.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.theCharge.Location = new System.Drawing.Point(170, 160); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(80, 25); this.theCharge.TabIndex = 3; this.theCharge.Text = "Charge"; this.theCharge.Click += new System.EventHandler(this.theCharge_Click); // // thePayment // this.thePayment.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.thePayment.Location = new System.Drawing.Point(60, 160); this.thePayment.Name = "thePayment"; this.thePayment.Size = new System.Drawing.Size(80, 25); this.thePayment.TabIndex = 2; this.thePayment.Text = "Payment"; this.thePayment.Click += new System.EventHandler(this.thePayment_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 272); this.Controls.Add(this.thePayment); this.Controls.Add(this.theCharge); this.Controls.Add(this.theBalance); this.Controls.Add(this.theAmount); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void theCharge_Click(object sender, System.EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance -= amount; theBalance.Text = String.Format("{0:n}",balance); theAmount.Text="0.00"; } private void thePayment_Click(object sender, System.EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance += amount; theBalance.Text = String.Format("{0:n}",balance); theAmount.Text="0.00"; } } }
file:///D|/1/final/BBL0116.html (186 von 186) [01.12.2007 04:50:10]
Lecture 14: File Input/Output and Object Serialization
Lecture 14: File Input/Output and Object Serialization Notice: This lecture contains the use of an Excel file: ARTotals.xls that is not included in this book. If you would like this file, email: [email protected]
Access to Stored Data Note: This lecture is only an introduction to working with data in C#. The lecture does not consider XML, SOAP and network file handling and it only contains a minimal discussion of memory and string data storage. As a program accesses data, the data is stored into what is called primary memory. That is the data is stored into the variables in memory that are in the RAM (random access memory i.e. the memory chips). Once the computer is turned off or the program moves from one section to another or is exited, the data stored in primary memory is lost. As a result, to save data from one session to the next, it is necessary to store data in what is called secondary storage or persistent storage. That is the data must be stored to devices like a floppy, a CD, a hard drive, a zip disk, a USB drive or a magnetic tape. Using one of these methods, data may be stored into what are called data files or into database files. C# has the ability to use any of these methods to store data. These notes will explore two methods of persistent data storage: i.e. data files and database files. This lecture will consider only data files. Note: C# has several different ways to approach file I/O. Only some of these approaches will be covered in the discussion below. When data is stored, the data will of course be a sequence of 0's and 1's. However these can be organized into several subdivisions to include: bytes, characters, fields, records and files. For example suppose that a program was to store the customer ID, the name of a customer and the balance due. Suppose that some of the data was to include: 1, George Washington, $1.25. Each of the symbols in this data would be a character. Each of the items: customer ID, first name, last name and balance due would be what is called a field. All of the information about each customer would be called a record. Lastly all of the data will be stored into a file in persistent storage. For example the data to be stored could be that which is included in the following table:
Open table as spreadsheet Field 1 Customer ID
Field 2 First Name
Field 3 Last Name
Field 4 Balance Due $1.25
Record 1
1
George
Washington
Record 2
93
Thomas
Doolittle
$32.33
Record 3
134
Jon
Le Moire
$421.33
Record 4
245
Juan
Sanchez
$532.64
Record 5
356
Heinrich
Schmitz
$1,343.23
Record 6
567
Wen
Wu
$4,632.33
In C# there are two general types of data files either text files or binary files. Storing data files into binary files is one way that is used when managing file storage for class objects. Regardless of which method of file access is
file:///D|/1/final/BBL0117.html (1 von 3) [01.12.2007 04:50:11]
Lecture 14: File Input/Output and Object Serialization
used, the following statement must be added at the top of the program to permit access to the C# input/output class library: using System.IO;
The namespace System.IO is contained in the file: System.IO.dll. This namespace contains classes, enumerations, structures and delegates needed for file I/O. The many classes in System.IO enable the program to read and write characters, strings and streams to files and memory as well as manipulate files and directories. Some of the classes in System.IO are listed in the following table:
Open table as spreadsheet Class
Description
BinaryReader
Permits the access to the system data types as well as binary values.
BinaryWriter
Permits the access to the system data types as well as binary values.
BufferedStream
Permits temporary storage for a stream of bytes that will be stored later.
Directory
Permits the manipulation of a directory or file as well as to create new files and new directories.
DirectoryInfo
Permits the extraction of information about a directory or a file.
File
Permits the manipulation of a directory or file as well as to create new files and new directories.
FileInfo
Permits the extraction of information about a directory or a file.
FileStream
Permits the random access to files when data is store as a stream of bytes.
MemoryStream
Permits the random access to files when data is stored in memory rather than a data file.
NetworkStream
Permits the access of data over a network.
StreamReader
Permits reading of text files.
SteamWriter
Permits writing to text files.
StringReader
Permits the reading of data stored in memory.
StringWriter
Permits the writing of data to memory.
In C# there are four main ways to store data that depend upon where the data is stored. Each of these storage methods is controlled by one of the classes listed above. For example, the classes are: FileStream (for storing/ accessing disk files), MemoryStream (for storing/accessing data in RAM), NetworkStream (for storing/accessing data files on a local area network) and BufferedStream (used with either of the previous classes for better data handling). Note: BufferedStream works best when used with NetworkStream. When a file is stored, it typically has a name and a directory path associated with it. A file may be considered as a sequential stream of bytes that ends with an end-of-file marker. When the program is opened, it is set to read or write. The file then becomes a stream that has three fundamental types of operations: ●
Reading - The transfer of data from a string into data structures such as an array of characters.
●
Writing - The transfer of data from a data structure to a stream.
file:///D|/1/final/BBL0117.html (2 von 3) [01.12.2007 04:50:11]
Lecture 14: File Input/Output and Object Serialization ●
Seeking - The query or modification of the current position using a stream.
Both the text file and the binary file read (and write) the data one byte after another until all of the file's data had been processed. This method of disk I/O is called synchronous file I/O. C# is also capable of processing of the data a little at a time. By this is meant that the computer is instructed to read (or write) data. While it is doing this, the computer's CPU can be used to process other instructions. Then after the data has been read (or written), the processing will return to the file I/O program for further instruction to the CPU. This processing of files I/O is called asynchronous file I/O i.e. part of the processing of the file takes place and then the CPU does other things. Later additional CPU processing of the file I/O takes place. This method of file I/O is best used when doing network processing of large data files so that the processing of data on the network does not come to a halt while the file I/O is processed. This type of file I/O will not be considered in these notes. Another distinction of file I/O is in what order the data is to be read from the file. In general, data is read one field or one record at a time and then the program moves to the next field or record. This is what is called sequential access. Another way is for the user to specify which record in the file is to be processed, have the program go to that particular record in the file and then to process it without processing any of the other records in the file. This method of file I/O is called random access. In C# binary files may use random access for file I/O.
file:///D|/1/final/BBL0117.html (3 von 3) [01.12.2007 04:50:11]
File and Directory Management
File and Directory Management C# has several classes that permit the reading and management of files and storage locations like drives and directories. These classes are: Directory, File, FileSystemInfo, DirectoryInfo and FileInfo. The classes: Directory, File and FileSystemInfo are derived from the class Object. The classes DirectoryInfo and FileInfo are derived from FileSystemInfo. These relationships are illustrated in the following graphic:
These classes contain methods for accessing, creating and moving files or directories. The classes: File and Directory have static methods. The classes FileInfo and DirectoryInfo have non-static methods and attributes. Both the File and the FileInfo classes help to manage the files. Both the Directory and the DirectoryInfo classes help to manage the directories (i.e. folders). The following table lists some of the methods of the Directory class:
Open table as spreadsheet
file:///D|/1/final/BBL0118.html (1 von 6) [01.12.2007 04:50:13]
File and Directory Management
Members
Description
CreateDirectory()
Creates all directions and subdirectories specified by it path parameter
Delete()
Deletes the directory and deletes all of its contents
Exists()
Returns a Boolean value, true if the path provided as a parameter leads to an existing directory.
GetCreationTime()
Returns the creation date and time of the directory.
SetCreationTime()
Sets the creation date and time of the directory.
GetCurrent directory ()
Returns the current directory.
SetCurrentDirectory()
Sets the current directory.
GetDirectories()
Gets an array of subdirectories.
GetDirectoryRoot()
Returns the root of the specified path.
GetFiles()
Returns an array of strings with the filenames for the files in the specified directory.
GetLastAccessTime()
Returns the last time the specified directory was accessed.
SetLastAccessTime()
Sets the last time the specified directory was accessed.
GetLastWriteTime()
Returns the last time the specified directory was written to‥
SetLastWriteTime()
Sets the last time the specified directory was written to‥
GetLogicalDrive()
returns the names of all of the logical drives in the form :\.
GetParent()
Returns the parent directory for the specified path.
Move()
Moves a directory and its contents to a specified path.
The following table lists some of the static methods of the File class:
Open table as spreadsheet Methods
Description
AppendText()
Creates a StreamWriter that appends text to the specified file.
Copy()
Copies an existing file to a new file.
Create()
Creates a file in the specified path.
CreateText()
Creates a StreamWriter that writes a new text file to the specified file.
Delete()
Deletes the specified file.
Exists()
Returns true if the specified file exist and otherwise it returns false.
GetAttribute()
Gets the FileAttributes of the specified file.
SetAttribute()
Sets the FileAttributes of the specified file.
GetCreationTime()
Returns the creation date and time of the file.
SetCreationTime()
Sets the creation date and time of the file.
GetLastAccessTime ()
Returns the last time the specified files was accessed.
SetLastAccessTime()
Sets the last time the specified files were accessed.
GetLastWriteTime()
Returns the last time the specified file was written to.
SetLastWriteTime()
Sets the last time the specified file was written to.
file:///D|/1/final/BBL0118.html (2 von 6) [01.12.2007 04:50:13]
File and Directory Management
Move()
Moves a file to a new location, and it can be used to rename a file.
OpenRead()
Opens the FileStream on the file.
OpenWrite()
Creates a read/write Stream on the specified path.
As indicated above, the class: FileSystemInfo is derived from Object and it is the base class for the classes: DirectoryInfo and FileInfo. The following table contains some of the members of the class FileSystemInfo:
Open table as spreadsheet Member
Description
Attributes
Gets or sets the attributes associated to the current file, that is represented by the FileAttributes enumeration.
CreationTime
Gets or sets the time of creation for the current file or directory.
Delete()
Method permits the deletions of a specified file or directory.
Exists
Can be used to determine if a given file or directory exists.
Extension
May be used to retrieve a file's extension.
FullName
Gets the full path of the directory or file.
LastAccessTime ()
Gets or sets the time when the current file or directory was accessed.
LastWriteTime
Gets or sets the time when the current file or directory was last written to.
Name
Returns the name of a given files and is a read-only property. Gets the name of the last directory hierarchy if possible or otherwise retrieves the fully qualified name.
Refresh()
When called prior to seeking information about a file or directory updates the information about the file or directory.
For an example using some of the members of FileSystemInfo above using the derived class: DirectoryInfo see: DirectoryInfo2.cs. The following table contains some of the members of the class: DirectoryInfo:
Open table as spreadsheet Member
Description
Attributes
Inherits from FileSystemInfo and gets or sets the attributes of the current file.
CreationsTime
Inherits from FileSystemInfo and gets or sets the creation time of the current file.
Exists
Public property and is a Boolean value, true if the directory exists.
Extension
Public property inherited from FileSystemInfo that is the file extension.
FullName
Public property inherited from FileSystemInfo that is the full path of the file.
LastAccessTime
Public property inherited from FileSystemInfo that gets or sets the last access time.
LastWriteTime
Public property inherited from FileSystemInfo that gets or sets the last write time.
file:///D|/1/final/BBL0118.html (3 von 6) [01.12.2007 04:50:13]
File and Directory Management
Name
Public property name of this instance of DirectoryInfo.
Root
Public property root portion of the path.
Create()
Creates a directory given a path name.
CreateSubdirectory ()
Creates a subdirectory given a path name.
Delete()
Deletes a directory and all of its files.
GetDirectoryies()
Gets an array of strings that represent all subdirectories in the current directory.
GetFiles()
Gets the files in the specified directory as an array of FileInfo types.
MoveTo()
Moves a directory and its contents to a new path.
Refresh()
Public method inherited from FileSystemInfo. refreshes the state of the object.
Parent
Returns the parent directory of the specified path.
For an second example using some of the members of DirectoryInfo see: DirectoryInfo1.cs Compile and run the program. Notice that this program created three folders: One using the name of the company you entered, one with the name: Expenses and another with the name: Sales. Next see DirectoryInfo3.cs. Take this program an compile and run it. After running the program look at the folders in the project folder. Next create a folder by the name of TheAccounting. Place the executable of this program in that folder. Run the program and compare the result of this program with the program in DirectoryInfo1.cs. Observe the new folders in the folder: TheAccounting. The following is table contains some of the FileInfo members:
Open table as spreadsheet Member
Description
Attrubutes()
Inherits from FileSystemInfo gets or sets the attributes of the current file.
CreationTime
Inherits from FileSystemInfo gets or sets the creation time of the current file.
Directory
Public property that gets an instance of the parent directory.
Exists
Public property Boolean value, true if the directory exists.
Extension
Public property inherited from FileSystemInfo, the file extension.
FullName
Public property inherited from FileSystemInfo, the full path of the file or directly.
LastAccessTime
Public property inherited from FileSystemInfo, gets or sets the last access time.
LastWriteTime
Public property inherited from FileSystemInfo gets or sets the time when the current file or directory was last written to‥
AppendText()
Creates a StreamWriter type that appends text to a file.
CopyTo()
Copies an existing file to a new file.
Create()
Creates a new file and returns a FileStream type to interact with the created file.
CreateText()
Creates a StreamWriter type that writes a new text file.
Delete()
Deletes the file to which a FileInfo instance is bound.
Directory
Gets an instance of the parent directory.
DirectoryName
Gets the full path of a file.
Length
Gets the size of the current file or directory
file:///D|/1/final/BBL0118.html (4 von 6) [01.12.2007 04:50:13]
File and Directory Management
MoveTo()
Moves a specified files to a new location, providing the options to specify a new file name.
Name
Gets the name of a file.
Open()
Opens a file with read/write and sharing ability.
OpenRead()
Creates a read only FileStream
OpenText()
Creates a StreamReader type that reads from an existing text file.
OpenWrite()
Creates a read/write FileStream Type
For an example using some of the members of the class FileInfo see FileInfo1.cs. The following table contains some of the FileAttributes enumerators:
Open table as spreadsheet Enumerator
Description
Archive
Permits the change of the file's archive status so that it may be marked for backup or removal status.
Compressed
Makes the file compressed.
Directory
Makes the file a directory.
Encrypted
Makes the file encrypted.
Hidden
Makes the file hidden and thus is not included in an ordinary directory.
Normal
The file is set to normal status and it has not other attributes set.
Offline
The file is set to offline and therefore the data is not immediately available.
ReadOnly
Makes the file read only.
System
Makes the file a system file and therefore only to be used exclusively by the operating system.
The following table contains the enumerators of the FileMode enumerated data type:
Open table as spreadsheet Enumerator
Description
Append
Opens the file if it exists and seeks the end of the file. If the file does not exist, a new file is created. It must be used in conjunction with the FileAccess enumerator Write.
Create
Specifies that the operating system should create a new file. If the file already exists, the file is overwritten.
CreateNew
Specifies that the operating system should create new file. If the file already exists, an IOException is thrown.
Open
Specifies that the operating system should open an existing file.
OpenOrCreate
Specifies that the operating system should open a file it is exists or otherwise create a new file.
Truncate
Specifies that the operating system should open an existing file and change its size of 0 bytes.
file:///D|/1/final/BBL0118.html (5 von 6) [01.12.2007 04:50:13]
File and Directory Management
The following table contains the enumerators of the FileAccess enumerated data type:
Open table as spreadsheet Enumerator
Description
Read
Specifies read only to the file
ReadWrite
Specifies read and write access to the file.
Write
Specifies write access to the file.
For an example the use of some of the enumerators of FileMode and FileAccess see FileMode1.cs. The following table contains the enumerators of the FileShare enumerated data type.
Open table as spreadsheet Enumerator
Description
None
Prevents sharing of the file. Any request to open fails until the file is closed.
Read
Permits opening of the file for the purpose of reading. If this flag is not specified, then any request to open the file for reading fails until the file is closed.
ReadWrite
Permits the opening of the file for the purpose of reading or writing to the file. If this flag is not specified, then any request to open the file will fail.
Write
Permits the opening of the file for the purpose of writing to the file. If this flag is not specified, then any request to write will fail.
For a console example of viewing the directories see DirectoryManagement.cs. Notice how the class DirectoryInfo is used to move up and down the directory tree using the recursive method: ExploreDirectories(). Using basically the same problem but including the use of the class FileInfo, the program: FileManagement.cs provides similar information about the files and the folders in which they are contained.
file:///D|/1/final/BBL0118.html (6 von 6) [01.12.2007 04:50:13]
The Stream Class
The Stream Class The abstract class: Stream provides functionality for representing streams as bytes. The class Stream is derived from the class Object. The objects from the classes derived from the class Stream work with data that is a stream of bytes rather than text-based data. In addition to reading and writing bytes, it is also possible to seek a particular location within the byte stream. The following table lists some of the Stream class members:
Open table as spreadsheet Member
Description
BeginRead ()
Used with asynchronous input for the purpose of improving CPU processing so that the data may be read when the processor permits it. It is used with a delegate to tell the program when to read.
BeginWrite ()
Used with asynchronous output for the purpose of improving CPU processing so that the data may be written when the processor permits it. It is used with a delegate to tell the program when to write.
CanRead
Determines whether the current Stream supports reading.
CanSeek
Determines whether the current Stream supports seeking.
CanWrite
Determines whether the current Stream supports writing.
Close()
Close the current Stream and releases any resources associated with the Stream.
Flush()
If the Stream supports a buffer, it updates the buffer.
Length
Returns the length of the Stream in bytes.
Position
Returns the current Position within the Stream.
Read()
Reads a sequence of bytes from the Stream and advances the Position in the Stream by the number of bytes read.
ReadByte()
Reads a bytes from the Stream and advances the position in the Stream for bytes read.
Seek()
Sets the Position in the Stream.
SetLength()
Sets the Length of the Stream.
Write()
Writes a sequence of bytes to the Stream and advances the position by the number of bytes written.
WriteByte()
Writes a byte to the Steam and advances the position one byte.
The BufferedStream, FileStream and MemoryStream classes are derived from the Stream class.
file:///D|/1/final/BBL0119.html (1 von 4) [01.12.2007 04:50:14]
The Stream Class
The BufferedStream class contains methods to transfer byte data to or from a stream using a region in memory called a buffer. A program can use the FileStream class to read byte data from and write byte data to sequentialaccess or to random-access files. The MemoryStream class enables the transfer of byte data directly to and from memory. Using the BufferedStream, byte data may be stored to a buffer and then transferred to a data file. For example the following code would achieve this objective: FileStream theFile = new FileStream("theData.txt", FileMode.Create, FileAccess.ReadWrite); BufferedStream myFileBuffer = new BufferedStream(theFile); byte[] theBuffer = {0x55, 0x71, 0x4, 0x0, 0x0, 0x16,0xAB,0x44,0x35}; myFileBuffer.Write(theBuffer, 0, theBuffer.Length); myFileBuffer.Close();
The following is an example using an object of the class: BufferedStream: BufferedStream1.cs. Compile and run the program. After running the program, look at the data file: theData.txt in the folder: \bin\Debug of your project and notice the byte data that was transferred to the file.
file:///D|/1/final/BBL0119.html (2 von 4) [01.12.2007 04:50:14]
The Stream Class
MemoryStream objects create memory files for the purpose of storing and accessing byte data rather than physical files as is done with objects of FileStream. Some of the MemoryStream members are the following:
Open table as spreadsheet Member
Description
Capacity
Gets or sets the number of bytes allocated for this Stream.
GetBuffer ()
Returns the array of unsigned bytes from which the Stream was created.
ToArray()
Writes the entire Stream to a byte array.
WriteTo()
Writes the entire contents of the MemoryStream to another stream-derived type such as a file.
The following code would create a memory object, write data to it, display the data stored in memory and then store the data to a file. MemoryStream myMemoryStream = new MemoryStream(); myMemoryStream.Capacity = 30; for(int i = 0; i < 30; i++) { myMemoryStream.WriteByte((byte)i); } myMemoryStream.Position = 0; for(int i = 0; i < 30; i++) { Console.WriteLine(myMemoryStream.ReadByte()); } Console.WriteLine(); FileStream theFile = new FileStream("theMemory.txt", FileMode.Create, FileAccess.ReadWrite); myMemoryStream.WriteTo(theFile);
For an example of this program see MemoryStream1.cs. Compile and run the program notice the data that was transferred to the data file: theMemory.txt. The class: FileStream provides for the option to create file based streaming. LIke DirectoryInfo and FileInfo, FileStream objects have the ability to open existing files and to create new ones. FileStream objects are created with FileMode, FileAccess and FileShare enumerators. The following code would create a file: myData.txt and write the bytes to the file and then read the data back and display it on the screen: FileStream theStream = new FileStream("myData.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); for(int index = 65; index < 125;++index) theStream.WriteByte((byte)index); theStream.Position = 0;
file:///D|/1/final/BBL0119.html (3 von 4) [01.12.2007 04:50:14]
The Stream Class
for(int index = 65; index < 125; ++index) Console.WriteLine(theStream.ReadByte());
For example see FileStream1.cs. After you have compiled and ran this example, look at the contents of the data file: myData.txt in the folder: \bin\Debug of your project and compare it with what was displayed on the screen.
file:///D|/1/final/BBL0119.html (4 von 4) [01.12.2007 04:50:14]
Text File Input/Output
Text File Input/Output The classes TextReader and TextWriter are derived from the class: Object. These classes are used to read and write Unicode character data from streams and strings. The classes StreamReader and StringReader are derived from TextReader. The classes StreamWriter and StringWriter are derived from the class TextWriter.
Text File Output The following are some of the members of the class TextWriter.
Open table as spreadsheet Member
Description
Close()
Closes the TextWriter object and frees associated resources as well as buffers which are flushed as a result of this method.
Flush()
Clears any buffers associated with the TextWriter object and forces any data in the buffer to be written to the associated device without closing the object.
NewLine
Used to create a new line character for the object. It is similar to "\r\n".
Write()
Writes a line of data to the object without a new line character. This method is similar to the Write() method for the Console class.
WriteLine ()
Writes a line of data to the object and terminates the data with a new line character. This method is similar to the Console's WriteLine().
file:///D|/1/final/BBL0120.html (1 von 5) [01.12.2007 04:50:15]
Text File Input/Output
The class StreamWriter implements each of the members of TextWriter above In addition the class has the member: AutoFlush. When set to true, this property forces the object to flush the buffer very time it writes. While this is an option, some recommend that AutoFlush should be set to false and then use Close() or Flush() to achieve this objective. In this way the system's resources would be better utilized. The next example will be considered text file output. This may be done using either the console or the Windows GUI environment. Only the console approach will be considered here. One of the major differences between these two types of approaches to file I/O is that in the GUI, it is much easier to select a particular file to access. In the console program, it is best to specify the data file in the code although this is not a requirement. Inside of the program's class definition the text file could be named with a statement like the following: static string fileName = @"datafile.txt";
Recall that the symbol: @ reduces the need for special characters in strings. The file may be located in any storage location by including the proper drive and path. This code will place the data in the text file: datafile.txt in the Debug subfolder of the bin folder for the program. The text file: datafile.txt is the storage file that will contain the data (there is nothing about this particular name that is required). (Although the examples include a few exception statements, more exception statements should be included in each program to handle the cases where either the file can not be found, opened, closed or the data may not be processed for some reason.) Another statement that is needed is the following: static FileStream writeFileStream;
The statement above defines an object writeFileStream (this could be any name) of the class FileStream that permits output of data. This class deals with the access to the environment outside. A statement like the following should also be included: static StreamWriter fileWriter;
The statement above defines an object fileWriter (this could be any name) of the class StreamWriter that is required for file output of text data. This class handles the data within the program before sending it out. The conditionals below are required to close the objects if they are already open to avoid an exception and thereby a crashing of the program. if(fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close();
The objects for the classes FileStream and StreamWriter need to be instantiated with statements similar to the following: writeFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); file:///D|/1/final/BBL0120.html (2 von 5) [01.12.2007 04:50:15]
Text File Input/Output
These two statements instantiate the objects: writeFileSream and fileWriter respectively. They will provide for the connecting of the program to the data file represented by fileName. Note: That the class: FileStream has overloaded constructors with several forms whose different options can be used to regulate how the file is accessed. Recall that FileMode and File Access are enumerated data types that regulate how the file will access the data. The FileMode options are: Append, CreateNew, Create, Open, OpenCreate and Truncate
The FileAccess options are: Read, Write and ReadWrite
While this program does not use the enumerated data type: FileShare, its enumerators are: None, Read, ReadWrite and Write
which could be used to control access to the file over a network. In the code where the data is received from the input there should be a line like the following: fileWriter.WriteLine(theData);
This line of code will send what ever is stored in theData variable to the file buffer associated with fileWriter and from there to the file. Notice the use of the method WriteLine() above. This method is similar to the WriteLine() used with Console. The difference is that the WriteLine() for Console is a static method while the method WriteLine() for StreamWriter is a non-static method and it must therefore be doted with an object like fileWriter. After all of the data for a record has been written to the output buffer fileWriter, the buffer should be cleared to ensure that the data has all been written to the data file. This can be done by using the StreamWriter method Flush () as in the following statement: fileWriter.Flush();
For an example of output to a text file, view the following: WriteToTextFiles.cs. This program implements the customer data specifications listed in the table above. Note: In the program above the location of the data file was changed to enable an exchange between this example and the next one that reads the data stored in the data file. The data file name used was: @"‥\‥\‥\‥ \datafile.txt ". This particular name will place the data file in the same folder with all of the Visual Studio Projects on your system. Create a C# Console program: WriteToTextFiles. Copy the code from the link above and replace the Program.cs file. Compile and run the program using the data in the table above. After you have stored these records to the disk, open the file: datafile.txt in NotePad and examined the file's contents. Notice that each field is listed one line after another and that the records that were entered are listed one after the other. Run the program on the following data and find the file: datafile.txt and notice where it is located. file:///D|/1/final/BBL0120.html (3 von 5) [01.12.2007 04:50:15]
Text File Input/Output
Open table as spreadsheet ID
First Name
Last Name
Owes
1
George
Washington
$2,393.30
2
Thomas
Jefferson
$4,233.30
3
John
Adams
$5,433.44
4
John Quincy
Adams
$4.40
5
Theodore
Roosevelt
$4,323.45
If you run this program more than once, then each time the program is run, the previous data would be overwritten. To avoid this, the program could have the FileMode enumerator be Append rather than OpenCreate. To observe this action, change the FileMode to Append and try the program several times. After you have done this, open the file datafile.txt into NotePad again and observe the difference between this modification of the program and the previous implementation. Another variation of this program is WriteToTextFiles2.cs. It uses an object of the class FileInfo instead of an object of the class FileStream. Compile and run the program. Next open its data file: datafile2.txt which should be in the same folder as the file: datafile.txt from the previous program
Text File Input Some of the members of the class TextReader are listed in the table below:
Open table as spreadsheet Member
Description
Peek()
Returns the next character without advancing the stream position.
Read()
Reads data from the input stream and advances the stream position.
ReadBlock()
Reads a maximum of count characters from the stream and writes the data to the associated buffer beginning at index.
ReadLine()
Reads a line of character data from the stream and returns the data as a string.
ReadToEnd ()
Reads all of the character data from the current position to the end of the TextReader and stores them into a string.
To read the text data in from storage, the code of the program is similar to that used for writing to the data file. The major difference is that instead of using an object of the class StreamWriter, an object of the class StreamReader is used instead. The following lines of code for reading data are similar to the lines of code in the discussion for text output above and they define the objects needed in this program: static string fileName = @"‥\‥\‥\‥\datafile.txt"; static FileStream readFileStream; static StreamReader fileReader;
and the following statements check to see if the objects have been instantiated followed by their instantiations:
file:///D|/1/final/BBL0120.html (4 von 5) [01.12.2007 04:50:15]
Text File Input/Output
if(readFileStream!=null) readFileStream.Close(); if( fileReader!=null) fileReader.Close();
Note: There is nothing unique about the names of the objects: readFileStream and fileReader used above. Other names could be used instead. The objects for the classes FileStream and StreamReader need to be instantiated with statements similar to the following: readFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream);
and to bring the data in, a statement like the following method call is needed. fileReader.ReadLine(theData);
Notice the use of ReadLine() above. As with WriteLine(), this ReadLine() is a non-static method of the class StreamReader and therefore it must be dotted with an object like: fileReader. The program must determine whether all of the data in the text file has been read. To do this the while() loop can be coded to determine whether there is more data to read or not. A statement like the following could be used to determine when the end of the data is reached. The ..... below indicates that there is additional code which is left out: 534 while(theData != null) { ..... }
For an example of input of the same text file: datafile.txt used in the previous console example view the following: ReadFromTextFiles.cs. Create a C# console project using the name of this file as the name of the project Copy this program over the default Program.cs of the project. Compile and run the program as you did in the previous example.(Note: Since datafile.txt was saved at the root of Visual Studio .NET Projects, this program may access the data using the following path: @"‥\‥\‥\‥\datafile.txt".) Notice how the program reads in the data that was stored into the file: datafile.txt by the program WriteToTextFiles.cs discussed above. Another variation of this program is ReadFromTextFiles2.cs. It uses an object of the class FileInfo instead of an object of the class StreamReader. Create a project with this name, compile and run it. Notice that this program reads in the data that was stored into the file datafile2.txt by the program: WriteToTextFiles2.cs discussed above.
file:///D|/1/final/BBL0120.html (5 von 5) [01.12.2007 04:50:15]
Binary File Input/Output and Serialization
Binary File Input/Output and Serialization Using text file I/O is not the best way to handle I/O of class objects. It is much more efficient to read and write the entire object rather than using each field as is necessary with text file I/O. To better handle I/O for class objects, binary file I/O should be considered. The major class that is needed for binary file input and output is the class BinaryFormatter. This class is a member of the namespace: System.Runtime.Serialization.Formatters.Binary
The class BinaryFormatter works in conjunction with IFormatter objects to perform the input and output of class objects. However, in order for this to occur, the class whose objects are being processed must be declared as Serializable. Serialization involves converting an object into a format that can be written without losing any of the object's data. In addition when the objects are read from the file, they must be Deserialized. Deserialization consists of reading this format from a file and then reconstructing the original object from the data read. The BinaryFormatter class contains the following methods to implement this process:
Open table as spreadsheet Method
Description
Deserialize ()
Deserializes the stream of bytes read from a binary file into an object.
Serialize()
Serializes an object to a stream of bytes for the purpose of storing the data in a binary file.
As stated above, an object of a class to be accessed using binary files requires that the class must be defined as serializable. Serialization means that the attributes are constructed as a series of bytes. This construction is accomplished by adding above the class' definition the statement: [Serializable]. In addition, if some of the attributes of the class are also objects of another class (i.e. a composition of classes), then the class of these objects must also be serializable. Further, if the class that is being accessed is derived from another class or a series of classes, then each of the classes in the hereditary tree must also be serializable. To understand binary files, the same sample data that was used for the text file above will be used in the examples of this section of the lecture. For this example, the class Customer was modified. It is stored in the file: customer. cs. Open the file and notice how it is different from the previous examples of classes because it has the statement [Serializable] listed above the class' definition.
Binary File Output Create a C# Console project called: WriteToBinaryFile. Copy the Customer's class file listed above to the project. A program will now be written to send objects of this class to a binary file. To begin copy the following statements to the top of the project to implement the formatting of the binary files and for the implementing of serialization: using System; using System.Collections.Generic; using System.Text; using System.IO;. using System.Runtime.Serialization;
file:///D|/1/final/BBL0121.html (1 von 4) [01.12.2007 04:50:16]
Binary File Input/Output and Serialization
using System.Runtime.Serialization.Formatters.Binary;
Because the class Customer in the file above may be used in different programs, the class' namespace is different from the program's namespace. Notice that the namespace in this file is: Customers. As a result, the following using needs to be added immediately after the other using statements listed above in order to use this class: using Customers;
Immediately after Main(), statements like the following definitions are needed (another file name and location could have been used or the program could have used code to select the desired file): Customer theCustomer = new Customer(); IFormatter serializer = new BinaryFormatter(); FileStream theOutFile = new FileStream("Customers.dat", FileMode.Append, FileAccess.Write);
As with the text file example above, there are several possible argument options for the enumerators of FileMode and FileAccess. In this case, the file is going to be opened and appended for the purpose of writing to the file: Customers.dat. This file will then be used in the example below where the binary data is read in. To help handle the keyboard input, a loop like the following could be used: char moreData = 'Y'; while ((moreData == 'Y') || (moreData == 'y')) { Console.Clear(); Console.Write("\n\nWhat is the customer's ID? "); theCustomer.customerID = Console.ReadLine(); Console.Write("\n\nWhat is the customer's first name? "); theCustomer.firstName = Console.ReadLine(); Console.Write("\n\nWhat is the customer's last name? "); theCustomer.lastName = Console.ReadLine(); Console.Write("\n\nHow much does the customer owe? "); theCustomer.balanceDue = decimal.Parse(Console.ReadLine()); serializer.Serialize(theOutFile, theCustomer); Console.Write("\n\nEnter another customer (Y/N)? "); moreData = Char.Parse(Console.ReadLine()); }
theOutFile.Close(); Console.Clear();
Notice in the code above that after the data is stored into the object theCustomer, it is written to the data file with a statement like the following: serializer.Serialize(theOutFile, theCustomer);
The BinaryFormatter method Serialize() reformats the objects being sent to the binary data file.
file:///D|/1/final/BBL0121.html (2 von 4) [01.12.2007 04:50:16]
Binary File Input/Output and Serialization
Go to the bin\Debug folder of this project and open the file: Customers.dat using Notepad. Notice that some of the data is viewable.
Binary File Input After the data has been stored to the data file, a program needs to be written to access the binary data. Name this project: ReadFromBinaryFiles. Add the class file: customer.cs to the project. As with the previous program, the top needs the following using statements: using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers;
Just below: Main(), statements like the following definitions are needed (another data file name and file location could of course have been used or the program could have permitted the user to have selected both of these using a menuing system like the examples in a previous lecture.) Customer theCustomer = new Customer(); IFormatter serializer = new BinaryFormatter(); theInFile = new FileStream("Customers.dat", FileMode.Open, FileAccess.Read);
In order for the data to be read into a Customer object, it must be deserialized as it is read in. This is done with a line of code like the following (notice the type casting using the as keyword): theCustomer = serializer.Deserialize(theInFile) as Customer;
Because of the nature of this type of file I/O, exiting from while() loop is implemented using a try block with a SerializationException in the catch(). The SerializationException is contained in the namespace: System. Runtime.Serialization. The following code then contains the necessary statements to input all of the data to the screen in a formatted manner: try { Customer theCustomer = new Customer(); IFormatter serializer = new BinaryFormatter(); theInFile = new FileStream("Customers.dat", FileMode.Open, FileAccess.Read); Console.WriteLine("{0,15} {1,20} {2,15}\n", "Customer's ID", "Customer's Name", "Balance due"); // The following loop continues until there is no more data // then an exception occurs to end the try block. The catch() // with the SerializationException catches the end of file // error and the program terminates successfully. // while (true) { theCustomer = serializer.Deserialize(theInFile) as Customer; Console.WriteLine("{0,15} {1,-20} {2,15:c}",
file:///D|/1/final/BBL0121.html (3 von 4) [01.12.2007 04:50:16]
Binary File Input/Output and Serialization
theCustomer.customerID,theCustomer.firstName + " " + theCustomer.lastName,theCustomer.balanceDue); theTotalDue += theCustomer.balanceDue; } } catch (SerializationException) { Console.WriteLine("\nTotal Account Receivable {0,27:c}", theTotalDue); Console.ReadKey(); } // The following catch will activate if the file did not open. // catch (IOException e) { Console.WriteLine("An IO exception has occurred."); Console.WriteLine(e.ToString()); }
Copy to this project's bin\debug folder, the data file: Customers.dat created when the output program above was run. Compile and run this program. Notice that the data which was entered from the previous example is read and then written to the screen in a business formatted manner.
file:///D|/1/final/BBL0121.html (4 von 4) [01.12.2007 04:50:16]
Binary File Random Access
Binary File Random Access While objects could be considered records, they can not be stored directly into binary files using random access file techniques. Instead object's field values must be stored into the file individually rather than as the entire object. The reason for this is that in order to use an object for binary file I/O, its class must be serialized and this prevents the object from being used directly for random access. While this is true, there is a way around this problem. To implement random access with objects, the class must not be serialized. Look at the class: NewCustomer in the file: NewCustomer.cs. Observe that this class is similar to the class Customer used above. One of the major differences is that this new class is not serialized. In addition the class NewCustomer contains no string fields. The string fields have all been converted to char arrays. If the user enters in too large of a string for the array, the extra characters are removed. If the string is too short, spaces are added to the array. In this way the actual size of the data will be fixed by using the dimension of each char array. Since a string variable could be of any size, this would eliminate the ability to have a fixed distance between the records. When viewing the file NewCustomer.cs, pay particular attention to the properties of these fields and how they differ from the field properties of the class Customer. In addition observe a new static field: theSize has been defined. This variable contains the sum of the sizes of all of the fields of an object in bytes. This value then is the size of each record. Notice the following in the class definition: private const int CHAR_ARRAY_LENGTH = 15; private const int SIZE_OF_CHAR = 2; private const int SIZE_OF_INT32 = 4; private const int SIZE_OF_DECIMAL = 8; private const Size = 2 * (SIZE_OF_CHAR + CHAR_ARRAY_LENGTH) + SIZE_OF_INT32 + SIZE_OF_DECIMAL;
This class can be used in the random access. First look at the file WritingRandomAccess.cs When viewing this program, pay particular attention to the methods: CreateFile() and CreateMoreRecords(). When the file is accessed the first time, the file does not exist. As a result, an exception is thrown. The catch() diverts the program to the method CreateFile(). This method then creates 100 records using the following loop: for(int index = 0; index < NUMBER_NEW_RECORDS; ++ index) { binaryOutput.Write(blankRecord.customerID); binaryOutput.Write(blankRecord.firstName); binaryOutput.Write(blankRecord.lastName); binaryOutput.Write(blankRecord.balanceDue); binaryOutput.Flush(); }
The variable NUMBER_NEW_RECORDS is a constant variable with the value of 100. As a result, 100 records are created in this loop. The NewCustomer object blankRecord was created to populate these 100 records. Because of the NewCustomer's default constructor, there is no data in this object. Note that there is no data transmitted to these 100 records. After the method CreateFile() was executed, the file "randomAccess.dat" starts out with 100 empty records. (This particular location enables both the reading and the writing programs to access the data.) Another difference between this implementation of the customer problem and the previous one above is that the customer ID's in this binary file example are used for the record number. That is to begin with each customer must have a customer ID between 1 and 100. Of course there could be more than 100 customers. If a customer number greater than 100 is written to the file, then the code determines that no such record exists. When this happens the
file:///D|/1/final/BBL0122.html (1 von 2) [01.12.2007 04:50:17]
Binary File Random Access
method CreateMoreRecords() is called. For example if the customer ID was 150, there would need to be at least 50 more records in order to store the customer information with ID 150. The method CreateMoreRecords() would be called to create 100 more records using the same loop as above. The program then determines whether there are yet enough records. For example if the customer number had been 250 instead of 150, there would need to be 300 records and not 200 new ones. As a result, the method CreateMoreRecords() would have to be called twice instead of just once. This action is accomplished by the following loop: while(fileLength < (long)(theCustomer.customerID-1) * NewCustomer.theSize) { CreateMoreRecords(); if(fileOutput != null) fileOutput.Close(); fileOutput = new FileStream(randomAccessFile, FileMode Open,FileAccess.Write); fileLength = fileOutput.Length; binaryOutput = new BinaryWriter(fileOutput); }
When looking at the code above, notice the use of the variable fileLength that is assigned the value fileOutput. Length, i.e. the length of the file in bytes. This value should be equivalent to the number of records times theSize. Create a Console project: RandomAccess.cs. Copy the files: WritingRandomAccess.cs and NewCustomer.cs to the project. Compile and run the program with at least 5 records using the data below:
Open table as spreadsheet ID
First Name
Last Name
Owes
1
George
Washington
$2,393.30
2
Thomas
Jefferson
$4,233.30
3
John
Adams
$5,433.44
4
John Quincy
Adams
$4.40
5
Theodore
Roosevelt
$4,456.50
Try entering the values for the customer ID so that they are not sequential. Once the program runs open the data file: randomAccess.dat and look at the records both with the empty records and with data in them. Having stored the records to the data file: randomAccess.dat, a program needs to be created that reads the data. This program should request the customer ID. If the record exists, it should be found and then displayed on the screen. If the record does not exist, an error message needs to be shown on the screen. The program: ReadingRandomAccess.cs achieves this goal. Copy the file:ReadingRandomAccess.cs to the same project: RandomAccess.cs. Compile and run the program. Notice that the 5 records that were entered with the program: WritingRandomAccess.cs appear when their customer ID is given. In addition to using these know customer IDs, try using some customer IDs that were not added to the data file. Notice how the program responds to the fact that these records are not in the data file.
file:///D|/1/final/BBL0122.html (2 von 2) [01.12.2007 04:50:17]
Text File I/O in a Windows Program
Text File I/O in a Windows Program Windows Forms and Text File Output Specifications: Suppose that you were requested to write a receivables program that would receive data entered from the keyboard and store it to a text file using the C# GUI interface. Suppose further that the data to be entered is: month, company name and amount due. The GUI should include a button labeled: Post that would append the data to the file: ??accountsReceivable.txt where the ?? is the month being processed. The form should look like the following:
Where the top three blanks are the text boxes and the bottom one is a button. The following is some sample data (however the dollar signs and the commas should not be entered into the program since this would be character data rather than numeric data.)
Open table as spreadsheet Company Name
Amount Due
The Big One
$10,000.00
Another One
$1,422.33
Again One
$23,320.21
Still More
$235.34
Coding: To begin, create a Windows form using the project name: postReceivables. Click on the form and using the Properties change the Text of the form to Post Receivables. Change the Size, Maximum Size and Minimum Size to 350,300 From the Toolbox drag two labels, two textboxes and a button to the form. ●
properties of the labels ❍
label1 properties: Font: Bold, Text: Company Name Location: 25, 90, Size: 120, 17
❍
label2 properties: Font: Bold, Text: Amount Due, Location: 25, 140, Size: 100, 17
❍
label3 properties: Font: Bold, Text: Month, Location: 25,40, Size: 52,17
file:///D|/1/final/BBL0123.html (1 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program ●
properties of the textboxes ❍
❍
❍
●
textbox1 properties: font: Bold, name: txtCompanyName, Location: 165, 40, size: 150, 22, TabIndex: 2 textbox2 properties: font: Bold , name: txtAmountDue, Location: 165, 100, size: 150, 22 , TextAlign: Right, TabIndex: 3 textbox3 properties: Font: Bold, Name: txtMonth, Location: 165,40,Size: 40,22, TextAlign: Right, TabIndex: 1.
properties of button ❍
button1 properties: font: Bold, text: Post , name: btnPost, location: 60, 200, size: 75, 25, TabIndex: 4
To complete the coding, click on the form and select: View Code. Place the following at the top of Form1.cs with the other using statements: using System.IO;
In the class: Form1 define the following data members: static string fileName = "accountsReceivable"; static string theFileName = ""; static FileStream writeFileStream; static StreamWriter fileWriter; DateTime theDay = DateTime.Now; static string theMonth;
By making the above as static data members, they will be accessible inside of any of the Form1 methods without the need to define an object of the class Form1 nor will it be necessary to dot it with the name of the class when they are used. In the Form1() constructor do the following: public Form1() { InitializeComponent(); txtMonth.Text = (theDay.Month).ToString(); txtCompanyName.Text = ""; txtAmountDue.Text = "0.00"; txtMonth.Focus(); }
Next double click the Post button and change its event handler to the following: private void btnPost_Click(object sender, EventArgs e) { if ((Int16.Parse(txtMonth.Text) >= 1)&& (Int16.Parse(txtMonth.Text) <= 12)) { if ((txtCompanyName.Text != "") && (Double.Parse(txtAmountDue.Text) > 0.00))
file:///D|/1/final/BBL0123.html (2 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program
{ theFileName = txtMonth.Text + fileName+".txt"; writeFileStream = new FileStream(theFileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); fileWriter.WriteLine(txtCompanyName.Text); fileWriter.WriteLine(txtAmountDue.Text); fileWriter.WriteLine(txtAmountDue.Text); fileWriter.Flush(); fileWriter.Close(); txtCompanyName.Text = ""; txtAmountDue.Text = "0.00"; txtCompanyName.Focus(); } else { MessageBox.Show("Enter a company name and an" + "amount", "Error"); } } else { MessageBox.Show("Month must be between 1 and 12", "Error: Incorrect Month"); txtMonth.Text = (theDay.Month).ToString(); txtCompanyName.Text = ""; txtAmountDue.Text = "0.00"; txtMonth.Focus(); } }
As indicated previously when text file I/O was discussed, the first two statements would write out the data from the textboxes to the text file: accountsReceivable.txt. The third statement would flush out the output buffer to send the data to the file. The fourth and fifth statement would clear the data in the textboxes and the sixth statement would return the cursor to the text box: companyName. Note: When comparing the pseudo code above with the actual code, you will notice that a lot of additional code was added to make the program more robust. Additional validation should be taken so that the data entered into the amount is numeric data.
Program to Output Data for Excel If the fields had commas between them and the output data file had an extension of .csv, then the file could be imported into Excel. To see how this could be done, modify the Form1.cs above to contain the following: private void btnPost_Click(object sender, EventArgs e) { if ((Int16.Parse(txtMonth.Text) >= 1) && (Int16.Parse(txtMonth.Text) <= 12)) { if ((txtCompanyName.Text != "") && (Double.Parse(txtAmountDue.Text) > 0.00)) { theFileName = txtMonth.Text + fileName+".txt"; writeFileStream = new FileStream(theFileName, FileMode.Append,FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); fileWriter.WriteLine(txtCompanyName.Text); file:///D|/1/final/BBL0123.html (3 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program
fileWriter.WriteLine(txtAmountDue.Text); fileWriter.WriteLine(txtAmountDue.Text); fileWriter.Flush(); fileWriter.Close(); theFileName = txtMonth.Text + "Excel" + fileName + ".csv"; writeFileStream = new FileStream(theFileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); fileWriter.Write(txtCompanyName.Text); fileWriter.Write(","); fileWriter.Write(txtAmountDue.Text); fileWriter.Write(","); fileWriter.WriteLine(txtAmountDue.Text); fileWriter.Flush(); fileWriter.Close(); txtCompanyName.Text = ""; txtAmountDue.Text = "0.00"; txtCompanyName.Focus(); } else { MessageBox.Show("Enter a company name and an amount", "Error"); } } else { MessageBox.Show("Month must be between 1 and 12", "Error: Incorrect Month") txtMonth.Text = (theDay.Month).ToString(); txtCompanyName.Text = ""; txtAmountDue.Text = "0.00"; txtMonth.Focus(); } }
Notice in the above code that two different files are opened and the data is written to each of them. Run at least ten companies through the program modification above. Then download ARTotals.xls and open it into Excel. When the file is opened, it should appear similar to the following:
file:///D|/1/final/BBL0123.html (4 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program
Notice that in the file ARTotals.xls, there is text: Total AR in A20 and in B20 is the Sum of B1-B19 while in C20 there is the Sum of C1-C19. Further the cells B1-B20 and C1-C19 are formatted into US currency. (Note: If there are a lot more entries, then these sums may need to include more rows.) Click on the cell: A2. Next click on the Data option on the menu bar. Follow this by clicking on: Import External Data and then on Import Data. Making these selections, Excel should appear as in the following graphic:
Using these selections, open the file: accountsPayable.csv. The following dialog should then appear:
Click on the Next button and the following dialog should appear:
file:///D|/1/final/BBL0123.html (5 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program
In the Delimiters uncheck Tab and check Comma. Next click the Finish button at the bottom. A dialog like the following should appear (Notice that the data will be placed beginning at A2):
Now click the OK button and in the spreadsheet should appear data like the following (Note: it may be necessary to adjust the width of the columns):
file:///D|/1/final/BBL0123.html (6 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program
Notice how the data appears formatted as would be needed. Note: It is also possible to create an Excel spreadsheet populated with data and to import the data into a C# program. This topic will not be discussed in these lectures.
Windows Forms and Text File Input Specifications: Suppose that you were requested to create a Windows GUI program that can read the data created by the program above one record at a time and display the Company Name and the Balance Due data read into textboxes after the month of the transactions were specified. In addition the program should total the account receivable balance due as it is read. The total accounts receivable balance due should then be posted to the Total AR Due text box. The form should look like the following where there are four text boxes and two buttons:
Coding: To begin, create a Window's project using the project name: viewReceivables Click on the form and using the Properties change the Text of the form to View Accounts Receivable and the Text to Bold. Set the Maximum Size and Minimum Size to the same values as the Size: 460, 380. From the Toolbox drag four labels, four textboxes and two buttons to the form as indicated in the specifications above. Change their properties to the following:
file:///D|/1/final/BBL0123.html (7 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program ●
●
properties of the labels ❍
label 1 properties:Font:Bold,Text:Month,Location:50,30,Size:52,17
❍
label 2 properties:Font:Bold,Text:Company Name,Location:40, 110,Size:120, 17
❍
label 3 properties:Font:Bold, Text:Balance Due,Location:40, 170 , Size:100, 17
❍
label 4 properties Font:Bold, Text:Total AR Due,Location: 40, 230, Size: 105, 17
properties of the textboxs ❍
❍
❍
❍
●
textbox 1 properties: Font: Bold , Name: txtMonth, Location: 140,30 ,Size: 50,22 TabIndex: 1 textbox 2 properties: Font: Bold, Name: txtCompanyName, location: 170, 110, Size: 140, 22, ReadOnly: True, Tab Stop: False textbox 3 properties: font: Bold, name: txtBalanceDue, location: 170, 170, size: 100, 22, ReadOnly: True, Tab Stop: False, Text Align: Right textbox 4 properties: font: Bold, name: txtTotalARDue, location: 170, 230, size: 100, 22, ReadOnly: True, Tab Stop: False, Text Align: Right
properties of button ❍
❍
button1 properties: Font: Bold, Text: Select Month, Name: btnSelect, Location: ,Size: TabIndex 2 button 2 properties: font: Bold, text: Next, name: viewPayables, location: 12, 171, size: 75, 23, TabIndex: 3
Add the following to the top of Form1.cs: using System.IO;
Add the following definitions to the class: Form1: static string theFile; static string fileName = "accountsReceivable.txt"; static FileStream readFileStream; static StreamReader fileReader; static double totalARDue; static string theMonth ="";
Modify the Form1 constructor to the following: public Form1() { InitializeComponent(); txtCompanyName.Text = ""; txtBalanceDue.Text = String.Format("{0:c}", 0.00); txtTotalARDue.Text = String.Format("{0:c}", 0.00); btnNext.Enabled = false; totalARDue = 0.00; } file:///D|/1/final/BBL0123.html (8 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program
The purpose of the second, third and fourth statements above is to initialize the three textboxes. The last line sets the variable: totalARDue to 0.00 for the purpose of adding the values as they are read in. Next double click on the Select Month button. Add the following code to the event handler: private void btnMonth_Click(object sender, EventArgs e) { if ((Int16.Parse(txtMonth.Text) >= 1) && (Int16.Parse(txtMonth.Text) <= 12)) { theMonth = txtMonth.Text; theFile = theMonth + fileName; try { readFileStream = new FileStream(theFile, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream); txtMonth.Enabled = false; txtMonth.TabStop = false; btnMonth.Enabled = false; btnMonth.TabStop = false; btnNext.TabStop = true; btnNext.Enabled = true; btnNext.Focus(); } // Catches the exception if the month's file is not // on record catch(FileNotFoundException) { MessageBox.Show("That month's data is not" + " on record.", "Error reading data"); txtMonth.Text = ""; txtMonth.Focus(); } } else { MessageBox.Show("The month must be between 1 and 12", "Error in month"); txtMonth.Text = ""; txtMonth.Focus(); } }
Next double click on the button: Next and change its event handler to the following: private void btnNext_Click(object sender, EventArgs e) { if (fileReader.EndOfStream == false) { txtCompanyName.Text = fileReader.ReadLine(); double theBalance = double.Parse(fileReader.ReadLine()); string theBlank = fileReader.ReadLine(); totalARDue += theBalance; txtBalanceDue.Text = String.Format("{0:c}", theBalance); txtTotalARDue.Text = String.Format("{0:c}", totalARDue); } else {
file:///D|/1/final/BBL0123.html (9 von 10) [01.12.2007 04:50:19]
Text File I/O in a Windows Program
MessageBox.Show("There is no more data to read.", "Notice"); btnNext.Enabled = false; btnNext.TabStop = false; txtMonth.Text = ""; txtMonth.TabStop = true; txtMonth.Enabled = true; txtMonth.Focus(); txtMonth.TabIndex = 1; btnMonth.TabStop = true; btnMonth.TabIndex = 2; btnMonth.Enabled = true; txtCompanyName.Text = ""; txtBalanceDue.Text = String.Format("{0:c}", 0.00); txtTotalARDue.Text = String.Format("{0:c}", 0.00); totalARDue = 0.00; } }
Notice the use of the StreamReader data member: EndOfStream to control access to fileReader.ReadLine(). The Console program viewed above used a while() loop and theData != Null to stop data entry. However that approach would not work here. Notice that a selection is set up to determine if all of the data in the file has been read. Inside of the then part of the selection are six statements to implement the reading of the data, the adding up of the amounts due and the displaying the dollar amounts of the amount due the current record and the total amount due. The else part of the selection contains a call to a MessageBox to inform the user when all of the data has been read and then to reset the form so that the user may begin processing a different month if desired. To complete the implementation and to test the program the data file: ??accountsReceivable.txt (where the ?? stands for the month) that was created in the program: postReceivables.cs needs to be copied to the bin\Debug folder of the current project. Comment: Another program which could be created to complement these two programs would be one that would post payments to the current balance of each customer. Comment: Above it was discussed how to output to a file that could then be used by Excel. It is also possible to create a file in Excel, save it as comma separated data: i.e. a .csv file and then using a C# Windows program input the data into a program like the one above. To do this would require the separation of the data into two strings: one for the company name and one for the amount owed. This would require the use of a string method to find the comma and then to separate the data into the company name up to the comma and the amount owed after the comma. This topic is left as an exercise for you.
file:///D|/1/final/BBL0123.html (10 von 10) [01.12.2007 04:50:19]
Lecture 14 Examples
Lecture 14 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
Accounts Receivable Posting
This is a windows program that permits the posting of accounts receivable to both a text file and a .csv file. The later of which can then be input using the Excel spreadsheet below.
●
Form1.cs
●
Form1.Designer.cs
●
Program1.cs
ARTotals.xls
This is an Excel spreadsheet that is used to input the date from the file: accountsPayable.csv which was output from the Windows program listed above.
Accounts Receivable Reading
This is a windows program that reads data from a text file create by the Accounts Receivable Posting program listed above. It requests the month to be read and then reads the data one record at a time.
●
Form1.cs
●
Form1.Designer.cs
●
Program1.cs
BufferedStream1.cs
This program sends data to a BufferedStream. Next it displays the data stored in memory. Then it creates a file using theFile. The data in the BufferedStream is then sent to the FileStream data file.
customer.cs
This file contains the definition of the class Customer.
DirectoryInfo1.cs
This program creates new subdirectories.
DirectoryInfo2.cs
This program creates a new DirectoryInfo object and then displays information about the directory to which the object is initialized.
DirectoryInfo3.cs
This program creates new subdirectories in the folder of the program. After compiling this program, create a directory called: TheAccounting. Next place the executable for this program in that folder.
DirectoryManagement.cs
This program demonstrates how to access the directory information for a locations specified from keyboard input.
FileInfo1.cs
This program creates a new file: CompanyInformation.txt in a folder created in DirectoryInfo1.cs and then displays the information about the directory. At the end, the program requests that any key be pressed. Once the key is pressed the file is deleted.
FileManagement.cs
This program enables access to a location and seeks to determine the number of files and folders at this location.
FileMode1.cs
This program creates a new file: Text.ini and then display information about the directory. The program requests that any key be pressed. Once it does the file is deleted.
FileStream1.cs
This program creates a file using FileStream and sends bytes to the file after which it resets the Position and the bytes are then read back into the program.
MemoryStream1.cs
This program sends data to a MemoryStream. Next it displays the data stored in memory. Then it creates a file using FileStream. The data in the MemoryStream is then sent to the FileStream data file.
NewCustomers.cs
This file contains the definition of the class NewCustomer which is use for random file access both input and output.
ReadFromBinaryFiles.cs
This program reads from a binary file.
ReadFromTextFiles2.cs
This program is similar to ReadFromTextFiles.cs except it uses StreamReader instead FileStream.
ReadFromTextFiles.cs
This program demonstrates how to read data from a text file.
readingBinaryFiles.cs
This program demonstrates the reading of serialized objects of the class customer from a binary file.
ReadingRandomAccess.cs
This file demonstrates the reading of random access files. It uses objects from the class NewCustomer from the file: NewCustomer.cs
WriteToBinaryFile
This program writes to binary files.
WriteToTextFile2.cs
This program is similar to WriteToTextFile.cs except it uses an object of FileInfo rather than an object of FileStream.
WriteToTextFiles.cs
This program demonstrates text file output.
writingBinaryFiles.cs
This program writes serialized objects of the class customer to a binary file.
WritingRandomAccess.cs
This program demonstrates writing random files using the class NewCustomers that is defined in the file: NewCustomers.cs.
// program_id
Form1.cs
file:///D|/1/final/BBL0124.html (1 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// written_by Don Voils // date_written 11/4/2006 // description This windows program simulates an accounts receivable // program that posts the data to both a text file and // a .csv file the latter of which can then be read from // Microsoft Excel. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace postReceivables { public partial class Form1 : Form { static string fileName = "accountsReceivable"; static string theFileName = ""; static FileStream writeFileStream; static StreamWriter fileWriter; DateTime theDay = DateTime.Now; static string theMonth; public Form1() { InitializeComponent(); txtMonth.Text = (theDay.Month).ToString(); txtCompanyName.Text = ""; txtAmountDue.Text = "0.00"; txtMonth.Focus(); } private void btnPost_Click(object sender, EventArgs e) { if ((Int16.Parse(txtMonth.Text) >= 1)&& (Int16.Parse(txtMonth.Text) <= 12)) { if ((txtCompanyName.Text != "") && (Double.Parse(txtAmountDue.Text) > 0.00)) { theFileName = txtMonth.Text + fileName + ".txt"; writeFileStream = new FileStream(theFileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); fileWriter.WriteLine(txtCompanyName.Text); fileWriter.WriteLine(txtAmountDue.Text); fileWriter.WriteLine(txtAmountDue.Text); fileWriter.Flush(); fileWriter.Close(); theFileName = txtMonth.Text + "Excel" + fileName + ".csv"; writeFileStream = new FileStream(theFileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); fileWriter.Write(txtCompanyName.Text); fileWriter.Write(","); fileWriter.Write(txtAmountDue.Text); fileWriter.Write(","); fileWriter.WriteLine(txtAmountDue.Text); fileWriter.Flush(); fileWriter.Close(); txtCompanyName.Text = ""; txtAmountDue.Text = "0.00"; txtCompanyName.Focus(); } else { MessageBox.Show("Enter a company name and an " + "amount", "Error"); }
file:///D|/1/final/BBL0124.html (2 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
} else { MessageBox.Show("Month must be between 1 and 12", "Error: Incorrect Month"); txtMonth.Text = (theDay.Month).ToString(); txtCompanyName.Text = ""; txtAmountDue.Text = "0.00"; txtMonth.Focus(); } } } }
// program_id Form1.Designer.cs // written_by Don Voils // date_written 11/4/2006 // description This windows program simulates an accounts receivable // program that posts the data to both a text file and // a .csv file the latter of which can then be read from // Microsoft Excel. // namespace postReceivables { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.btnPost = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtCompanyName = new System.Windows.Forms.TextBox(); this.txtAmountDue = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.txtMonth = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // btnPost // this.btnPost.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnPost.Location = new System.Drawing.Point(60, 200); this.btnPost.Name = "btnPost"; this.btnPost.Size = new System.Drawing.Size(75, 25); this.btnPost.TabIndex = 4; this.btnPost.Text = "Post"; this.btnPost.UseVisualStyleBackColor = true; this.btnPost.Click += new System.EventHandler(this.btnPost_Click); //
file:///D|/1/final/BBL0124.html (3 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(25, 90); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(120, 17); this.label1.TabIndex = 1; this.label1.Text = "Company Name"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(25, 140); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 17); this.label2.TabIndex = 2; this.label2.Text = "Amount Due"; // // txtCompanyName // this.txtCompanyName.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing. GraphicsUnit.Point, ((byte)(0))); this.txtCompanyName.Location = new System.Drawing.Point(165, 90); this.txtCompanyName.Name = "txtCompanyName"; this.txtCompanyName.Size = new System.Drawing.Size(150, 22); this.txtCompanyName.TabIndex = 2; // // txtAmountDue // this.txtAmountDue.Location = new System.Drawing.Point(165, 140); this.txtAmountDue.Name = "txtAmountDue"; this.txtAmountDue.Size = new System.Drawing.Size(150, 22); this.txtAmountDue.TabIndex = 3; this.txtAmountDue.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(25, 40); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(52, 17); this.label3.TabIndex = 4; this.label3.Text = "Month"; // // txtMonth // this.txtMonth.Location = new System.Drawing.Point(165, 40); this.txtMonth.Name = "txtMonth"; this.txtMonth.Size = new System.Drawing.Size(40, 22); this.txtMonth.TabIndex = 1; this.txtMonth.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(342, 267); this.Controls.Add(this.txtMonth); this.Controls.Add(this.label3); this.Controls.Add(this.txtAmountDue); this.Controls.Add(this.txtCompanyName); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.btnPost); this.MaximumSize = new System.Drawing.Size(350, 300); this.MinimumSize = new System.Drawing.Size(350, 300); this.Name = "Form1"; this.Text = "Post Receivables"; this.ResumeLayout(false); this.PerformLayout();
file:///D|/1/final/BBL0124.html (4 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
} #endregion private System.Windows.Forms.Button btnPost; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtCompanyName; private System.Windows.Forms.TextBox txtAmountDue; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtMonth; } }
// program_id Program.cs // written_by Don Voils // date_written 11/4/2006 // description This windows program simulates an accounts receivable // program that posts the data to both a text file and // a .csv file the latter of which can then be read from // Microsoft Excel. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace postReceivables { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id Form1.cs // written_by Don Voils // date_wrtten 11/2/2006 // description This program reads the data written to a text // file by the program:Accounts Receivable Posting. // It permits the selection of the month and then // reads one record at a time. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace viewReceivables { public partial class Form1 : Form { static string theFile; static string fileName = "accountsReceivable.txt"; static FileStream readFileStream; static StreamReader fileReader; static double totalARDue; static string theMonth ="";
file:///D|/1/final/BBL0124.html (5 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
public Form1() { InitializeComponent(); txtCompanyName.Text = ""; txtBalanceDue.Text = String.Format("{0:c}", 0.00); txtTotalARDue.Text = String.Format("{0:c}", 0.00); btnNext.Enabled = false; totalARDue = 0.00; } private void btnMonth_Click(object sender, EventArgs e) { if ((Int16.Parse(txtMonth.Text) >= 1) && (Int16.Parse(txtMonth.Text) <= 12)) { theMonth = txtMonth.Text; theFile = theMonth + fileName; try { readFileStream = new FileStream(theFile, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream); txtMonth.Enabled = false; txtMonth.TabStop = false; btnMonth.Enabled = false; btnMonth.TabStop = false; btnNext.TabStop = true; btnNext.Enabled = true; btnNext.Focus(); } // Catches the exception if the month's file is not on record // catch(FileNotFoundException) { MessageBox.Show("That month's data is not on record.","Error reading data"); txtMonth.Text = ""; txtMonth.Focus(); } } else { MessageBox.Show("The month must be between 1 and 12", "Error in month"); txtMonth.Text = ""; txtMonth.Focus(); } } private void btnNext_Click(object sender, EventArgs e) { if (fileReader.EndOfStream == false) { txtCompanyName.Text = fileReader.ReadLine(); double theBalance = double.Parse(fileReader.ReadLine()); string theBlank = fileReader.ReadLine(); totalARDue += theBalance; txtBalanceDue.Text = String.Format("{0:c}", theBalance); txtTotalARDue.Text = String.Format("{0:c}", totalARDue); } else { MessageBox.Show("There is no more data to read.", "Notice"); btnNext.Enabled = false; btnNext.TabStop = false; txtMonth.Text = ""; txtMonth.TabStop = true; txtMonth.Enabled = true; txtMonth.Focus(); txtMonth.TabIndex = 1;
file:///D|/1/final/BBL0124.html (6 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
btnMonth.TabStop = true; btnMonth.TabIndex = 2; btnMonth.Enabled = true;
txtCompanyName.Text = ""; txtBalanceDue.Text = String.Format("{0:c}", 0.00); txtTotalARDue.Text = String.Format("{0:c}", 0.00); totalARDue = 0.00; } } } }
// program_id Form1.Designer.cs // written_by Don Voils // date_wrtten 11/2/2006 // description This program reads the data written to a text // file by the program:Accounts Receivable Posting. // It permits the selection of the month and then // reads one record at a time. // namespace viewReceivables { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.txtMonth = new System.Windows.Forms.TextBox(); this.btnMonth = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtCompanyName = new System.Windows.Forms.TextBox(); this.txtBalanceDue = new System.Windows.Forms.TextBox(); this.txtTotalARDue = new System.Windows.Forms.TextBox(); this.btnNext = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(50, 30); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(52, 17); this.label1.TabIndex = 0; this.label1.Text = "Month";
file:///D|/1/final/BBL0124.html (7 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// // txtMonth // this.txtMonth.Location = new System.Drawing.Point(140, 30); this.txtMonth.Name = "txtMonth"; this.txtMonth.Size = new System.Drawing.Size(50, 22); this.txtMonth.TabIndex = 1; this.txtMonth.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // btnMonth // this.btnMonth.Location = new System.Drawing.Point(307, 29); this.btnMonth.Name = "btnMonth"; this.btnMonth.Size = new System.Drawing.Size(128, 32); this.btnMonth.TabIndex = 2; this.btnMonth.Text = "Select Month"; this.btnMonth.UseVisualStyleBackColor = true; this.btnMonth.Click += new System.EventHandler(this.btnMonth_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(40, 110); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(120, 17); this.label2.TabIndex = 3; this.label2.Text = "Company Name"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(40, 170); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(100, 17); this.label3.TabIndex = 4; this.label3.Text = "Balance Due"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(40, 230); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(105, 17); this.label4.TabIndex = 5; this.label4.Text = "Total AR Due"; // // txtCompanyName // this.txtCompanyName.Location = new System.Drawing.Point(170, 110); this.txtCompanyName.Name = "txtCompanyName"; this.txtCompanyName.ReadOnly = true; this.txtCompanyName.Size = new System.Drawing.Size(140, 22); this.txtCompanyName.TabIndex = 3; this.txtCompanyName.TabStop = false; // // txtBalanceDue // this.txtBalanceDue.Location = new System.Drawing.Point(170, 170); this.txtBalanceDue.Name = "txtBalanceDue"; this.txtBalanceDue.ReadOnly = true; this.txtBalanceDue.Size = new System.Drawing.Size(100, 22); this.txtBalanceDue.TabIndex = 4; this.txtBalanceDue.TabStop = false; this.txtBalanceDue.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtTotalARDue // this.txtTotalARDue.Location = new System.Drawing.Point(170, 230); this.txtTotalARDue.Name = "txtTotalARDue"; this.txtTotalARDue.ReadOnly = true; this.txtTotalARDue.Size = new System.Drawing.Size(100, 22); this.txtTotalARDue.TabIndex = 8; this.txtTotalARDue.TabStop = false; this.txtTotalARDue.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; //
file:///D|/1/final/BBL0124.html (8 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// btnNext // this.btnNext.Location = new System.Drawing.Point(54, 288); this.btnNext.Name = "btnNext"; this.btnNext.Size = new System.Drawing.Size(75, 28); this.btnNext.TabIndex = 5; this.btnNext.Text = "Next"; this.btnNext.UseVisualStyleBackColor = true; this.btnNext.Click += new System.EventHandler(this.btnNext_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(452, 347); this.Controls.Add(this.btnNext); this.Controls.Add(this.txtTotalARDue); this.Controls.Add(this.txtBalanceDue); this.Controls.Add(this.txtCompanyName); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.btnMonth); this.Controls.Add(this.txtMonth); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.MaximumSize = new System.Drawing.Size(460, 380); this.MinimumSize = new System.Drawing.Size(460, 380); this.Name = "Form1"; this.Text = "View Accounts Receivable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtMonth; private System.Windows.Forms.Button btnMonth; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtCompanyName; private System.Windows.Forms.TextBox txtBalanceDue; private System.Windows.Forms.TextBox txtTotalARDue; private System.Windows.Forms.Button btnNext; } }
// program_id Program.cs // written_by Don Voils // date_wrtten 11/2/2006 // description This program reads the data written to a text // file by the program:Accounts Receivable Posting. // It permits the selection of the month and then // reads one record at a time. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace viewReceivables { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
file:///D|/1/final/BBL0124.html (9 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Application.Run(new Form1()); } } }
// program_id BufferedStream1.cs // written_by don voils // date_written 3/24/2006 // description This program sends data to a BufferedStream. Next // it displays the data stored in memory. Then // it creates a file using theFile. The data in // the BufferedStream is then sent to the FileStream // data file. // using System; using System.IO; namespace MemoryStreamApp { public class theProgram { public static int Main(string[] args) { Console.WriteLine("\nWorking the BufferedStream!\n\n"); FileStream theFile = new FileStream("theData.txt", FileMode.Create, FileAccess.ReadWrite); BufferedStream myFileBuffer = new BufferedStream(theFile); byte[] theBuffer = {0x55, 0x71, 0x4, 0x0, 0x0, 0x16,0xAB,0x44,0x35}; myFileBuffer.Write(theBuffer, 0, theBuffer.Length); myFileBuffer.Close(); return 0; } } }
// program_id customer.cs // written_by don voils // date_written 10/30/2006 // description This file contains the definition of the // class Customer. // using System; namespace Customers { [Serializable] public class Customer { private string ID; private string first; private string last; private decimal Due; public string customerID { get { return ID; } set { ID = value; } }
file:///D|/1/final/BBL0124.html (10 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
public string firstName { get { return first; } set { first = value; } } public string lastName { get { return last; } set { last = value; } }
public decimal balanceDue { get { return Due; } set { Due = value; } } public Customer() { customerID = ""; firstName = ""; lastName = ""; balanceDue = 0.00m; } } }
// program_id DirectoryInfo1.cs // writen_by don voils // date_written 3/19/2006 // description This program creates new subdirectories. // using System; using System.IO; namespace DirectoryInfo1 { class theProgram { static void Main(string[] args) { DirectoryInfo theDirectory = new DirectoryInfo(@"‥/‥/‥/"); Console.Write("What is the company name? "); string theName = Console.ReadLine(); try {
file:///D|/1/final/BBL0124.html (11 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
theDirectory.CreateSubdirectory(theName); string theSales = theName + @"\Sales"; string theExpenses = theName + @"\Expenses"; theDirectory.CreateSubdirectory(theSales); theDirectory.CreateSubdirectory(theExpenses); } catch(IOException e) { Console.WriteLine(e.Message); } Console.WriteLine("\n"); } } }
// program_id DirectoryInfo2.cs // writen_by don voils // date_written 3/19/2006 // description This program creates a new DirectoryInfo object // and then displays information about the // directory to which the object is initialized. // using System; using System.IO; namespace DirectoryInfo1 { class theProgram { static void Main(string[] args) { DirectoryInfo theDirectory = new DirectoryInfo(@"‥\‥\bin"); Console.WriteLine("****Directory Information****"); Console.WriteLine("FullName: {0}",theDirectory.FullName); Console.WriteLine("Name: {0}",theDirectory.Name); Console.WriteLine("Parent: {0}",theDirectory.Parent); Console.WriteLine("Creation: {0}",theDirectory.CreationTime); Console.WriteLine("Attributes: {0}",theDirectory.Attributes.ToString()); Console.WriteLine("Root: {0}",theDirectory.Root); Console.WriteLine("**********************"); } } }
// program_id DirectoryInfo3.cs // writen_by don voils // date_written 3/19/2006 // description This program creates new subdirectories in // the folder of the program. After compiling this // program, create a directory called: TheAccounting. // Next place the executable for this program in that // folder. // using System; using System.IO; namespace DirectoryInfo1 {
class theProgram {
static void Main(string[] args) { DirectoryInfo theDirectory = new DirectoryInfo(@"‥\TheAccounting"); Console.Write("What is the company name? ");
file:///D|/1/final/BBL0124.html (12 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
string theName = Console.ReadLine(); try { theDirectory.CreateSubdirectory(theName); string theSales = theName + @"\Sales"; string theExpenses = theName + @"\Expenses"; theDirectory.CreateSubdirectory(theSales); theDirectory.CreateSubdirectory(theExpenses); } catch(IOException e) { Console.WriteLine(e.Message); } Console.WriteLine("\n"); } } }
// program_id DirectoryManagement.cs // written_by don voils // date_written 12/06/2005 // description This program demonstrates how to access the // directory information for a locations specified // from keyboard input. // using System; using System.IO; namespace DirectoryManagement { class DirectoryManagement { // if you have permission try the following directory: @"c:\Program Files"; // try other directories to observe how the code works. // if your a: disk does not have sub directories, make some to see how this // program works. // static string theDirectory; static int dirCounter = 1; static int indentLevel = -1; static void Main(string[] args) { char more = 'Y'; do { Console.Clear(); Console.Write("What is the drive and directory you want to search? "); theDirectory = Console.ReadLine(); DirectoryInfo theInfo = new DirectoryInfo(theDirectory); ExploreDirectories(theInfo); Console.WriteLine("\n\n{0} directories were found in {1}\n",dirCounter,theDirectory); Console.Write("\n\nAnother locations? (Y/N) "); more = Char.Parse(Console.ReadLine()); Console.Clear(); }while((more=='Y') || (more=='y')); } // The following is a recursive method that moves up and down the directory tree // static void ExploreDirectories(DirectoryInfo info) { indentLevel++; for(int index = 0; index < indentLevel; ++index) Console.Write(" ");
file:///D|/1/final/BBL0124.html (13 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Console.WriteLine("Level:[{0}] Name:[{1}] Date of last access:[{2}]",indentLevel, info.Name, info.LastAccessTime); DirectoryInfo[] directories = info.GetDirectories(); foreach(DirectoryInfo newDir in directories) { dirCounter++; ExploreDirectories(newDir); } indentLevel--; } } }
// program_id FileInfo1.cs // writen_by don voils // date_written 3/19/2006 // description This program creates a new file: CompanyInformation.txt // in a folder created in DirectoryInfo1.cs and then displays // the information about the directory. At the end, the program // requests that any key be pressed. Once the key is pressed the file // is deleted. // using System; using System.IO; namespace FileInfo1 {
class theProgram {
static void Main(string[] args) { Console.WriteLine("In the following use the same name"); Console.WriteLine("as used with DirectoryInfo1.cs example.\n"); Console.Write("What is the name of the company? "); string theName = Console.ReadLine(); FileInfo theInfo = new FileInfo(@"‥\‥\‥\"+theName +@"\CompanyInformation.txt"); FileStream theStream = theInfo.Create(); Console.WriteLine("\n\n****File Information****"); Console.WriteLine("FullName: {0}",theInfo.FullName); Console.WriteLine("Creation: {0}",theInfo.CreationTime); Console.WriteLine("Attributes: {0}",theInfo.Attributes.ToString()); Console.WriteLine("**********************"); Console.WriteLine("\n\nLook in the "+theName+ " folder to view this file."); Console.WriteLine("\nAfter you press any key, the file will be deleted.\n"); Console.WriteLine("Press a key to delete the file."); Console.Read(); theStream.Close(); theInfo.Delete(); } } }
// program_id FileManagement.cs // written_by don voils // date_written 12/06/2005 // description This program enables access to a location // and seeks to determine the number of files // and folders at this location. // using System; using System.IO;
file:///D|/1/final/BBL0124.html (14 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
namespace FileManagement {
class FileManagement { // if you have permission try the following directory: @"c:\Program Files"; // try other directories to observe how the code works. // if your a: disk does not have sub directories, make some to see how this // program works. // static string theDirectory; static int dirCounter = 1; static int indentLevel = -1; static int fileCounter = 0; static void Main(string[] args) { char more = 'Y'; do { Console.Clear(); Console.Write("What locations do you wish to explore? "); theDirectory = Console.ReadLine(); DirectoryInfo theInfo = new DirectoryInfo(theDirectory); ExploreDirectories(theInfo); Console.WriteLine("\n\n{0} files in {1} directories were found.\n",fileCounter,dirCounter); Console.Write("Do you want to search another location? Y/N) "); more = Char.Parse(Console.ReadLine()); }while((more=='Y')||(more=='y')); Console.Clear(); } // The following is a recursive method that moves up and down the directory tree // static void ExploreDirectories(DirectoryInfo info) { indentLevel++; for(int index = 0; index < indentLevel; ++index) Console.Write(" "); Console.WriteLine("Level:[{0}] Name:[{1}] Date of last access:[{2}]",indentLevel, info.Name, info.LastAccessTime); FileInfo[] filesinDirectory = info.GetFiles(); foreach(FileInfo newFile in filesinDirectory) { for(int index = 0; index < indentLevel+1;++index) Console.Write(" "); Console.WriteLine("File:[{0}] Last Written:[{1}] Size {2} bytes",newFile.Name,newFile.LastWriteTime,newFile.Length); ++fileCounter; } DirectoryInfo[] directories = info.GetDirectories(); foreach(DirectoryInfo newDir in directories) { dirCounter++; ExploreDirectories(newDir); } indentLevel--; } } }
file:///D|/1/final/BBL0124.html (15 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// program_id FileMode1.cs // writen_by don voils // date_written 3/19/2006 // description This program creates a new file: Text.ini // and then display information about the // directory. The program requests that any // key be pressed. Once it does the file // is deleted. // using System; using System.IO; namespace FileInfo1 {
class theProgram {
static void Main(string[] args) { Console.Write("What is your name? "); string theName = Console.ReadLine(); FileInfo theInfo = new FileInfo(@"‥\‥\"+theName+@"'s InformationFile.txt"); FileStream theStream = theInfo.Open(FileMode.OpenOrCreate,FileAccess.ReadWrite); Console.WriteLine("****File Information****"); Console.WriteLine("FullName: {0}",theInfo.FullName); Console.WriteLine("Creation: {0}",theInfo.CreationTime); Console.WriteLine("Attributes: {0}",theInfo.Attributes.ToString()); Console.WriteLine("**********************"); Console.WriteLine("\nLook in the bin directory of the program's folder to view this file."); Console.WriteLine("\nAfter you press any key, the file will be deleted.\n"); Console.WriteLine("Press a key to delete the file."); Console.Read(); theStream.Close(); theInfo.Delete(); } } }
// program_id FileStream1.cs // written_by don voils // date_written 3/24/2006 // description This program creates a file using FileStream // and sends bytes to the file after which // it resets the Position and the bytes are // then read back into the program. // using System; using System.IO; namespace FileStream1 { class theProgram { static void Main(string[] args) { FileStream theStream = new FileStream("myData.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); for(int index = 65; index < 125;++index) theStream.WriteByte((byte)index); theStream.Position = 0; for(int index = 65; index <125; ++index)
file:///D|/1/final/BBL0124.html (16 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Console.WriteLine(theStream.ReadByte()); theStream.Close(); } } }
// program_id MemoryStream1.cs // written_by don voils // date_written 3/24/2006 // description This program sends data to a MemoryStream. Next // it displays the data stored in memory. Then // it creates a file using FileStream. The data in // the MemoryStream is then sent to the FileStream // data file. // using System; using System.IO; namespace MemoryStreamApp { public class theProgram { public static int Main(string[] args) { Console.WriteLine("Working with the Memory Stream Application!"); MemoryStream myMemoryStream = new MemoryStream(); myMemoryStream.Capacity = 30; for(int i = 0; i < 30; i++) { myMemoryStream.WriteByte((byte)i); } myMemoryStream.Position = 0; for(int i = 0; i < 30; i++) { Console.WriteLine(myMemoryStream.ReadByte()); } Console.WriteLine(); FileStream theFile = new FileStream("theMemory.txt", FileMode.Create, FileAccess.ReadWrite); myMemoryStream.WriteTo(theFile); //byte[] bytesinMemory = myMemoryStream.ToArray(); myMemoryStream.Close(); return 0; } } }
// program_id NewCustomers.cs // written_by don voils // date_written 10/06/2006 // description This file contains the definition of the // class NewCustomer which is use for random // file access both input and output. // using System; namespace NewCustomers { public class NewCustomer { private const int CHAR_ARRAY_LENGTH = 15; private const int SIZE_OF_CHAR = 2; private const int SIZE_OF_INT32 = 4;
file:///D|/1/final/BBL0124.html (17 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
private const int SIZE_OF_DECIMAL = 8; private const int Size = 2 * (SIZE_OF_CHAR + CHAR_ARRAY_LENGTH) + SIZE_OF_INT32 + SIZE_OF_DECIMAL; private char[] first = new char[CHAR_ARRAY_LENGTH]; private char[] last = new char[CHAR_ARRAY_LENGTH]; private int ID; private decimal Due; static public int theSize { get { return Size; } } public int customerID { get { return ID; } set { ID = value; } } public string firstName { get { return new string(first); } set { int stringSize = value.Length; string firstNameString = value; if(CHAR_ARRAY_LENGTH >= stringSize) { firstNameString = value + new string(' ',CHAR_ARRAY_LENGTH - stringSize); } else { firstNameString = value.Substring(0,CHAR_ARRAY_LENGTH); } first = firstNameString.ToCharArray(); } } public string lastName { get { return new string(last); } set { int stringSize = value.Length; string lastNameString = value; if(CHAR_ARRAY_LENGTH >= stringSize) { lastNameString = value + new string(' ',CHAR_ARRAY_LENGTH - stringSize); } else { lastNameString = value.Substring(0,CHAR_ARRAY_LENGTH); } last = lastNameString.ToCharArray(); } }
file:///D|/1/final/BBL0124.html (18 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
public decimal balanceDue { get { return Due; } set { Due = value; } } public NewCustomer() { customerID = 0; firstName = ""; lastName = ""; balanceDue = 0.00m; } public NewCustomer(int ID,string FirstName,string LastName,decimal BalanceDue) { customerID = ID; firstName = FirstName; lastName = LastName; balanceDue = BalanceDue; } } }
// program_id ReadFromBinaryFiles // written_by don voils // date_written 11/04/2006 // using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers; namespace ReadFromBinaryFiles { class Program { static void Main(string[] args) { FileStream theInFile; decimal theTotalDue = 0.00m; try { Customer theCustomer = new Customer(); IFormatter serializer = new BinaryFormatter(); theInFile = new FileStream("Customers.dat", FileMode.Open, FileAccess.Read); // The following loop continues until there is no more data // then an exception occurs to end the try block. The catch() // with the SerializationException catches the end of file // error and the program terminates successfully. // while (true) { theCustomer = serializer.Deserialize(theInFile) as Customer; Console.WriteLine("Customer's ID: " + theCustomer.customerID); Console.WriteLine("Customer's Name: " + theCustomer.firstName + " " + theCustomer.lastName); Console.WriteLine(String.Format("\nBalance due is: {0:c}\n\n", theCustomer.balanceDue)); theTotalDue += theCustomer.balanceDue; } } catch (SerializationException) {
file:///D|/1/final/BBL0124.html (19 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Console.WriteLine("Total Account Receivable {0:c}", theTotalDue); Console.ReadKey(); } catch (IOException e) { Console.WriteLine("An IO exception has occurred."); Console.WriteLine(e.ToString()); } } } }
// program_id ReadFromTextFiles2.cs // written_by don voils // date_written 3/25/2006 // description This program is similar to ReadFromTextFiles.cs // except it uses StreamReader instead FileStream. using System; using System.IO; namespace ReadFromTextFiles2 { class InPutData { static string fileName = @"‥\‥\‥\‥\datafile2.txt"; static StreamReader fileReader; static void Main(string[] args) { OpentoReadDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; customerID = fileReader.ReadLine(); while(customerID != null) { Console.WriteLine("Customer's ID: "+customerID); customerFirstName = fileReader.ReadLine(); customerLastName = fileReader.ReadLine(); Console.WriteLine("\nCustomer's name: "+customerFirstName+ " "+customerLastName); customerBalanceDue = decimal.Parse(fileReader.ReadLine()); Console.WriteLine(String.Format("\nBalance due: {0:c}\n\n", customerBalanceDue)); customerID = fileReader.ReadLine(); } CloseDataFiles(); } static void OpentoReadDataFile() { fileReader = File.OpenText(fileName); } static void CloseDataFiles() { fileReader.Close(); } } }
// program_id ReadFromTextFiles.cs // written_by don voils // date_written 12/19/2005 // description This program demonstrates how to read data // from a text file. //
file:///D|/1/final/BBL0124.html (20 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
using System; using System.IO; namespace ReadFromTextFiles { class InPutData { static string fileName = @"‥\‥\‥\‥\datafile.txt"; static FileStream readFileStream; static StreamReader fileReader; static void Main(string[] args) { OpentoReadDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; customerID = fileReader.ReadLine(); while(customerID != null) { Console.WriteLine("Customer's ID: "+customerID); customerFirstName = fileReader.ReadLine(); customerLastName = fileReader.ReadLine(); Console.WriteLine("\nCustomer's name: "+customerFirstName+" "+customerLastName); customerBalanceDue = decimal.Parse(fileReader.ReadLine()); Console.WriteLine(String.Format("\nBalance due: {0:c}\n\n",customerBalanceDue)); customerID = fileReader.ReadLine(); } CloseDataFiles(); } static void OpentoReadDataFile() { if(readFileStream!=null) readFileStream.Close(); if(fileReader!=null) fileReader.Close(); readFileStream = new FileStream(fileName,FileMode.Open,FileAccess.Read); fileReader = new StreamReader(readFileStream); } static void CloseDataFiles() { fileReader.Close(); readFileStream.Close(); } } }
// program_id readingBinaryFiles.cs // written_by don voils // date-written 10/30/2006 // description This program demonstrates the reading of // serialzed objects of the class customer // from a binary file. // namespace CustomSerialization { using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers; public class theInputProgram {
file:///D|/1/final/BBL0124.html (21 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
public static int Main(string[] args) { BinaryFormatter myBinaryFormat = new BinaryFormatter(); Customer theCustomer = new Customer(); Stream myStream = File.OpenRead(@"‥\‥\‥\‥\CustomerData.dat"); decimal theTotal = 0.00m; Console.WriteLine(" Accounts Receivable\n\n"); try { while(true) { theCustomer = (Customer)myBinaryFormat.Deserialize(myStream); Console.WriteLine("Customer's ID: "+ theCustomer.customerID); Console.WriteLine("Customer's name: "+theCustomer.firstName + " " + theCustomer.lastName); Console.WriteLine(String.Format("\nBalance due is:{0:c}\n\n", theCustomer.balanceDue)); theTotal += theCustomer.balanceDue; } } catch(SerializationException) { myStream.Close(); } Console.WriteLine("Total Accounts Receivable {0:c}",theTotal); char resp; Console.Write("\n\nContinue?"); resp = Char.Parse(Console.ReadLine()); return 0; } } }
// program_id ReadingRandomAccess.cs // written_by don voils // date_written 12/06/2006 // description This file demonstrates the reading of // random access files. It uses objects from // the class NewCustomer from the file: // NewCustomer.cs // using System; using System.IO; using NewCustomers; namespace ReadingRandomAccessFiles { class ReadingRandomAccess { static FileStream fileInput; static BinaryReader binaryInput; static string randomAccessFile = "randomAccess.dat"; static void Main(string[] args) { char moreData = 'N'; Console.Clear(); NewCustomer theCustomer = new NewCustomer(); if (fileInput != null) fileInput.Close(); // If the file has never been created, then the following will throw an exception
file:///D|/1/final/BBL0124.html (22 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// try { fileInput = new FileStream(randomAccessFile, FileMode.Open, FileAccess.Read); } // If the file did not exist before this run of the program then the follow catch // executes informs the user that there is no data in the customer file. // catch (FileNotFoundException) { Console.WriteLine("There is no data in the customer file. To end press the Enter key."); Console.ReadLine(); return; } binaryInput = new BinaryReader(fileInput); do { int theID; Console.Write("\n\nWhat is the customer ID you are looking for? "); theID = int.Parse(Console.ReadLine()); try { fileInput.Seek(NewCustomer.theSize * (theID - 1), 0); theCustomer.customerID = binaryInput.ReadInt32(); } catch (IOException) { Console.WriteLine("\n\nThat customer ID was not on record!\n"); moreData = 'Y'; } if (moreData != 'Y') { if (theCustomer.customerID == theID) { theCustomer.firstName = binaryInput.ReadString(); theCustomer.lastName = binaryInput.ReadString(); theCustomer.balanceDue = binaryInput.ReadDecimal(); Console.WriteLine("\nCustomer ID: " + theCustomer.customerID); Console.WriteLine("Customer Name: " + theCustomer.firstName + " " + theCustomer.lastName); Console.WriteLine(String.Format("Balance due: {0:c}\n\n", theCustomer.balanceDue)); } else { Console.WriteLine("\n\nThat customer ID was not on record!\n"); } } Console.Write("\n\nProcess another customer? (Y/N). "); moreData = Char.Parse(Console.ReadLine()); Console.Clear(); } while ((moreData == 'Y') || (moreData == 'y')); Console.WriteLine("\n"); } } }
// program_id: WriteToBinaryFile // written_by: don voils // date_written: 11/04/2006 // description: This program writes to binary files. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers;
file:///D|/1/final/BBL0124.html (23 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
namespace WriteToBinaryFiles { class Program { static void Main(string[] args) { Customer theCustomer = new Customer(); IFormatter serializer = new BinaryFormatter(); FileStream theOutFile = new FileStream("Customers.dat", FileMode.Append, FileAccess.Write); char moreData = 'Y'; while ((moreData == 'Y') || (moreData == 'y')) { Console.Clear(); Console.Write("\n\nWhat is the customer's ID? "); theCustomer.customerID = Console.ReadLine(); Console.Write("\n\nWhat is the customer's first name? "); theCustomer.firstName = Console.ReadLine(); Console.Write("\n\nWhat is the customer's last name? "); theCustomer.lastName = Console.ReadLine(); Console.Write("\n\nHow much does the customer owe? "); theCustomer.balanceDue = decimal.Parse(Console.ReadLine()); serializer.Serialize(theOutFile, theCustomer); Console.Write("\n\nEnter another customer (Y/N)? "); moreData = Char.Parse(Console.ReadLine()); } theOutFile.Close(); Console.Clear(); } } }
// program_id WriteToTextFile2.cs // written_by don voils // date_written 3/25/2006 // description This program is similar to WriteToTextFile.cs // except it uses an object of FileInfo rather than // an object of FileStream. // using System; using System.IO; namespace WriteToTextFile2 { class OutPutData2 { static string fileName = @"‥\‥\‥\‥\datafile2.txt"; static FileInfo writeFileStream; static StreamWriter fileWriter; static void Main(string[] args) { OpentoWritetoDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; char moreData = 'Y'; while((moreData == 'Y') || (moreData == 'y')) { Console.Clear(); Console.Write("\n\nWhat is the customer's ID? "); customerID = Console.ReadLine(); fileWriter.WriteLine(customerID); Console.Write("\n\nWhat is the customer's first name? "); customerFirstName = Console.ReadLine(); fileWriter.WriteLine(customerFirstName); Console.Write("\n\nWhat is the customer's last name? ");
file:///D|/1/final/BBL0124.html (24 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
customerLastName = Console.ReadLine(); fileWriter.WriteLine(customerLastName); Console.Write("\n\nHow much does the customer owe? "); customerBalanceDue = decimal.Parse(Console.ReadLine()); fileWriter.WriteLine(customerBalanceDue); fileWriter.Flush(); Console.Write("\n\n\nContinue? (Y/N) "); moreData = Char.Parse(Console.ReadLine()); Console.Clear(); } CloseDataFile(); } static void OpentoWritetoDataFile() { if(fileWriter!=null) fileWriter.Close(); writeFileStream = new FileInfo(fileName); fileWriter = writeFileStream.CreateText(); } static void CloseDataFile() { Console.WriteLine("\n");
} } }
// program_id WriteToTextFiles.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates text file output. // using System; using System.IO; namespace WriteToTextFiles { class OutPutData { static string fileName = @"‥\‥\‥\‥\datafile.txt"; static FileStream writeFileStream; static StreamWriter fileWriter; static void Main(string[] args) { OpentoWritetoDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; char moreData = 'Y'; while((moreData == 'Y') || (moreData == 'y')) { Console.Clear(); Console.Write("\n\nWhat is the customer's ID? "); customerID = Console.ReadLine(); fileWriter.WriteLine(customerID); Console.Write("\n\nWhat is the customer's first name? "); customerFirstName = Console.ReadLine(); fileWriter.WriteLine(customerFirstName); Console.Write("\n\nWhat is the customer's last name? "); customerLastName = Console.ReadLine(); fileWriter.WriteLine(customerLastName); Console.Write("\n\nHow much does the customer owe? "); customerBalanceDue = decimal.Parse(Console.ReadLine()); fileWriter.WriteLine(customerBalanceDue); fileWriter.Flush();
file:///D|/1/final/BBL0124.html (25 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Console.Write("\n\n\nContinue? (Y/N) "); moreData = Char.Parse(Console.ReadLine()); Console.Clear(); } CloseDataFile(); } static void OpentoWritetoDataFile() { if(fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close(); // The enumerator FileMode.Create should be // Append if the file already exists and the // program should add to existing data. // writeFileStream = new FileStream(fileName,FileMode.Create, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } static void CloseDataFile() { Console.WriteLine("\n"); fileWriter.Close(); writeFileStream.Close(); } } }
// program_id writingBinaryFiles.cs // written_by don voils // date_written 10/30/2006 // description This program writes serialized objects // of the class customer to a binary file. // namespace CustomSerialization { using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers; public class theOutputProgram { public static int Main(string[] args) { Customer theCustomer = new Customer(); Stream saveFileStream = File.Open(@"‥\‥\‥\‥\CustomerData.dat",FileMode.Append); BinaryFormatter fileFormatter = new BinaryFormatter(); char moreData = 'Y'; while((moreData == 'Y') || (moreData == 'y')) { clearScreen(); Console.Write("\n\nWhat is the customer's ID? "); theCustomer.customerID = Console.ReadLine(); Console.Write("\n\nWhat is the customer's first name? "); theCustomer.firstName = Console.ReadLine(); Console.Write("\n\nWhat is the customer's last name? "); theCustomer.lastName = Console.ReadLine(); Console.Write("\n\nHow much does the customer owe? "); theCustomer.balanceDue = decimal.Parse(Console.ReadLine()); fileFormatter.Serialize(saveFileStream,theCustomer);
file:///D|/1/final/BBL0124.html (26 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
clearScreen(); Console.Write("\n\n\nContinue? (Y/N)"); moreData = Char.Parse(Console.ReadLine()); clearScreen(); } saveFileStream.Close(); return 0; } static void clearScreen() { for(int index = 0;index<150;++index) Console.WriteLine("\n"); } } }
// program_id WritingRandomAccess.cs // written_by don voils // date_written 10/07/2006 // description This program demonstrates writing random // files using the class NewCustomers that // is defined in the file: NewCustomers.cs. // using System; using System.IO; using NewCustomers; namespace WritingRandomAccessFiles { class WritingRandomAccess { const int NUMBER_NEW_RECORDS = 100; static FileStream fileOutput; static BinaryWriter binaryOutput; static string randomAccessFile = "randomAccess.dat"; static void Main(string[] args) { char moreData = 'Y'; NewCustomer theCustomer = new NewCustomer(); if (fileOutput != null) fileOutput.Close(); // If the file has never been created, then the following will throw an exception // try { fileOutput = new FileStream(randomAccessFile, FileMode.Open, FileAccess.Write); } // If the file did not exist before this run of the program then the follow catch // executes which calls the method CreateFile() which in turn creates the // file with 100 records. // catch (FileNotFoundException) { CreateFile(); if (fileOutput != null) fileOutput.Close(); fileOutput = new FileStream(randomAccessFile, FileMode.Create, FileAccess.Write); } long fileLength = fileOutput.Length; binaryOutput = new BinaryWriter(fileOutput); do
file:///D|/1/final/BBL0124.html (27 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
{ Console.Clear(); Console.Write("\n\nWhat is the cutomer ID? "); theCustomer.customerID = int.Parse(Console.ReadLine()); // If the customerID is beyond the end of the file, // the following loop continues to create additional // blank records in the file until there are more // records than are needed to fit this customer into // the available records in the file. // while (fileLength < (long)(theCustomer.customerID - 1) * NewCustomer.theSize) { CreateMoreRecords(); if (fileOutput != null) fileOutput.Close(); fileOutput = new FileStream(randomAccessFile, FileMode.Open, FileAccess.Write); fileLength = fileOutput.Length; binaryOutput = new BinaryWriter(fileOutput); } Console.Write("\nWhat is the customer's first name? "); theCustomer.firstName = Console.ReadLine(); Console.Write("\nWhat is the customer's last name? "); theCustomer.lastName = Console.ReadLine(); Console.Write("\nWhat is the balance due? "); theCustomer.balanceDue = decimal.Parse(Console.ReadLine()); // Moves the file pointer to the position where the record number is // one less than the customerID. // fileOutput.Seek((theCustomer.customerID - 1) * NewCustomer.theSize, SeekOrigin.Begin); binaryOutput.Write(theCustomer.customerID); binaryOutput.Write(theCustomer.firstName); binaryOutput.Write(theCustomer.lastName); binaryOutput.Write(theCustomer.balanceDue); binaryOutput.Flush(); Console.Write("\n\nEnter another customer? (Y/N) "); moreData = Char.Parse(Console.ReadLine()); Console.WriteLine("\n\n"); Console.Clear(); } while ((moreData == 'Y') || (moreData == 'y'));
} // The following method creates additional blank records for the file // if the number of records is less then needed for a particular // customerID. static void CreateMoreRecords() { NewCustomer blankRecord = new NewCustomer(); if (fileOutput != null) fileOutput.Close(); fileOutput = new FileStream(randomAccessFile, FileMode.Append, FileAccess.Write); binaryOutput = new BinaryWriter(fileOutput); long fileLength = fileOutput.Length; fileOutput.SetLength(fileLength + NewCustomer.theSize + NUMBER_NEW_RECORDS); fileOutput.Position = fileLength; for (int index = 0; index < NUMBER_NEW_RECORDS; ++index) { binaryOutput.Write(blankRecord.customerID); binaryOutput.Write(blankRecord.firstName); binaryOutput.Write(blankRecord.lastName); binaryOutput.Write(blankRecord.balanceDue); binaryOutput.Flush(); }
file:///D|/1/final/BBL0124.html (28 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
} // The following method creates the file and places 100 blank records into // the file provided the file did not exist prior to this run of the program. // static void CreateFile() { NewCustomer blankRecord = new NewCustomer(); if (fileOutput != null) fileOutput.Close(); fileOutput = new FileStream(randomAccessFile, FileMode.Create, FileAccess.Write); binaryOutput = new BinaryWriter(fileOutput); long fileLength = fileOutput.Length; fileOutput.SetLength(fileLength + NewCustomer.theSize + NUMBER_NEW_RECORDS); fileOutput.Position = fileLength; for (int index = 0; index < NUMBER_NEW_RECORDS; ++index) { binaryOutput.Write(blankRecord.customerID); binaryOutput.Write(blankRecord.firstName); binaryOutput.Write(blankRecord.lastName); binaryOutput.Write(blankRecord.balanceDue); binaryOutput.Flush(); } } } }
file:///D|/1/final/BBL0124.html (29 von 29) [01.12.2007 04:50:23]
Lecture 15: Accessing Data with ADO.NET
Lecture 15: Accessing Data with ADO.NET Notice: The examples in this lecture require the use of two Access databases: Northwind.mdb and Expenses.mdb. These databases are not included in this book. If you would like to acquire these databases, email: [email protected].
Accessing and Changing Database Data with ADO.NET Introduction to ADO .NET Modern programs need to access stored data. Up to this point in the lectures only C# text file, binary file and random access file I/O have been discussed. While these approaches can handle some I/O needs, they do not handle all I/O needs. Today one of the more important tools for handling I/O are databases and XML data files. To handle database I/O and XML data files, Visual Studio . NET introduced ADO .NET an extension of ADO that was used with C++ and Visual Basic. ADO .NET is a significant improvement over ADO. While Visual Basic was the main tool for ADO, C# is a tool in addition to Visual Basic that may be used with ADO .NET. ADO .NET can be used with Console, Windows and web programs. This lecture is only an introduction to the topic of ADO .NET. This introduction will only discuss ADO .NET used with Console and Windows programs that utilize Access databases. To fully study this topic would require that the prerequisite of these lectures should be one or more courses on database management as well as requiring that the reader have experience in the database management field. If this is going to be a need-to-know topic, then after this brief introduction, it is recommended that one of the several books on the market that address ADO .NET specifically should be consulted to obtain a more in-depth coverage of the topic. Since Visual Studio .NET 2005 was introduced in November of 2005, the books to be read need to address .NET 2005 This is especially true, since the 2005 version has added a significant number of new tools to make the job of working with ADO .NET easier for both Windows and for Web forms as well. There is a claim that a .NET 2007 is in preparation and it is supposed to be adding many additional tools for ADO .NET. Therefore the reader should consult the Microsoft web site to keep tract of the additional modifications that are in store with this up coming revision. Note: It is assumed that you have some knowledge of database theory in particular Access. If you do not, then refer to the discussion in some Access database textbook. Since Microsoft Office 2007 is being introduced, a book on Access 2007 should be consulted.
The Database Samples These notes will address ADO .NET using Access database files because many universities' computer labs do not permit the use of the SQL Express that is included in Visual Studio .NET 2005. While the notes will discuss Access databases, it should be possible for you to install and to use SQL Express that is included with Visual Studio .NET 2005. If this is the approach you would like to take, consult some of the ADO .NET books on the market as to how to install and use SQL Express. The Access databases that will be discussed during this lecture are Northwind. mdb and expenses.mdb. To enable this discussion, download each of these files from this web site and install each of them into the Visual Studio Projects 2005 folder on the computer you are using so that the examples of this lecture may access these databases. The graphic below depicts the many different tables incorporated into the Northwind data base and the interrelationships between these tables. In these notes only two of these tables will be used in the examples of this lecture: Customers and Orders:
The expenses.mdb database is much simpler since it only contains two tables: GLAccounts and Checks. The table: GLAccounts has two fields: GLAccountNumber and GLAccountName. The table: Checks has the fields: GLAccountNumber, CheckDate, PayeeName, CheckNumber and CheckAmount. Both of these databases will be used in the following examples.
Using the DataReader to Read Data file:///D|/1/final/BBL0125.html (1 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
Example 1: This section of the lecture will discuss reading data using the DataReader in a Console program. As the name of this tool indicates, it is only for the purpose of reading data from the records. The first step is to create a Console project and name it: SelectCustomers.cs. Open up the Program.cs file in the Code View addition. The next step is to include additional using statements to permit the program to work with the Access data bases. Add the second and third using statements listed below to the top of the code: using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text;
The second using permits the program to work with database files. The third using statement permits the program to work with several databases including Access. Note: If the program was to use the SQL server, then the third using would be the following: using System.Data.SQLClient; If a database other than Access or SQL were used, then a different using statement would need to be used to replace the third using statement in order to permit the program to work with the type of database selected. The next step is to add the following line of code This statement defines a connection between the program and the Access database: Northwind. mdb. OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Northwind.mdb");
Note: Be sure that the code after the @ is all in one line or the program may not work. Further the location implies that the Northwind.mdb is in the bin/Debug folder of the project. If the database was in a different location, then the path to the database would need to be listed before that database's name. In each of the examples below, it will be necessary to copy the database into the bin/Debug folder of the project. Next the following statement needs to be added. It opens this connection: customerConnection.Open();
The next statement creates a command reference and the second statement states that the program would use the two fields CustomerID and CompanyName from the table Customers (if more fields were used, then each of them would need to be listed in addition to these two fields): OleDbCommand accessCommand = customerConnection.CreateCommand(); accessCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers";
and then the code must include the following statement which defines the DataReader: OleDbDataReader customerReader = accessCommand.ExecuteReader();
Of course the name of the OleDbCommand and the name of the OleDbDataReader object may be different than accessCommand and customerReader respectively. The program is now ready to read the data in from the Customers table. What needs to be done now is to create a loop that will continue to read the data until it has all been read in and displayed on the screen. The following code will achieve this objective: int numberCustomers = 1; OleDbDataReader customerReader = accessCommand.ExecuteReader(); Console.WriteLine("{0}\t{1}", " Customer ID", "Customer Name"); Console.WriteLine("{0}\t{1}", " -----------", "-------------"); while (customerReader.Read()) { Console.WriteLine("{0,3} {1}\t{2}",numberCustomers, customerReader["CustomerID"], customerReader["CompanyName"]); ++numberCustomers; file:///D|/1/final/BBL0125.html (2 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
}
What needs to be done next would be to close the reader and then close the connection with the following two statements: customerReader.Close(); customerConnection.Close();
This completes the necessary code so compile and run the program. Notice that the code has addtional code to make the program more user friendly. Compile and run the program. What should be seen on the screen will be a table listing the CustomerID and the CustomerName for each of the 90+ records. (Remember that the Northwind.mdb must be in the bin/ Debug folder of the program.) To view what the program should look like link to the following file: :SelectCustomers.cs. Example 2: Next consider an example using the database: expenses.mdb. Create a Console project called: ChartOfAccounts.cs and copy the follow code into the project. Copy the database: expense.mdb to the bin\Debug folder of the project. As with the previous example, the following using statements need to appear at the top of the project: using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text;
Instead of the statements for the Customers table in the Northwind.mdb database, this time statements about the GLAccounts table in the database expenses.mdb will be included in the code. So at the top of Main() add the following statements: OleDbConnection GLAccountConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=expenses.mdb"); GLAccountConnection.Open(); OleDbCommand accessCommand = GLAccountConnection.CreateCommand(); accessCommand.CommandText = "SELECT AccountID, AccountName FROM GLAccounts"; OleDbDataReader AccountReader = accessCommand.ExecuteReader();
and then to read the data the following while() loop is needed: int numberAccounts = 0; Console.WriteLine("\t\tChart of Accounts"); Console.WriteLine(" {0} \t{1}", " GL Account Number", "GL Account Name"); Console.WriteLine("------------------------------"); while (AccountReader.Read()) { ++numberAccounts; Console.WriteLine("{0,3} \t{1}\t\t{2}", numberAccounts, AccountReader["GLAccountNumber"], AccountReader["GLAccountName"]); } Console.WriteLine("\n\nThere are {0} GL Accounts.\n",numberAccounts);
and at the bottom of Main() add the following two lines: AccountReader.Close(); GLAccountConnection.Close();
Compile and run the program to view the Chart of Accounts of this company. To view the program, link to the following: ChartOfAccounts.cs and view the code.
Using the DataReader to Search for Data Example 1: Now suppose that you wanted to find a record whose CustomerID was a particular value say: THEBI or VICTE. Create a project: SelectCustomer2.cs In Program.cs enter the same code as in SelectCustomers.cs above. Place Northwind.mdb into the bin\Debug folder. file:///D|/1/final/BBL0125.html (3 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
The next step would be to add code that would request the CustomerID just above the loop like the following: Console.Write("What is the customer number? "); string theCustomerID= Console.ReadLine();
Then inside of the loop add the following if() statement. if(theCustomerNumber == String.Format("{0}", customerReader["CustomerID"])) { Console.WriteLine("{0,3} {1}\t{2}",numberCustomers, customerReader["CustomerID"], customerReader["CompanyName"]); }
Compile and run the program. Use the two CustomerIDs listed above to see what happens. To view of the code, link to the following file: SelectCustomers2.cs. The previous two examples only worked with only two of the fields of the Customers table. Check out SelectCustomer3.cs to notice that additional fields may be used as well. This example in addition used the field: Phone. Create a Console project and copy this file into the project, compile and run it. (Remember that the Northwind.mdb must be in the bin/Debug folder of the program.) Example 2: The previous two examples used the Customers table in the database: Northwind.mdb. These techniques may also be used with other databases and their tables as well. For example, it is possible to use the database: expenses.mdb and its table: GLAccounts. Create a project: GLAccounts.cs. At the top of the project are the same using statements. Inside of Main() the following statements (which are similar to those used with the Customers above) need to be added: OleDbConnection GLAccountConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=expenses.mdb"); GLAccountConnection.Open(); OleDbCommand accessCommand = GLAccountConnection.CreateCommand(); accessCommand.CommandText = "SELECT GLAccountNumber, GLAccountName FROM GLAccounts"; OleDbDataReader GLAccountReader;
Next include the following code: char doAnother; int numberAccounts; do { Console.Clear(); GLAccountReader = accessCommand.ExecuteReader(); numberAccounts = 1; Console.Write("What is the GL Account Number? "); string theGLAccountNumber = Console.ReadLine(); Console.Clear(); bool isThere = false; Console.WriteLine("\n\n {0,-20}\t{1,-20}", "GL Account Number","GL Account Name"); Console.WriteLine(" {0,-20}\t{1,-20}", "-----------------", "---------------"); while (GLAccountReader.Read()) { if (theGLAccountNumber == String.Format("{0}", GLAccountReader["GLAccountNumber"])) { Console.WriteLine("{0,3}{1,18}\t {2,20}", numberAccounts, GLAccountReader["GLAccountNumber"], GLAccountReader["GLAccountName"]); isThere = true; } ++numberAccounts; } if (!isThere) {
file:///D|/1/final/BBL0125.html (4 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
Console.WriteLine("\n\nThat account number is not on file!"); } Console.WriteLine("\n\n All {0} of the GL Accounts have been checked.\n\n", --numberAccounts); Console.Write("\nWhat you like to search for another account? (Y/N) "); doAnother = Char.Parse(Console.ReadLine()); GLAccountReader.Close(); } while ((doAnother=='Y')||(doAnother=='y'));
Then when the program terminates the following statement needs to execute so place it at the bottom of the code: GLAccountConnection.Close();
Compile the project.and run the program. Try different values for the GLAccountNumber requested including some that are in the table and some that are not. To view the code link to the following file: GLAccounts.cs.
Using the DataSet to Read Data The examples in the previous sections only permitted the reading of data by using the DataReader . As the name implies, this class is used to only read data. There is an additional class, the DataSet that permits not only the reading but the updating of data as well. This section of the lecture will only consider the reading of data using the DataSet and another section will demonstrate the modifications of the data. Create a project: DataSetCustomers.cs Don't forget to copy Northwind.mdb into the bin\Debug folder of the program before you run it. The using statements in the previous programs are used in this project as well. What changes is the code within Main(). What needs to be included this time are the following statements: OleDbConnection customerConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName, Phone FROM Customers", customerConnection); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers");
Again note that the names of the objects that are defined in the code above could be any programmer name. Notice the method Fill() which is used to place a copy of the database table: Customers into memory in the customerDataSet. This time instead of a while() loop, a foreach() will be used instead as noted in the following code: int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", foreach(DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; }
Another difference between this program and the previous one is that the DataSet does not need to be closed like the Reader did. Here only the Connection requires the followig statement: customerConnection.Close();
file:///D|/1/final/BBL0125.html (5 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
Now that the program is complete, compile and run it. Notice that the output is the same as an example using the DataReader. To see a copy of the code, link to the follow file: DataSetCustomers.cs Note: This example used the Customers table in the data base: Northwind.mdb. A table from the database: expenses.mdb could have been used in a similar fashion.
Using the DataSet to Modify a Field The next step is to consider not only how to view a record but how to modify a record, how to add a record and finally how to delete a record. In order to accomplish this task, the DataSet must be used rather than the DataReader because the DataReader is just for reading of data as its name implies. As you will see, the DataSet not only permits the changing of the data in memory but it also updates the database as well. The next example will show how to modify a field in the Customers tables of the Northwind.mdb database. To achieve this objective, create a Console project: named: ModifyCustomersinMemory.cs. Using the same using statements. In Main() should be the following statements: OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName, Phone FROM Customers", customerConnection); OleDbCommandBuilder theBuilder = new OleDbCommandBuilder(customerAdapter); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers");
Next add the following code: Console.Write("What is the number of the customer you want to change" + " the name? "); int customerRecord = Int16.Parse(Console.ReadLine()); customerRecord--; Console.WriteLine("\nThe current name is: {0}\n", customerDataSet.Tables["Customers"].Rows[customerRecord]["CompanyName"]); Console.Write("\nWhat do you want to change the name to? "); string newName = Console.ReadLine(); customerDataSet.Tables["Customers"].Rows[customerRecord]["CompanyName"] = newName;
The code above takes the record number submitted by the user and lists that particular customer's CompanyName on the screen using the Rows[ ] array. It then prompts the user for what the new CompanyName should be by requesting the row number listed in the table. Using that particular number for the Row[ ], the CompanyName is replaced by the name entered by the user. Compile and run the program. The program will list all of the Customers on file. Pick the number of one of the names to change. Supply this number when requested. Change the name to The Big Company. Notice that when the program lists the names again after the change, that particular name was changed to this new value. Next shut the program down and then start it again. Notice that when you run the program once more, that name has returned to its original value. Therefore the value in memory was changed but not the value in the Customers table of the database. To modify the fields in the Customers' table of the database requires the use of the method: Update(). The following code needs to be added to the program when the update to the database is desired: customerAdapter.Update(customerDataSet,"Customers");
Add the line above to the code just below the following line: customerDataSet.Tables["Customers"].Rows[customerRecord]["CompanyName"] = newName;
Compile and run the program. Change the CompanyName of a customer. Be sure to note where it was changed. Close the program down, and run it again. Notice that the name was not only been changed in memory as before, but it has now been changed in the database as well. To view a copy the program link to the following file: ModifyCustomersInMemory.cs.
Using the DataSet to Add a Record file:///D|/1/final/BBL0125.html (6 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
Create the project: AddRowsToCustomers.cs. Copy the following file into the project: DataSetCustomers.cs. Copy Northwind.mdb to the bin \Debug folder of the project. Change the top statements to the following: OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName FROM Customers", customerConnection); OleDbCommandBuilder thisBuilder = new OleDbCommandBuilder(customerAdapter); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers");
Just after the foreach() and just before: customerConnection.Close();
add the following code: Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n", --numberCustomers); DataRow thisRow = customerDataSet.Tables["Customers"].NewRow(); numberCustomers = 1; Console.Write("What is the Customer ID you are adding? "); string theID = Console.ReadLine(); Console.Write("\n\nWhat is the Company Name? "); string theName = Console.ReadLine(); thisRow["CustomerID"] = theID; thisRow["CompanyName"] = theName; customerDataSet.Tables["Customers"].Rows.Add(thisRow);
In the code above, notice the definition of the object: thisRow which receives the output of the NewRow() method. This action adds a new row to the table in memory. Using thisRow, the CustomerID and the CompanyName fields of the new row receive values from the keyboard input. Recall that there are addtional fields in this record. Since these fields are not receiving data, each of them will receive the null value. After the above code and once again, just before the Close() statement, add the following code: Console.WriteLine("# of rows after change: {0}", customerDataSet.Tables["Customers"].Rows.Count); Console.WriteLine("\n\n {0}\t{1}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}", " -----------", "---------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"]); ++numberCustomers; } Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n", --numberCustomers); customerAdapter.Update(customerDataSet, "Customers");
This code will show what is currently in memory but remember that the data in the database has not yet been updated and if the program ended prior to the last statement above, then the new data would be lost.
file:///D|/1/final/BBL0125.html (7 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
The last statement contains a call to the method: Update(). This method as in the previous example, checks the database against the data that is currently in memory and if there have been any modifications, the database will be updated. Compile and run the program. Add several records and then end the program. This modified copy of Northwind.mdb will be used in the next example so make one of the CustomerID's: AAAA. After the program has ended, start it again and notice that the table Customers in the database has been changed. To see what this program looks like, link to the following: AddRowsToCustomers.cs
Using the DataSet to Delete a Record Create the project: DeleteRowstoCustomers.cs. Copy the code from the file: DataSetCustomers.cs. into the project. Copy the Northwind.mdb from the previous program's bin\Debug and copy it into this projects bin\Debug folder. Note: The reason for using this modification to Northwind.mdb is that some of the records in the Customers table are related to records in the Orders table and if an attempt is made to delete records in the Customers table that have corresponding records in the Orders table, the program will throw an exception. As was done in the previous example, add the following statement: OleDbCommandBuilder tableBuilder = new OleDbCommandBuilder(customerAdapter);
just before the following statement: DataSet customerDataSet = new DataSet();
Just after the displaying of the records of the table: Customers replace the remaining code with the following: DataColumn[] theKeys = new DataColumn[1]; theKeys[0] = customerDataSet.Tables["Customers"].Columns["CustomerID"]; customerDataSet.Tables["Customers"].PrimaryKey = theKeys; Console.Write("\nWhat is the Customer ID for the record you wish to remove? "); string theCustomerID = Console.ReadLine(); try { DataRow rowToDelete = customerDataSet.Tables["Customers"].Rows.Find(theCustomerID); if (rowToDelete != null) { Console.WriteLine("\n{0} is in the table.", theCustomerID); rowToDelete.Delete(); customerAdapter.Update(customerDataSet, "Customers"); Console.WriteLine("\nThat record has been deleted from the database.\n"); } else Console.WriteLine("\n{0} was not in the table.\n", theCustomerID); Console.WriteLine("Press any key to continue."); Console.ReadKey(); Console.Clear(); numberCustomers = 1; Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------","--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } } catch (Exception e) file:///D|/1/final/BBL0125.html (8 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
{ Console.WriteLine("\nThat record may not be deleted. {0}", e.Message); } finally { customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n" + "Press any key to exit.\n", --numberCustomers); Console.ReadKey(); }
Notice in the code above the following statement: DataRow rowToDelete = customerDataSet.Tables["Customers"].Rows.Find(theCustomerID);
This line attempts to find the record to delete. Then the following code: if(rowToDelete != null)
will be used to determine whether the record is there or not. If the record is in the database, then rowToDelete.Delete();
attempts to delete the row. If it is not there, then the else statement will tell the user that the record was not there. But should the record selected for deletion have related records in the Orders table, then an exception is thrown. This exception is handled by the catch() block statements which will tell the user that the record may not be deleted because of this relationship. In either case, the finally block is used to close the connection. Compile and run the program. The first time try for the CustomerID one for the records listed near the bottom which you added in the previous example.: e.g. AAAA. Notice that the program functioned correctly and that these records were deleted. Run the program a second time. This time use ZZZZ for the customerID. (Assuming that you did not add it in the previous example.) This time the program should again work correctly except you will be told that the record did not exist. Run the program one more time. This time select as CustomerID from one of the records higher in the list to delete: e.g. VICTE. For this example, notice that an exception was thrown but the code caught it and the program functioned correctly. To see the program link to DeleteRowstoCustomers.cs.
Viewing Data in Multiple Related Tables In the examples above the data used was only from one table. However in Northwind.mdb, there are several other tables some of which are related. For example the table Customers has a relationship with the table Orders. For example a customer may have several orders outstanding. Create a Console project: CustomersAndOrders.cs Copy Northwind.mdb to the bin\Debug folder of the project. At the top of the project add the using statements discussed above. Inside of Main() add the following statements: OleDbConnection thisConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter theAdapter = new OleDbDataAdapter( "SELECT CustomerID, CompanyName FROM Customers", thisConnection); OleDbCommandBuilder theBuilder = new OleDbCommandBuilder(theAdapter); DataSet thisDataSet = new DataSet(); OleDbDataAdapter customerAdapter = new OleDbDataAdapter( "SELECT * FROM Customers", thisConnection); OleDbDataAdapter ordersAdapter = new OleDbDataAdapter( "SELECT * FROM Orders", thisConnection); customerAdapter.Fill(thisDataSet, "Customers"); ordersAdapter.Fill(thisDataSet, "Orders"); DataRelation customersandOrdersRelation = thisDataSet.Relations.Add("CustomerOrders", thisDataSet.Tables["Customers"].Columns["CustomerID"], thisDataSet.Tables["Orders"].Columns["CustomerID"]); int numberCustomers = 0; file:///D|/1/final/BBL0125.html (9 von 10) [01.12.2007 04:50:26]
Lecture 15: Accessing Data with ADO.NET
foreach (DataRow customerRow in thisDataSet.Tables["Customers"].Rows) { numberCustomers++; Console.WriteLine("\nCustomer ID: " + customerRow["CustomerID"] + " Company Name: " + customerRow["CompanyName"]); foreach (DataRow orderRow in customerRow.GetChildRows(customersandOrdersRelation)) { Console.WriteLine(" Orders: " + orderRow["OrderID"]); } if (numberCustomers == 10) { Console.WriteLine("\n\nPress the Enter key to continue."); Console.ReadKey(); Console.Clear(); numberCustomers = 0; } } thisConnection.Close(); Console.WriteLine("Press any key to continue."); Console.ReadKey();
Compile and run the program. What should be seen will be a list of each customers followed by their respective orders. The program originally had a problem in that there are so many customers and orders not all of them are viewable at one time. However the buffer will overflow making it so that some of the data will be lost from view. For this reason a counter on the number of customers was added to make the output more readable. See CustomersAndOrders.cs
file:///D|/1/final/BBL0125.html (10 von 10) [01.12.2007 04:50:26]
Using ADO.NET wizards on a Single Table
Using ADO.NET wizards on a Single Table Using the Data Source Configuration Wizard Visual Studio .NET 2005 has several wizards built into the IDE which permit the programmer to create Windows GUI programs using ADO .NET far easier than the code demonstrated in the previous section of this lecture. This section will show some of these features. It appears that .NET 2007 will have even more wizards to make coding with ADO .NET even easier than will be demonstrated here. Open a C# Windows project and call it customers1. When the window of the project opens, change the Form1's Text to Customers. Next the Server Explorer needs to be made available as a tool. To begin click on Connect to Database under the Tools menu options as in the following:
When you do, a dialog like the following will appear (Note: This is what will appear assuming that this is the first time this step has been taken. However, if the following configuration has been taken before, then the next step will appear at this point.) :
Observe at the top of the list is the link to Microsoft Access Database File. Click on this selection and then click the Continue button. When you do, the Add Connection dialog like the following appears:
file:///D|/1/final/BBL0126.html (1 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Next click the Browse button and a dialog like the following should open to enable you to search where you downloaded Northwind.mdb in the previous examples to the Visual Studio 2005/Projects. Select Northwind. mdb.
Next click the Open button and the Add Connection dialog should now appear as the following:
file:///D|/1/final/BBL0126.html (2 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
If it is not clear whether the data base was connected to the program correctly, click on the Test Connection button near the bottom. If the connection is made, then the following should appear on the screen (otherwise the steps above should be followed once more or go into Access and try to open the file):
Follow this action by clicking the OK button on the Messagebox and then the OK on the Add Connection dialog box. After completing these tasks, the Data Connections in the Server Explorer should now have a + to the left. Click this + to reveal the options: Tables, Views and Stored Procedures. Click the + near Tables. The table names should now appear as below showing all of the tables in this database.
file:///D|/1/final/BBL0126.html (3 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Next click the Data option on the menu bar and select Add New Data Source like the following:
This selection should bring up a screen like the following:
file:///D|/1/final/BBL0126.html (4 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Select the Database option and click the Next > button. When this is done the next dialog should be like the following:
Click the Next > button one more time. When this is done, the following screen should appear. Note that the NothwindConnectionString is being created:
file:///D|/1/final/BBL0126.html (5 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Click the Next > button on this screen and you should see the following after clicking the + sign to the left of both the Tables and Customers. This example will use just the CustomerID, CustomerName and ContactName fields so click the checkboxes to the left of each of these fields and then click the Finish button:
Next click on the Data menu option and select Show Data Source as in the following:
file:///D|/1/final/BBL0126.html (6 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
A Data Sources window like the following should appear:
Click on each of the Customers' fields that were selected one at a time and drag them onto the form. When you do, the following will appear like the following after some adjustments for size and location of these tools:
file:///D|/1/final/BBL0126.html (7 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Notice the tools that were added to the bottom of the form. Next look at the top of the form. Notice tools that were added automatically to the form. For example there are the arrows, the + sign, the red X and the Save button. Each of these tools was added automatically to the form without the need to do any coding just the dragging of the fields onto the form. Change the Text of the Form to Customers and then compile and run the program. What you should see is something like the following:
Notice that when the program runs, that the data from the table is loaded into the form. Using the blue arrows, it is possible to move one record at a time up or down the table or use the blue arrows with the bar to move to the beginning or to the end of the table. By clicking the + sign, blank fields appear in the table permitting the user to add data to a new record. Click this button and add some data to the empty fields as it appears in the graphic below. This can be followed up by clicking the Save button to save the new data into the table in RAM. Notice that the Northwind database was
file:///D|/1/final/BBL0126.html (8 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
attached to the form and the following record is displayed in the table. The table now lists 92 records:
Using the arrows, move around in the different records and observe the field data. Next click the + button once again. Remember that this button is for the purpose of adding records. Notice that the fields are now empty again and the number of records listed is now 93. Enter some data into the fields. Take these steps several times so that there are at least 95 records listed. Notice that there is a X button. This button is for the purpose of deleting records from the table held in RAM. Click it. Notice that the number of records is now 94. By using the arrows and move around in the data, you will notice that the 95th record was deleted. After making these changes, press the Save button. Next shut the program down and then restart it. What should now appear are the 91 records that were in the original database plus the 3 additional ones that you entered. Note: While there were new records stored in RAM, the new records may not have been saved to the table. The claim by one author was that early versions of Visual Studio .NET 2005 do not save the data to the table stored on the disk. However this was fixed and later versions apparently do save the new fields to the database. What I found was that if you leave Visual Studio .NET and go to the bin\Debug folder and double click on the .exe file, following this up by the same steps taken above, the data entered will be saved.
Using the DataGrid View Visual Studio has additional ADO .NET features which may be used to view the data. One of these is the DataGridView. This view shows the data in a format similar to one you would see in a spreadsheet where the records are the rows and the fields are the columns. Using the example above, make the form larger. Make the Size, Minimum Size and the Maximum Size 600, 530. Next click on the Customer table link in the Data Sources dialog like the following:
file:///D|/1/final/BBL0126.html (9 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Next drag this link onto the enlarged form and then stretch the DataGrid to look like the following:
After making the above changes have been made, compile and run the program. The form should now look like the following with the data not only in the textboxes but also in the DataGrid below:
file:///D|/1/final/BBL0126.html (10 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Using either the arrows at the top of the form, the vertical scroll on the right of the DataGrid, or by just moving the cursor up and down through the columns, notice how the DataGrid provides a new view and a new way to access this data. As you scrolled through the data, you should have noticed that some of the data in the CompanyName and in the ContactName columns were not viewable. What needs to be done is to format the DataGrid so that the columns are wide enough to permit a complete view of the data in each column. To achieve this objective, do a right click on the DataGrid and select Edit Columns as in the following graphic:
When this is done, the screen should show a view like the following:
file:///D|/1/final/BBL0126.html (11 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Clicking on the field name on the left one at a time, in the Bound Column Properties window, change the Width of CustomerID to 75, CompanyName to 200 and ContactName to 180. Now compile and run the program. The form should now appear like the following:
There are several other modifications that can be made in addition to changing the size of the columns. For example, it is possible to change the appearance of the form. One way of doing this is to right click on the DataGrid and select Properties. Under Properties select the button to the right of : ColumnHeadersDefultCellStyle. Like the following:
file:///D|/1/final/BBL0126.html (12 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
When this button is clicked a CellStyle Builder dialog like the following will appear:
Click on the BackColor button on the right and then the following selections will appear:
file:///D|/1/final/BBL0126.html (13 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Under the Web tab, select Orchid. Now compile and run the program. The DataGrid should now appear like the following:
When you get a chance, experiment with some of the other options in the CellStyle Builder.
Using a Listbox View Other controls may be used as well. For example, it is possible to place a ListBox onto the form and then to connect it to one of the fields. To achieve this objective, using the Toolbox place a ListBox onto the form to the right of the textboxes like the following:
file:///D|/1/final/BBL0126.html (14 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Next, click on the Listbox and then on Properties. On Properties select DataSource and then customersBindingSource as in the following:
After having selected customerBindingSource for DataSource, click on DisplayMember and select CustomerID as in the following:
file:///D|/1/final/BBL0126.html (15 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
To complete this exercise, place a label with the following text above the listbox: Select Cusomter ID. Compile and run the program. The form should now appear as in the following:
In previous Windows examples, there were only three files that needed to be viewed and copied: Form1.cs, Form1. Designer.cs and Program.cs. However in the program created up to this point, there are several other files as can be seen in looking at the following graphic of the Solution Explorer:
file:///D|/1/final/BBL0126.html (16 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
In particular notice the file app.config. Double click on this file listed in the Solution Explorer. Notice that this file contains XML instructions about the configuration of the database as can be seen in the following:
Additional files listed in the Solution Explorer include: ●
Northwind.mdb
●
NorthwindDataSet.xsd ❍
NorthwindDataSet.Designer.cs
❍
NothwindDataSet..xsc
❍
NothwindDataSet.xss
Double click on NorthwindDataSet.Designer.cs and observe all of the code in the file. This code was generated by the IDE and should not be modified.
file:///D|/1/final/BBL0126.html (17 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizard on Multiple Related Tables
Using ADO.NET wizard on Multiple Related Tables This exercise will discuss how a program can be created that permits the viewing of fields from two different but related tables in the Northwind database namely the Customers and Orders tables. Begin by creating the project: CustomerOrders. Change the Text of Form1 to Customer Orders.
Proceed as was done in the previous example except when the tables are being selected. In this case the Server Explorer should show something like the following:
Notice in the graphic above that the following fields have been selected in the Customers table and in the graphic below that the Orders fields listed below have been selected: ●
Customers Table:
file:///D|/1/final/BBL0127.html (1 von 4) [01.12.2007 04:50:28]
Using ADO.NET wizard on Multiple Related Tables
●
❍
CustomerID
❍
CompanyName
❍
ContactName
❍
Phone
Orders Table ❍
OrderID
❍
CustomerID
❍
EmployeeID
❍
OrderDate
These fields from the two related tables will be used in this exercise. Next under the Data menu option, select Show Data Source and the following Data Sources will appear:
file:///D|/1/final/BBL0127.html (2 von 4) [01.12.2007 04:50:28]
Using ADO.NET wizard on Multiple Related Tables
Grab each of the fields for the table: Customers and add them to the form. Arrange them in an attractive manner similar to the following:
Next click on the Orders icon that is listed a part of the Customers listing and drag it onto the form adjusting the size to look similar to the following:
file:///D|/1/final/BBL0127.html (3 von 4) [01.12.2007 04:50:28]
Using ADO.NET wizard on Multiple Related Tables
Next compile and run the program. When you do, a screen similar to the following should appear:
Next click on the arrows and move around in the Customers data. As you move around in this table, the Orders data in the Data Grid below should now reflect those Orders for the Customers viewed as in the following graphic:
This exercise has demonstrated how a form can be made which demonstrates how the ADO.NET can be used on Multiple Related Tables. If you click on the add or the delete buttons, then it adds or deletes the customer records and their related orders.
file:///D|/1/final/BBL0127.html (4 von 4) [01.12.2007 04:50:28]
An Expense Ledger: Using DataSet and Windows Forms
An Expense Ledger: Using DataSet and Windows Forms This section of the lecture will demonstrate the use of a DataSet with a Windows Form. To begin, create a Windows project: ExpenseLedger.cs. Copy the database: expenses.mdb into the bin\Debug folder of the project. Check the using statements at the top of the program to ensure that the following two are there and if not, add them: using System.Data; using System.Data.OleDb;
Change the Text of the form to Expense Ledger. Change the Font to Bold. Change the Size, Minimum Size and Maximum Size to 410, 300. Drag on to the form: five labels, four textboxes, one button and one DateTimePicker. Change the Text of the labels and the button and arrange each of these tools to make the Form look similar to the following:
Change the Form1 constructor to the following: public Form1() { InitializeComponent(); txtGLAccountNumber.Focus(); }
Double click on the Add button. When the event handler opens, add the following code: private void btnAddRecord_Click(object sender, EventArgs e) { // Be sure that the following is all in one line of code. // OleDbConnection expensesConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;
file:///D|/1/final/BBL0128.html (1 von 2) [01.12.2007 04:50:28]
An Expense Ledger: Using DataSet and Windows Forms
Data Source=expenses.mdb"); // Be sure that the following is all in one line of code. // OleDbDataAdapter expensesAdapter = new OleDbDataAdapter("SELECT GLAccountNumber,PayeeName,CheckNumber, CheckAmount,CheckDate FROM Checks", expensesConnection); OleDbCommandBuilder thisBuilder = new OleDbCommandBuilder(expensesAdapter); DataSet expensesDataSet = new DataSet(); expensesAdapter.Fill(expensesDataSet,"Checks"); DataRow thisRow = expensesDataSet.Tables["Checks"].NewRow(); thisRow["GLAccountNumber"] = String.Format("{0}",txtGLAccountNumber.Text); thisRow["PayeeName"] = String.Format("{0}",txtPayeeName.Text); thisRow["CheckDate"] = checkDate.Value; thisRow["CheckNumber"] = Int32.Parse(String.Format("{0}", txtCheckNumber.Text)); thisRow["CheckAmount"] = Convert.ToDouble(txtCheckAmount.Text); expensesDataSet.Tables["Checks"].Rows.Add(thisRow); expensesAdapter.Update(expensesDataSet,"Checks"); txtGLAccountNumber.Clear(); txtPayeeName.Clear(); txtCheckNumber.Clear(); txtCheckAmount.Clear(); txtGLAccountNumber.Focus(); expensesConnection.Close(); }
Compile and run the program. Enter several checks into the program and click the Add button after each check has been entered. After you have entered several checks, open expenses.mdb in Access and look at the data in the Checks table to see if the data you entered was stored into the database correctly. See the file: ExpenseLedger. cs
file:///D|/1/final/BBL0128.html (2 von 2) [01.12.2007 04:50:28]
Lecture 15 Examples
Lecture 15 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
AddRowstoCustomers.cs
This program demonstrates how to modify add rows to a table.
ChartOfAccounts.cs
This program demonstrates the use of the reader to read data from the GLAccounts table in the expenses.mdb database.
CustomersAndOrders.cs
This program demonstrates how to view the data in related tables of a database.
DataSetCustomers.cs
This program demonstrates how to view data using a Data Set.
DeleteRowstoCustomers.cs
This program demonstrates how to delete records from a database table data using a Data Set.
expenses.mdb
An Access database that is used in several of the examples in this lecture.
ExpenseLedger.cs
This program along with the Access database: expenses.mdb simulates an Expense ledger.
GLAccounts.cs
This program demonstrates how to find a particular GL Account in the database expenses.mdb GLAccounts table.
ModifyCustomersInMemory. cs
This program demonstrates how to modify data in memory using a Data Set.
Northwind.mdb
An Access database that is used in several of the examples in this lecture.
SelectCustomers2.cs
This program demonstrates how to view data how to find a particular record.
SelectCustomers3.cs
This program demonstrates how to view data how to find a particular record.
SelectCustomers.cs
This program demonstrates how to view data.
// program_id AddRowstoCustomers.cs // written_by Don Voils // date_written 11/16/2006 // description This program demonstrates how to modify add // rows to a table. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers4 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName FROM Customers", customerConnection); OleDbCommandBuilder thisBuilder = new OleDbCommandBuilder(customerAdapter); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers"); int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}", "Customer ID", "Customer Name");
file:///D|/1/final/BBL0129.html (1 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
Console.WriteLine("{0}\t{1}", " -----------", "--------------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"]); ++numberCustomers; } Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n", --numberCustomers); DataRow thisRow = customerDataSet.Tables["Customers"].NewRow(); numberCustomers = 1; Console.Write("What is the Customer ID you are adding? "); string theID = Console.ReadLine(); Console.Write("\n\nWhat is the Company Name? "); string theName = Console.ReadLine(); thisRow["CustomerID"] = theID; thisRow["CompanyName"] = theName; customerDataSet.Tables["Customers"].Rows.Add(thisRow); Console.WriteLine("# of rows after change: {0}", customerDataSet.Tables["Customers"].Rows.Count); Console.WriteLine("\n\n {0}\t{1}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}", " -----------", "--------------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"]); ++numberCustomers; } Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n", --numberCustomers); customerAdapter.Update(customerDataSet, "Customers"); customerConnection.Close(); } } }
// program_id ChartOfAccounts.cs // written_by don voils // date_written 11/14/2006 // description This program demonstrates the use of the reader // to read data from the GLAccounts table in the // expenses.mdb database. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace ChartOfAccounts {
file:///D|/1/final/BBL0129.html (2 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
class Program { static void Main(string[] args) { OleDbConnection GLAccountConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=expenses.mdb"); GLAccountConnection.Open(); OleDbCommand accessCommand = GLAccountConnection.CreateCommand(); accessCommand.CommandText = "SELECT GLAccountNumber, GLAccountName FROM GLAccounts"; OleDbDataReader AccountReader = accessCommand.ExecuteReader(); int numberAccounts = 0; Console.WriteLine("\t\tChart of Accounts"); Console.WriteLine(" {0} \t{1}", " GL Account Number", "GL Account Name"); Console.WriteLine("--------------------------------------------"); while (AccountReader.Read()) { ++numberAccounts; Console.WriteLine("{0,3} \t{1}\t\t{2}", numberAccounts, AccountReader["GLAccountNumber"], AccountReader["GLAccountName"]); } Console.WriteLine("\n\nThere are {0} GL Accounts.\n",numberAccounts); AccountReader.Close(); GLAccountConnection.Close(); } } }
// program_id CustomersAndOrders.cs // written_by don voils // date_written 11/18/2006 // description This program demonstrates how to view the data // in related tables of a database. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace CustomersAndOrders { class Program { static void Main(string[] args) { OleDbConnection thisConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter theAdapter = new OleDbDataAdapter( "SELECT CustomerID, CompanyName FROM Customers", thisConnection); OleDbCommandBuilder theBuilder = new OleDbCommandBuilder(theAdapter); DataSet thisDataSet = new DataSet(); OleDbDataAdapter customerAdapter = new OleDbDataAdapter( "SELECT * FROM Customers", thisConnection); OleDbDataAdapter ordersAdapter = new OleDbDataAdapter( "SELECT * FROM Orders", thisConnection);
file:///D|/1/final/BBL0129.html (3 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
customerAdapter.Fill(thisDataSet, "Customers"); ordersAdapter.Fill(thisDataSet, "Orders"); DataRelation customersandOrdersRelation = thisDataSet.Relations.Add("CustomerOrders", thisDataSet.Tables["Customers"].Columns["CustomerID"], thisDataSet.Tables["Orders"].Columns["CustomerID"]); int numberCustomers = 0; foreach (DataRow customerRow in thisDataSet.Tables["Customers"].Rows) { numberCustomers++; Console.WriteLine("\nCustomer ID: " + customerRow["CustomerID"] + " Company Name: " + customerRow["CompanyName"]); foreach (DataRow orderRow in customerRow.GetChildRows(customersandOrdersRelation)) { Console.WriteLine(" Orders: " + orderRow["OrderID"]); } if (numberCustomers == 10) { Console.WriteLine("\n\nPress the Enter key to continue."); Console.ReadKey(); Console.Clear(); numberCustomers = 0; } } thisConnection.Close(); Console.WriteLine("\n\nPress the Enter key to continue."); Console.ReadKey(); } } }
// program_id DataSetCustomers.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to view data // using a Data Set. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers4 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName, Phone FROM Customers", customerConnection); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers"); int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone");
file:///D|/1/final/BBL0129.html (4 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n Press any key to exit.\n", --numberCustomers); Console.ReadKey(); } } }
// program_id DeleteRowstoCustomers.cs // written_by Don Voils // date_written 11/18/2006 // description This program demonstrates how to delete records // from a database table data using a Data Set. // // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers4 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NorthwindAdd.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName, Phone FROM Customers", customerConnection); OleDbCommandBuilder tableBuilder = new OleDbCommandBuilder(customerAdapter); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers"); int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers,
file:///D|/1/final/BBL0129.html (5 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } DataColumn[] theKeys = new DataColumn[1]; theKeys[0] = customerDataSet.Tables["Customers"].Columns["CustomerID"]; customerDataSet.Tables["Customers"].PrimaryKey = theKeys; Console.Write("\nWhat is the Customer ID for the record you wish to remove? "); string theCustomerID = Console.ReadLine(); try { DataRow rowToDelete = customerDataSet.Tables["Customers"].Rows.Find(theCustomerID); if (rowToDelete != null) { Console.WriteLine("\n{0} is in the table.", theCustomerID); rowToDelete.Delete(); customerAdapter.Update(customerDataSet, "Customers"); Console.WriteLine("\nThat record has been deleted from the database.\n"); } else Console.WriteLine("\n{0} was not in the table.\n", theCustomerID); Console.WriteLine("Press any key to continue."); Console.ReadKey(); Console.Clear(); numberCustomers = 1; Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } } catch (Exception e) { Console.WriteLine("\nThat record may not be deleted. {0}", e.Message); } finally { customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n Press any key to exit.\n", --numberCustomers); Console.ReadKey(); } } } }
// program_id ExpenseLedger.cs
file:///D|/1/final/BBL0129.html (6 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
// written_by Don Voils // date_written 11/19/2006 // description This program along with the Access database: expenses.mdb // simulates an Expense ledger. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Data.OleDb; using System.Text; using System.Windows.Forms; namespace Expenses { public partial class Form1 : Form {
public Form1() { InitializeComponent(); txtGLAccountNumber.Focus(); } private void btnAddRecord_Click(object sender, EventArgs e) { OleDbConnection expensesConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=expenses.mdb"); OleDbDataAdapter expensesAdapter = new OleDbDataAdapter("SELECT GLAccountNumber,PayeeName,CheckNumber,CheckAmount,CheckDate FROM Checks", expensesConnection); OleDbCommandBuilder thisBuilder = new OleDbCommandBuilder(expensesAdapter); DataSet expensesDataSet = new DataSet(); expensesAdapter.Fill(expensesDataSet,"Checks"); DataRow thisRow = expensesDataSet.Tables["Checks"].NewRow(); thisRow["GLAccountNumber"] = String.Format("{0}",txtGLAccountNumber.Text); thisRow["PayeeName"] = String.Format("{0}",txtPayeeName.Text); thisRow["CheckDate"] = checkDate.Value; thisRow["CheckNumber"] = Int32.Parse(String.Format("{0}",txtCheckNumber.Text)); thisRow["CheckAmount"] = Convert.ToDouble(txtCheckAmount.Text); expensesDataSet.Tables["Checks"].Rows.Add(thisRow); expensesAdapter.Update(expensesDataSet,"Checks"); txtGLAccountNumber.Clear(); txtPayeeName.Clear(); txtCheckNumber.Clear(); txtCheckAmount.Clear(); txtGLAccountNumber.Focus(); expensesConnection.Close(); } } }
// program_id GLAccounts.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates // how to find a particular GL Account // in the database expenses.mdb GLAccounts // table. //
file:///D|/1/final/BBL0129.html (7 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { OleDbConnection GLAccountConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=expenses.mdb"); GLAccountConnection.Open(); OleDbCommand accessCommand = GLAccountConnection.CreateCommand();
accessCommand.CommandText = "SELECT GLAccountNumber, GLAccountName FROM GLAccounts"; OleDbDataReader GLAccountReader; char doAnother; int numberAccounts; do { Console.Clear(); GLAccountReader = accessCommand.ExecuteReader(); numberAccounts = 1; Console.Write("What is the GL Account Number? "); string theGLAccountNumber = Console.ReadLine(); Console.Clear(); bool isThere = false; Console.WriteLine("\n\n {0,-20}\t{1,-20}", "GL Account Number", "GL Account Name"); Console.WriteLine(" {0,-20}\t{1,-20}", "-----------------", "---------------"); while (GLAccountReader.Read()) { if (theGLAccountNumber == String.Format("{0}", GLAccountReader["GLAccountNumber"])) { Console.WriteLine("{0,3}{1,18}\t {2,20}", numberAccounts, GLAccountReader["GLAccountNumber"], GLAccountReader["GLAccountName"]); isThere = true; } ++numberAccounts; } if (!isThere) { Console.WriteLine("\n\nThat account number is not on file!"); } Console.WriteLine("\n\n All {0} of the GL Accounts have been checked.\n\n", --numberAccounts); Console.Write("\nWhat you like to search for another account? (Y/N) "); doAnother = Char.Parse(Console.ReadLine()); GLAccountReader.Close(); } while ((doAnother=='Y')||(doAnother=='y')); GLAccountConnection.Close(); Console.WriteLine("\n\nPress Enter to exit.\n"); Console.ReadLine(); } } }
file:///D|/1/final/BBL0129.html (8 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
// program_id ModifyCustomersInMemory.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to modify data // in memory using a Data Set. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers4 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName, Phone FROM Customers", customerConnection); OleDbCommandBuilder theBuilder = new OleDbCommandBuilder(customerAdapter); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers"); int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; }
Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n", --numberCustomers); Console.Write("What is the number of the customer you want to change the name? "); int customerRecord = Int16.Parse(Console.ReadLine()); customerRecord--; Console.WriteLine("\nThe current name is: {0}\n",customerDataSet.Tables["Customers"].Rows[customerRecord]["CompanyName"]); Console.Write("\nWhat do you want to change the name to? "); string newName = Console.ReadLine(); customerDataSet.Tables["Customers"].Rows[customerRecord]["CompanyName"] = newName; Console.Clear(); Console.WriteLine("The names are now: "); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------",
file:///D|/1/final/BBL0129.html (9 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
"--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } customerConnection.Close(); } } }
// program_id SelectCustomers2.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to view data // how to find a particular record. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers2 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); customerConnection.Open(); OleDbCommand accessCommand = customerConnection.CreateCommand(); accessCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers"; int numberCustomers = 1; Console.Write("What is the customer ID? "); string theCustomerID = Console.ReadLine(); Console.Clear(); OleDbDataReader customerReader = accessCommand.ExecuteReader(); Console.WriteLine("\n\n{0}\t{1}", " Customer ID", "Customer Name"); Console.WriteLine("{0}\t{1}", " -----------", "-------------"); while (customerReader.Read()) { if(theCustomerID == String.Format("{0}",customerReader["CustomerID"])) { Console.WriteLine("{0,3} {1}\t{2}",numberCustomers, customerReader["CustomerID"],customerReader["CompanyName"]); } ++numberCustomers; } customerReader.Close();
file:///D|/1/final/BBL0129.html (10 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n Press any key to exit.\n",--numberCustomers); Console.ReadKey(); } } }
// program_id SelectCustomers3.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to view data // how to find a particular record. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers3 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); customerConnection.Open(); OleDbCommand accessCommand = customerConnection.CreateCommand(); accessCommand.CommandText = "SELECT CustomerID, CompanyName, Phone FROM Customers"; int numberCustomers = 1; Console.Write("What is the Customer ID? "); string theCustomerNumber = Console.ReadLine(); Console.Clear(); OleDbDataReader customerReader = accessCommand.ExecuteReader(); Console.WriteLine("\n\n{0}\t{1}\t\t{2}", " Customer ID", "Customer Name","Phone"); Console.WriteLine("{0}\t{1}\t{2}", " -----------", "--------------------", "-------------"); while (customerReader.Read()) { if(theCustomerNumber == String.Format("{0}",customerReader["CustomerID"])) { Console.WriteLine("{0,3} {1}\t{2} \t\t{3}", numberCustomers, customerReader["CustomerID"], customerReader["CompanyName"], customerReader["Phone"]); } ++numberCustomers; } customerReader.Close(); customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n Press any key to exit.\n",--numberCustomers); Console.ReadKey(); }
file:///D|/1/final/BBL0129.html (11 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
} }
// program_id SelectCustomers.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to view data. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); customerConnection.Open(); OleDbCommand accessCommand = customerConnection.CreateCommand(); accessCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers"; int numberCustomers = 1; OleDbDataReader customerReader = accessCommand.ExecuteReader(); Console.WriteLine("{0}\t{1}", " Customer ID", "Customer Name"); Console.WriteLine("{0}\t{1}", " -----------", "-------------"); while (customerReader.Read()) { Console.WriteLine("{0,3} {1}\t{2}",numberCustomers, customerReader["CustomerID"], customerReader["CompanyName"]); ++numberCustomers; } customerReader.Close(); customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n Press any key to exit.",--numberCustomers); Console.ReadKey(); } } }
file:///D|/1/final/BBL0129.html (12 von 12) [01.12.2007 04:50:30]
List of Tables
List of Tables Lecture 1: Introduction to Business Programming Southern Warehousing Monthly Accounts Profit or Loss Statement Expense Ledger Sales Ledger
file:///D|/1/final/BBL0130.html [01.12.2007 04:50:31]