Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming and Visual C# 2008

Similar presentations


Presentation on theme: "Introduction to Programming and Visual C# 2008"— Presentation transcript:

1 Introduction to Programming and Visual C# 2008
Chapter 1 Introduction to Programming and Visual C# 2008

2 Chapter Objectives - 1 Describe the process of visual program design and development Explain the term object-oriented programming Explain the concepts of classes, objects, properties, methods, and events List and describe the three steps for writing a C# program Describe the various files that make up a C# project

3 Chapter Objectives - 2 Identify the elements in the Visual Studio environment Define design time, run time, and debug time Write, run, save, print, and modify your first C# program Identify syntax errors, run-time errors, and logic errors Look up C# topics in Help

4 Writing Windows Applications
Your C# programs will look and act like standard Windows programs Use tools to create: Labels Text boxes Buttons Radio buttons Picture box Check box Menu Bar Drop-down list List box Group box

5 Windows Graphical User Interface (GUI)
Windows GUI defines how elements look and function Windows are called forms Elements are called controls Add controls to your forms using the toolbox C# projects follow the object-oriented programming (OOP) technique GUI is pronounced "gooey".

6 Programming Languages— Procedural and Object Oriented
Procedural — Basic, C, Cobol, Fortran, PL/1, Pascal Program specifies exact sequence of operations Object Oriented Programming (OOP) — C#, Java, Visual Basic User controls the sequence User actions cause events to occur which trigger methods A method is a set of programming statements written by the programmer.

7 The Object Model Objects have properties, methods and events
An object is based on a class Objects (noun or thing) Forms, Controls Properties (adjectives) Name, Color, Size, Location Methods (verbs) Close, Show, Clear Events (occurs when user takes action) Click, KeyPress, Scroll, Close window Classes (template or blueprint) Contain definition of all available properties, methods and events OOP terminology is used throughout the text. Chapter 12 presents object-oriented programming in greater depth.

8 OOP Terminology Object.Property Object.Method SalesForm.Text
BillingForm.Show exitButton.Show SalesForm.Text is pronounced “sales form dot text”. The term members is used to refer to both properties and methods.

9 Object Model Analogy Class = automobile
Object = one individual automobile Object is an instance of the automobile class Properties = make, model, color, engine, number of doors Methods = start, speedup, slowdown, stop Events = arrive, crash An example of the color property would be yourAuto.Color = Blue An example a method would be yourAuto.Start An example of an event would be yourAuto.Crash

10 Microsoft’s Visual Studio 2008
.NET 3.5 Framework Environment that allows objects from different languages to operate together, standardizes references to data and objects .NET languages all compile (translate) to Microsoft Intermediate Language (MSIL) MSIL runs in the Common Language Runtime (CLR) Programming Languages Visual C#, Visual C++, Visual Basic C# Versions Express Edition, Standard Edition, Professional Edition, Team System Team System is available as four specialized versions for large enterprise application development. Professional or Team System Database versions should be used if advanced features of database management are needed. The trial version packaged with this textbook is the 180-day trial version of the Professional Edition. Express edition of C# is available for free download from The text is based on the Professional Edition.

11 Writing C# Programs – The Three-Step Process (Planning)
Design the user interface Sketch screens Show forms and all controls Name forms and objects on form Consult with user Plan the properties Plan the C# code Plan classes and methods Write pseudocode Actual C# code must follow the language syntax rules. Pseudocode is an English expression or comment that describes the action. For example, an event that occurs when the user clicks the Exit button would be written in Pseudocode as End the project or Quit.

12 Writing C# Programs – The Three-Step Process (Programming)
Define user interface Create forms and controls Set the properties Name each object and define its attributes Write the code Define the actions of the program Setting the properties of an object could include the contents of a label, the size of the text, the words that appear on a button or in the form’s title bar.

13 C# Application Files Solution file Project file Form files
A C# application is called a solution and can consist of one or more projects .sln extension Project file Describes project and lists files included .csproj extension Form files .cs, .Designer.cs, .resx extensions The Visual Studio environment creates several more files The solution (.sln) file is a file that holds information about the solution and the projects it contains. The project (.csproj) file describes the project and lists files that are included in the project. The .cs (C#) file holds the code methods that are written. The Designer.cs (C#) file is created by the Form Designer and holds the definition of the form and its controls. The resource file (.resx) is a text file that defines all the resources used by the form. The additional files created by the Visual Studio environment are: The solution user options (.suo) file stores information about the state of the IDE. The project user options (.csproj.user) file is a text file that holds IDE option settings. The Program.cs (C#) file contains automatically generated code that runs first when your application is executed.

14 The Visual Studio Environment
Integrated development environment (IDE) Includes various tools Form designer Editor for entering and modifying C# code Compiler Debugger Object Browser Help Form designer allows you to visually create a form. The compiler translates the C# statements into intermediate machine code. The debugger helps to locate and correct errors. The object browser allows you to view the available classes, objects, properties, methods and events.

15 Default Environment Settings
Visual Studio 2008 allows selection of default IDE profile Available with full version of Visual Studio Choose Visual C# Development Settings Text uses the Visual C# settings Settings can be saved for more than one language To switch between the settings for languages: Select Tools/Import and Export Settings Choose Reset all settings The first time you open the Visual Studio IDE, you must select the default environment settings for Visual C# development.

16 The New Project Dialog Select File/New Project
New Project Dialog Box Opens Select the Windows Forms Application template Deselect the check box for Create directory for solution, which creates an extra level of folders that are not needed for single-project solutions. If a Start Page opens, without an open project, you can close the Start Page by clicking on its Close button. (See Figure 1.4 in textbook) Select Visual C# Windows Enter the Project Name

17 The IDE Main Window Solution Explorer Toolbox Properties window Windows can be displayed or hidden from the View menu. The Visual Studio environment has a main window and various child windows. Main Document window Each window can be moved, resized, closed, or customized

18 The Toolbars Toolbar buttons are shortcuts
Each button’s command is also a menu selection Select View/Toolbars to display or hide a toolbar Three commonly used toolbars Standard Layout Text Editor

19 Document Window Use tabs to switch between open documents
Items in Document window Form Designer Code Editor Project Designer Database Designer Object Browser Close any document window using its Close button. Use Ctrl + Tab to switch to another open document in the Document window.

20 The Form Designer Design forms for user interface
Change size of form using sizing handles or selection border A new default form is added when a new C# application is started

21 The Solution Explorer and Properties Windows
Solution Explorer window Holds filenames for project files Lists classes referenced Holds name of solution (.sln) file Properties Window Used to set properties for objects in project Sort properties in the properties window alphabetically or by category using the buttons on the Properties window.

22 Toolbox Holds tools to place controls on form
Tools vary depending on edition of C# Sort tools in the toolbox by right-clicking on the toolbox and selecting Sort Items Alphabetically from the shortcut menu.

23 Help Help with specific tasks Selected Topic Help Search Filter
Help displays in a new window, independent of the Visual Studio IDE window. This allows you to have Help and the Document window open at the same time. Help Index Help Contents Help Favorites Index Results

24 Design Time, Run Time, Debug Time
Design user interface (forms) Write code Run Time Testing project Running project Debug Time Run-time errors Pause program execution The IDE window title bar displays (Running) or (Debugging) to indicate that a project is no longer in design time.

25 Writing Your First C# Project - 1
Run Visual Studio Start a New Project Select File/New/Project Visual C# and Windows must be selected for Project types Select Windows Forms Application for the template Enter Hello World as the project name Click the OK button If you are using Visual Studio Professional and this is the first time VS has been opened for this user, you need to select Visual C# Development Settings from the Choose Default Environment Settings dialog box (see Figure 1.3 in textbook).

26 Writing Your First C# Project - 2
Windows and Windows Forms Application have been selected and “HelloWorld” has been entered in the Name textbox.

27 Writing Your First C# Project - 3
Set Up Your Environment Click Window/Reset Window Layout, Click Yes Point to toolbox icon Pushpin icon toggles Auto Hide feature for toolbox Optional Tools/Options Options dialog box Startup under Environment At startup list Show empty environment After Clicking Yes when choosing Window/Reset Window Layout the IDE will match Figure 1.12 in the textbook. Clicking the pushpin icon pins the toolbox window open rather than allowing it to Auto Hide. You can show the Start Page at any time by selecting View/Start Page.

28 Writing Your First C# Project - 4
Plan the project Design the user interface Plan the properties Plan the code (Planning the properties and code have been done for the first sample project) Draw the sketch by hand and label the form and controls with the names you plan to give them.

29 Writing Your First C# Project - 5
Define the User Interface Set Up the Form Drag handle to resize form Place Controls on the Form Double-click the Label tool

30 Writing Your First C# Project - 6
Draw a button on the form Click the button tool and draw with the crosshair pointer Create a second button Double-click the Button tool in the toolbox Use snap lines to align all three controls Snap lines appear as you draw or move controls on the form and can help to align the controls. Click outside of a control to deselect it.

31 Writing Your First C# Project - 7
Controls Select, Delete, Move or Resize Select a control Click on it Delete a selected control Select control and press the Delete key Move a selected control Point inside control (not on a handle) and drag to a new location Resize a selected control Point to a resizing handle and drag to resize

32 Writing Your First C# Project - 8
Set Properties Press F4 key if Properties window is not displayed Click title bar of Properties window to make active window Click on control to change its properties Click Alphabetical button to sort properties Select Name property Enter Name for Control (used in code) Select AutoSize property Choose True or False Select Text property Change value for display on form Don’t confuse the Name property with the Text property. The Name property refers to the control in C# code. The Text property determines what the user will see on the form. C# sets both properties to the same value by default, it is easy to confuse them.

33 Writing Your First C# Project - 9
Lock the Controls When controls are in desired location, lock them in place Unlock controls by clicking again on Lock Controls on the context menu Right-click on the form and select Lock Controls Right-click to access the context menu, select Lock Controls. The Lock Controls menu item works like a toggle switch to lock and unlock controls. Context menus differ depending on the current operation and system setup. A button that is selected and locked

34 Writing Your First C# Project - 10
Set Button Properties button1 Name - displayButton Text - Display button2 Name – exitButton Text – Exit Always set the Name property of controls before writing code. This allows the method names to match the control names, saving confusion.

35 Writing Your First C# Project - 11
Change Properties of the Form Text property appears in the form’s title bar Set StartPosition property to CenterScreen Icon indicates that the form’s controls are locked The next slide describes changing the form’s name and file name. Form’s Text property appears in the title bar

36 Changing a Form’s Name You must change the name of the form’s file and the name of the class If you change the filename first, the IDE automatically changes the name of the class The reverse is not true See the next slide for a picture of the Properties window for the form.

37 HelloForm.cs Name of the form’s file File name Name of the form class
If you change the name of the form’s class in the properties window, you also must manually change the name of the file. It is much better to change the name of the file and allow the IDE to rename the form’s class to match.

38 Write Code C# Events While a project is running the user can perform actions, each of which causes an event to occur C# will execute a method when code has been written for an event C# ignores events for which no methods are written Some events, like clicking on a button, you care about. Some events, like moving the mouse and resizing the window, you do not care about.

39 C# Event Handlers Write C# code in methods
Each begins with the words private void Code in method is enclosed in braces { } C# names the event-handling method as the object name, an underscore (_) and the name of the event displayButton_Click Event-handling methods are also called event handlers.

40 C# Code Statements Comment statements Ending a statement
Sometimes called remarks Ending a statement Code statements are terminated by a semicolon (;) Assignment statements Executing a Method Methods always have parentheses Use this keyword to execute method of the current form Examples of methods are: helloButton.Hide(); messageLabel.Show();

41 The Comment Statement Comments or remarks are for project documentation Explain purpose of the program Provide identifying information Non-executable statements within the code Automatically colored green by the editor Single-line comments begin with two slashes // Display a message to the user. Multiline comments begin with /* and end with */ /* First line ... Last line */

42 Ending a Statement Most C# statements end with a semicolon (;)
A statement can appear on multiple lines The semicolon determines the end of the statement Comments and a few other C# statements do not end with a semicolon A later chapter will discuss the C# statements that do not end with a semicolon.

43 The Assignment Statement
Assigns a value to a property or variable Operates from right to left The value on the right side of the equal sign is assigned to the property on the left side of the equal sign Enclose text (a literal) in quotation marks (" ") Chapter 3 discusses variables. Do not enclose a numeric value in quotation marks. Do not use quotation marks around the terms true and false which are special key terms in C#. messageLabel.Text = "Hello World";

44 Ending a Program by Executing a Method
To execute a method of an object, write: Object.Method(); Methods are always followed by parentheses Can help distinguish methods from properties To execute a method of the current form use the this keyword this.Close(); this.Close() is used to end a program in the event-handling method for an Exit button or menu choice Properties never have parentheses. The keyword this refers to the current object. It can be omitted since a method without an object reference defaults to the current object.

45 Code Event-Handling Methods - 1
Double-click the Display button The Editor window opens The header line for the method is in place The insertion point appears inside the opening and closing braces private void displayButton_Click(object sender, EventArgs e) { | }

46 Code Event-Handling Methods - 2
Editor tab Form Designer tab Comment statement Assignment statement Allow the Editor and IntelliSense to help. If IntelliSense does not pop up, likely the name of the control is misspelled. An asterisk on the tab at the top of the window indicates there are unsaved changes. Execute the Close method to end the program

47 Run the Project - 1 Use one of three techniques to run
IDE Title bar indicates program is in run time Use one of three techniques to run Open the Debug menu / Start Debugging Press the Start Debugging toolbar button Press F5, the keyboard shortcut Form for the running application Editor and Form Designer locked tabs

48 Run the Project - 2 Click the Display button
“Hello World” message appears in the label Click the Exit button to end the project and return to Design time

49 Save Your Work File menu/Save All
Saves the current form, project and solution files Click Save All toolbar button to quickly save all files File menu/Close Solution If file has not been saved since last change, prompt to save appears By default Visual Studio saves files automatically to a temporary location each time you compile or run the project. NOTE: Do not try to save a modified version of a project by giving the project a new name. See Appendix C on how to move or rename a project.

50 Open the Project Three ways to open a project File menu/Open Project
Browse to find .sln file (small “9” as part of file’s icon) Choose project from File/Recent Projects menu Start Page (if available) View/Other Windows/Start Page

51 Modify the Project Modify the project by making changes to the design (including properties) and/or the code (including comments) Double-click on a button to open the editor Editor will open in corresponding click event code Change the Font property of the form and this will set the default Font for all objects on the form. Comments – Always begin each method with comments that tell the purpose of the method. Properties button Click to expand Font list Settings box

52 Print the Code Print View Event Handlers Open Editor window File/Print
Select a button control Click Events button (lightning bolt) on Properties window Double-click on the event name Code Editor window opens inside template for event handler The Print command is disabled unless code is displayed and the window is selected.

53 Automatically Generated Code
Using Statements Provide references to classes from the language library System.Windows.Forms Allows program to refer to all Windows controls Namespace Statement .NET Framework requires every program component to have a namespace Class Statement A new class can inherit from another class Without the using statement, the complete reference would have to be used for each control. Using System.Windows.Forms allows messageLabel to be used in code. Without the using statement the same label would have to be referred to as System.Windows.Forms.Label.messageLabel. Classes will be discussed in detail later in the textbook.

54 Finding and Fixing Errors
Syntax errors Breaking the rules of the language Editor finds most, compiler reports remainder Editor identifies syntax errors with a red squiggly line Run-time errors or exceptions Program halts due to statements that cannot execute For example, impossible arithmetic operations Logic errors Program runs but produces incorrect results Carefully proof output to make sure it is correct Computations, text and spacing Language rules include punctuation, format and spelling. Jump to an error line by double-clicking on it in the Error List window. In Chapter 3 there is information on how to catch exceptions so that the program does not halt when an error occurs.

55 Project Debugging Program errors are bugs
Editor highlights syntax and run-time errors Programmer must locate logic errors C# allows edit-and-continue Fix error and press F5 or Debug/Continue Clean Compile No errors during the compile process If you get the message, “There were build errors. Continue?” click No. Yes allows the last cleanly compiled version to run rather than the current version.

56 Modifying an Event Handler -1
Deleting an Event Handler Select form or control Click Events button in Properties window Select and delete name of the method Select the event Delete the method name

57 Modifying an Event Handler - 2
Renaming a Control Change the name of the control in the design window Switch to Editor window Right-click name of event-handling method Select Refractor/Rename Enter new name in Rename dialog box Click Apply in Preview Changes dialog box Refractor changes all references to the old name to the new name including the line in the Designer.cs file that assigns the event handler.

58 Naming Rules and Conventions for Objects
Follow C# rules for naming objects, methods and variables Good programmers follow naming rules and conventions Most programming shops have standards that must be followed When programmers consistently follow standards, programs are easier to read and to maintain, by both the original programmer and by others You should have a set of naming standards and always follow them.

59 The Naming Rules Name must begin with a letter or an underscore
Name can contain letters, digits, and underscores Name cannot include a space, punctuation mark or be a reserved word Names are case sensitive exitbutton, ExitButton and exitButton refer to three different objects Reserve words include Close or button. A name can contain a reserve word as part of a longer name. For example, exitButton and closeButton are legal.

60 The Naming Conventions -1
Follow standard naming conventions Use camel casing Begin name with lowercase character Capitalize each additional word in name Use meaningful names, indicate purpose of object Append full name of control’s class Examples messageLabel, exitButton, discountRateLabel

61 The Naming Conventions - 2
Do not keep C# default names Exception is labels that never change during execution Use pascal casing to name forms and classes Capitalize first letter of name and first letter of all other words in name Examples HelloForm, MainForm, AboutForm

62 Visual Studio Help Installing and Running MSDN Viewing Help Topics
Can be run from a hard drive or online Viewing Help Topics Help window opens on top of IDE window Filter by C# and either Express or Professional Edition Context-Sensitive Help Select a C# object (i.e. form or control) Place insertion point in a word in the editor Press F1 A good way to start using Help is to view the topics that demonstrate how to look up topics in Help. Display context-sensitive Help about the environment by clicking in an area of the screen and pressing Shift + F1.


Download ppt "Introduction to Programming and Visual C# 2008"

Similar presentations


Ads by Google