Open Library is a project of the Internet Archive , a c 3 non-profit. This edition doesn't have a description yet. Can you add one? Previews available in: English. Add another edition? Copy and paste this code into your Wikipedia page.
Need help? Donate this book to the Internet Archive library. If you own this book, you can mail it to our address below. Not in Library. Want to Read. Delete Note Save Note. Download for print-disabled. Check nearby libraries Library. Share this book Facebook. December 20, History. An edition of Programming in Visual C Written in English. Then you will use the toolbox to add the various elements, called controls.
The projects that you will write follow a programming technique called object-oriented programming OOP. Each was developed to solve a particular type of problem.
That is, the program specifies the exact sequence of all operations. Program logic determines the next instruction to execute in response to conditions and user requests. In the OOP model, programs are no longer procedural. They do not follow a sequential logic. You, as the programmer, do not take control and determine the sequence of execution. Instead, the user can press keys and click various buttons and boxes in a window.
Each user action can cause an event to occur, which triggers a method a set of programming statements that you have written. For example, the user clicks on a button labeled Calculate. Each object is based on a class. Objects Think of an object as a thing, or a noun. Examples of objects are forms and controls. Forms are the windows and dialog boxes you place on the screen; controls are the components you place inside a form, such as text boxes, buttons, and list boxes.
Properties Properties tell something about or control the behavior of an object such as its name, color, size, or location. You can think of properties as adjectives that describe objects. When you refer to a property, you first name the object, add a period, and then name the property.
Methods Actions associated with objects are called methods. Methods are the verbs of object-oriented programming. Some typical methods are Close, Show, and Clear. Each of the predefined objects has a set of methods that you can use. You will learn to write additional methods to perform actions in your programs.
You refer to methods as Object. For example, a Show method can apply to different objects: BillingForm. Show shows the form object called BillingForm; exitButton.
Show shows the button object called exitButton. Events You can write methods that execute when a particular event occurs. An event occurs when the user takes an action such as clicking a button, pressing a key, scrolling, or closing a window. Events also can be triggered by actions of other objects, such as repainting a form or a timer reaching a preset point. Classes A class is a template or blueprint used to create a new object.
Classes contain the definition of all available properties, methods, and events. Each time that you create a new object, it must be based on a class. For example, you may decide to place three buttons on your form. Each button is based on the Button class and is considered one object, called an instance of the class. Each button or instance has its own set of properties, methods, and events.
An Analogy If the concepts of classes, objects, properties, methods, and events are still a little unclear, maybe an analogy will help. Consider an Automobile class. When TIP The term members is used to refer to both properties and methods. Introduction to Programming and Visual C E R Text 1 we say automobile, we are not referring to a particular auto, but we know that an automobile has a make and model, a color, an engine, and a number of doors.
These elements are the properties of the Automobile class. Each individual auto is an object, or an instance of the Automobile class. Each Automobile object has its own settings for the available properties. For example, each Automobile object has a Color property, such as myAuto. To refer to the methods of a specific object of the class, use myAuto. Start and yourAuto. The events of an Automobile class could be Arrive or Crash. In a C program, you write event-handling methods that specify the actions you want to take when a particular event occurs for an object.
For example, you might write a method to handle the yourAuto. Crash event. Note: Chapter 12 presents object-oriented programming in greater depth. NET 3. The Framework provides for easier development of Web-based and Windows-based applications, allows objects from different languages to operate together, and standardizes how the languages refer to data and objects.
Several third-party vendors have produced versions of other programming languages to run in the. NET Framework, including. C Microsoft C is a part of Visual Studio. You also can purchase C by itself without the other languages but with the. C is available in an Express Edition, a Standard Edition, a Professional Edition, and four specialized versions of Team System Editions for large enterprise application development.
You can find a matrix showing the features of each edition in Help. Anyone planning to do professional application development that includes the advanced features of database management should use the Professional Edition or the Team System Database version. The full Professional Edition is available to educational institutions through the Microsoft Academic Alliance program and is the best possible deal.
When a campus department purchases the Academic Alliance, the school can install Visual Studio on all classroom and lab computers and provide the software to all students and faculty at no additional charge. This text is based on the Professional Edition of Visual Studio , the current version.
You cannot run the projects in this text in any earlier version of C. Writing C Programs When you write a C application, you follow a three-step process for planning the project and then repeat the three-step process for creating the project. The three steps involve setting up the user interface, defining the properties, and then creating the code. The Three-Step Process Planning 1. Design the user interface. When you plan the user interface, you draw a sketch of the screens the user will see when running your project.
On your sketch, show the forms and all the controls that you plan to use. Indicate the names that you plan to give the form and each of the objects on the form. Refer to Figure 1.
Before you proceed with any more steps, consult with your user and make sure that you both agree on the look and feel of the project.
Plan the properties. For each object, write down the properties that you plan to set or change during the design of the form. Plan the C code. In this step you plan the classes and methods that will execute when your project runs. You will determine which events require action to be taken and then make a step-by-step plan for those actions. Later, when you actually write the C code, you must follow the language syntax rules. But during the planning stage, you will write out the actions using pseudocode, which is an English expression or comment that describes the action.
For example, you must plan for the event that occurs when the user clicks on the Exit button. The pseudocode for the event could be End the project or Quit. Programming After you have completed the planning steps and have approval from your user, you are ready to begin the actual construction of the project.
Use the same three-step process that you used for planning. Define the user interface. When you define the user interface, you create the forms and controls that you designed in the planning stage. Think of this step as defining the objects you will use in your application. Set the properties. You might think of this step as describing each object. Write the code. You will use C programming statements called C code to carry out the actions needed by your program.
You will be surprised and pleased by how few statements you need to create a powerful Windows program. You can think of this third step as defining the actions of your program. C Application Files A C application, called a solution, can consist of one or more projects.
Each project can contain one or more form files. Starting in Chapter 6, your projects will contain multiple forms and additional files. A text file that holds information about the solution and the projects it contains. This is the primary file for the solution—the one that you open to work on or run your project.
Stores information about the state of the integrated development environment IDE so that all customizations can be restored each time you open the solution.
This is a text file that you can open in any editor. Warning: You should not modify this file unless you are using the editor in the Visual Studio environment. You should not modify this file directly, but instead make changes in the Designer and allow it to update the file. This text file defines all resources used by the form, including strings of text, numbers, and any graphics. This text file holds IDE option settings so that the next time you open the project, all customizations will be restored.
Note: You can display file extensions. Deselect the check box for Hide extensions for known file types. If you do not display the extensions, you can identify the file types by their icons. After you run your project, you will find several more files created by the system.
The only file that you open directly is the. The IDE consists of various tools, including a form designer, which allows you to visually create a form; an editor, for entering and modifying program code; a compiler, for translating the C statements into the intermediate machine code; a debugger, to help locate and correct program errors; an object browser, to view the available classes, objects, properties, methods, and events; and a Help facility.
In versions of Visual Studio prior to. Default Environment Settings The full version of Visual Studio provides an option that allows the programmer to select the default profile for the IDE. This text uses the Visual C settings. Note: If you plan to develop in more than one language, such as VB and C , you can save each group of settings and switch back and forth between the two.
In the step-by-step exercise later in this chapter, you will learn to reset the IDE layout to its default view. The contents of the Start Page vary, depending on whether you are connected to the Internet. Microsoft has included links that can be updated, so you may find new and interesting information on the Start Page each time you open it.
You can open an existing project or begin a new project using the Start Page or the File menu. The examples in this text use the menus.
In the New Project dialog, you may need to expand the node for Other Languages, depending on your installation. You also give the project a name in this dialog. Deselect the check box for Create directory for solution, which creates an extra level of folders for our single-project solutions. You can close the Start Page by clicking on its Close button. Note that each window can be moved, resized, opened, closed, and customized. Some windows have tabs that allow you to display different contents.
Your screen may not look exactly like Figure 1. The Designer and Editor windows are generally displayed in tabs in the center of the screen the Document window , and the various tool windows are docked along the edges and bottom of the IDE, but the locations and the docking behavior are all customizable.
You can display or hide the various windows from the View menu. Figure The Visual Studio environment. Each window can be moved, resized, closed, or customized.
The Toolbars You can use the buttons on the toolbars as shortcuts for frequently used operations. Each button represents a command that also can be selected from a menu. You can display or hide each of the toolbars: a.
Notice the tabs across the top of the window, which allow you to switch between open documents. You can switch from one tab to another, or close any of the documents using its Close button.
In Figure 1. The Solution Explorer Window The Solution Explorer window holds the filenames for the files included in your project and a list of the classes it references. The Properties Window You use the Properties window to set the properties for the objects in your project.
TIP You can sort the properties in the window either alphabetically or by categories. Use the buttons on the Properties window. You may have more or different tools in your toolbox, depending on the edition of C you are using Express, Standard, Professional, or Team System. Figure Common controls for Windows Forms 1. Your toolbox may have more or fewer tools, depending on the edition you are using. TIP You can sort the tools in the toolbox: Right-click the toolbox and select Sort Items Alphabetically from the context menu the shortcut menu.
Help includes the entire reference manual, as well as many coding examples. When you make a selection from the Help menu, the requested item appears in a new window that floats on top of the IDE window Figure 1. While you are designing the user interface and writing code, you are in design time. When you are testing and running your project, you are in run time. If you get a run-time error or pause program execution, you are in debug time. The IDE window title bar indicates Running or Debugging to indicate that a project is no longer in design time.
The label does not appear until the button is pressed. You also may need to customize your workspace. Run Visual Studio These instructions assume that Visual Studio is installed in the default location. If you are running in a classroom or lab, the program may be installed in an alternate location, such as directly on the desktop. Locate Microsoft Visual Studio Visual Studio will start and display the Start Page refer to Figure 1. The new project opens Figure 1. At this point, your project is stored in a temporary directory.
You can specify a new location for the project later when you save it. Figure Enter the name for the new project.
Set Up Your Environment In this section, you will customize the environment. For more information on customizing windows, floating and docking windows, and altering the location and contents of the various windows, see Appendix C. The IDE should now match Figure 1. Point to the icon for the toolbox at the left of the IDE window. The Toolbox window pops open. Notice the pushpin icon at the top of the window Figure 1. Click the Auto Hide pushpin icon for the Toolbox window; the toolbox will remain open.
Your screen may look significantly different from the figure since the environment can be customized. In the Options dialog box, select Startup under Environment, drop down the At startup list and select Show empty environment Figure 1.
This selection causes the Start Page to not appear and will make your environment match the illustrations in this text. Set this option so that the Start Page does not appear at startup Plan the Project The first step in planning is to design the user interface. You will refer to the sketch as you create the project. Figure A sketch of the Hello World form for planning. Introduction to Programming and Visual C E R Text 19 1 The next two steps, planning the properties and the code, have already been done for this first sample project.
You will be given the values in the steps that follow. Define the User Interface Set Up the Form Notice that the new form in the Document window has all the standard Windows features, such as a title bar, maximize and minimize buttons, and a Close button. The handles disappear as you drag the corner of the form.
Drag handle to enlarge form Place Controls on the Form You are going to place three controls on the form: a label and two buttons. Drag the label to the desired location Figure 1.
As long as the label is selected, you can press the Delete key to delete it, or drag it to a new location. You can tell that a label is selected; it has a dotted border, as shown in Figure 1. Draw a button on the form: Click on the Button tool in the toolbox, position the crosshair pointer for one corner of the button, and drag to the diagonally opposite corner Figure 1. Double-click the Label tool Figure 1.
The blue snap lines help to align controls. Snap line Draw the Button control using the crosshair pointer resizing handles. The blue lines that appear are called snap lines, which can help you align your controls. While a control is selected, you can delete it or move it. If it has resizing handles, you also can resize it. Refer to Table 1. Click outside of a control to deselect it. Delete a control Select the control and then press the Delete key on the keyboard.
Move a control Select the control, point inside the control not on a handle , press the mouse button, and drag it to a new location. Note that the default format for labels does not allow resizing. A new button of the default size will appear on top of the last-drawn control Figure 1. The new button appears on top of the previously selected control. Select each control and move and resize the controls as necessary.
Make the two buttons the same size and line them up. Use the snap lines to help with the size and alignment. Note that you can move but not resize the label. At this point you have designed the user interface and are ready to set the properties. Click on the title bar of the Properties window to make it the active window Figure 1. TIP If no control is selected when you double-click a tool, the new control is added to the upper-left corner of the form.
Introduction to Programming and Visual C E R 23 1 Notice that the Object box at the top of the Properties window is showing label1 the name of the object and System. Label as the class of the object. The actual class is Label; System. Forms is called the namespace, or the hierarchy used to locate the class.
In the Properties window, click on the Alphabetical button to make sure the properties are sorted in alphabetic order. Then select the Name property, which appears near the top of the list. Click on Name and notice that the Settings box shows label1, the default name of the label Figure 1. Click on the Name property to change the value in the Settings box. See Figure 1. Drop down the list and make your selection from the possible values True or False, in this case.
Click on the Text property to select it. Scroll the Properties list if necessary. The Text property of a control determines what will be displayed on the form. Because nothing should display when the program begins, you must delete the value of the Text property as described in the next two steps. Double-click on label1 in the Settings box; the entry should appear selected highlighted.
Then press Enter and notice that the label on the form appears empty. Changes do not appear until you press Enter or move to another property or control. As an alternate technique, you can double-click on the property name, which automatically selects the entry in the Settings box.
Then you can press the Delete key or just begin typing to change the entry. All you see is a very small selection border Figure 1. If you need to select the label after deselecting it, you can click in the approximate spot on the form or use the Properties window: Drop down the Object list at the top of the window; you can see a list of all controls on the form and can make a selection Figure 1.
You will use the Name property to refer to the control in your C code. The Text property determines what the user will see on the form. C sets both of these properties to the same value by default and it is easy to confuse them. Label is empty and selected Text deleted from the Settings box Figure 1. On the context menu, select Lock Controls Figure 1.
When your controls are locked, a selected control has a small lock icon in the upper-left corner instead of resizing handles Figure 1. Note: You can unlock the controls at any time if you wish to redesign the form. Just click again on Lock Controls on the context menu to deselect it. Remember that context menus differ depending on the current operation and system setup.
The Object box should show the name button1 and class System. Button of the button Figure 1. If you should double-click and code appears in the Document window, simply click on the Form1. Although the project would work fine without this step, we prefer to give this button a meaningful name, rather than use button1, its default name. This step changes the words that appear on top of the button. Form as its class.
The Text property of a form determines the text that appears in the title bar. Your screen should now look like Figure 1. STEP 3: In the Properties window, click on the StartPosition property and notice the arrow on the property setting, indicating a drop-down list. Drop down the list and select CenterScreen. This will make your form appear in the center of the screen when the program runs.
Press Enter when finished and click Yes on the confirmation dialog box. This changes the name of the file that saves to disk Figure 1. You can change the filename in the Properties window or the Solution Explorer. Each action by the user causes an event to occur in your C project. Some events like clicking on a button you care about, and some events like moving the mouse and resizing the window you do not care about. If you write code for a particular event, then C will respond to the event and automatically execute your method.
C ignores events for which no methods are written. C Event Handlers You write code in C in methods. C automatically names your event-handling methods also called event handlers. You also will execute a method of an object. The Comment Statement Comment statements, sometimes called remarks, are used for project documentation only. The purpose of comments is to make the project more readable and understandable by the people who read it. Good programming practices dictate that programmers include comments to clarify their projects.
Every method should begin with a comment that describes its purpose. In addition, it is a good idea to place comments within the logic of a project, especially if the purpose of any statements might be unclear. C comments begin with slashes. Most of the time, your comments will be on a separate line. You also can add slashes and a comment to the right end of a line of code. The enclosing symbols can be on lines by themselves or on existing lines. As you type additional lines between the beginning and ending symbols, the editor adds an asterisk at the start of each line, indicating that it is a comment line.
Comments and a few other statements which you will learn about later do not end with a semicolon. A C statement may extend over multiple lines; the semicolon indicates that the statement is complete. The Assignment Statement The assignment statement assigns a value to a property or variable you learn about variables in Chapter 3.
Assignment statements operate from right to left; that is, the value that appears on the right side of the equal sign is assigned to the property named on the left of the equal sign. Text is replaced by Hello World. This convention allows you to type any combination of alpha and numeric characters.
If the value is numeric, do not enclose it in quotation marks. And do not place quotation marks around the terms true and false, which C recognizes as special key terms. Method ; Notice that methods always have parentheses. Examples helloButton. Hide ; messageLabel. And the method that closes the form and terminates the project execution is Close. Close ; In most cases, you will include this.
Close in the event-handling method for an Exit button or an Exit menu choice. Note: Remember, the keyword this refers to the current object. You can omit this since a method without an object reference defaults to the current object. The Visual Studio editor opens with the header line of your method already in place, with the insertion point indented inside the opening and closing braces Figure 1.
STEP 3: Notice that the editor automatically displays comments in green unless you or someone else has changed the color with an Environment option. Follow good coding conventions and indent all lines between the opening and closing braces. The smart editor attempts to help you follow this convention. Also, always leave a blank line after the comments at the top of a method. Press Enter twice and then type this assignment statement: messageLabel.
When several items match the first letter, you can type additional characters until you get a match, or use your keyboard down arrow or the mouse to highlight the correct item. To accept the correct item when it is highlighted, press the punctuation character that should follow the item, such as the period, spacebar, equal sign, semicolon, Tab key, or Enter key, or double-click the item with your mouse.
Select the correct item from the list and press the period, spacebar, semicolon, Tab key, or Enter key to accept the text. TIP Accept an entry from the IntelliSense popup list by typing the punctuation that follows the entry, by pressing the spacebar, the Tab key, or the Enter key.
You also can scroll the list and select with your mouse. Compare your screen to Figure 1. Figure Editor tab 1. STEP 2: Type this comment: help you. If the IntelliSense list does not pop up, likely you misspelled the name of the control. Notice that an asterisk appears on the tab at the top of the window, indicating that there are unsaved changes in the file.
Use one of these three techniques: 1. Open the Debug menu and choose Start Debugging. Press the Start Debugging button on the toolbar. Press F5, the shortcut key for the Start Debugging command.
You must correct any errors and restart the program. If all went well, the form appears and the Visual Studio title bar now indicates that you are in run time Figure 1. TIP If your form disappears during run time, click its button on the Windows task bar. IDE title bar indicates that the program is in run time Running program, Editor tab is locked Running program, Form Designer tab locked Form for the running application 1. Introduction to Programming and Visual C Figure 1. Your project terminates, and you return to design time.
Save Your Work Of course, you must always save your work often. Except for a very small project such as this one, you will usually save your work as you go along. After you have performed a save to a different location, files are automatically resaved each time you compile or run.
You also can save the files as you work. This option will save the current form, project, and solution files. Note: When saving a project, do not attempt to save a modified version by giving the project a new name.
If you want to move or rename the project, it must be closed. See Appendix C for help. Open the Project Now is the time to test your save operation by opening the project from disk. Remember that the file to open is the. If you do not see your form on the screen, check the Solution Explorer window—it should say HelloWorld for the project. Select the icon for your form: HelloForm. You can double-click the icon or single-click and click on the View Designer button at the top of the Solution Explorer Figure 1.
If your controls are currently locked, select Lock Controls to unlock the controls so that you can make changes. STEP 2: Drop down the Object list at the top of the Properties window and select messageLabel, which will make the label appear selected. The Font property is actually a Font object that has a number of properties.
To see the Font properties, click on the small plus sign on the left Figure 1. You also can display the Font dialog box and make changes there. Click on the View Code button to display the code in the editor. Click to expand the Font list Figure 1. Select 12 point if it is available. Click OK to close the Font dialog box. Select the TextAlign property.
The Properties button that appears with the down-pointing arrow indicates a drop-down list of choices. Drop down the list Figure 1. You can resize the form if necessary. Note: You do not need to rename this label because it will never be referred to in the code. TIP When you change a property from its default value, the property name appears bolded; you can scan down the property list and easily identify the properties that are changed from their default value.
Select 12 point Figure 1. Properties button Select MiddleCenter alignment Figure 1. TIP You can change the Font property of the form, which sets the default Font for all objects on the form. When AutoSize is set to True the default , the label resizes automatically to accommodate the Text property, which can be an advantage when the text or font size may change. However, if you plan to delete the Text property, as you did for messageLabel, the label resizes to such a tiny size that it is difficult to see.
Any time that you want to set the size of a label yourself, change the AutoSize property to False. This setting also allows you to create taller labels that allow a long Text property to wrap to multiple lines. If you set the Text property to a very long value when AutoSize is set to True, the label will resize only to the edge of the form and cut off any excess text, but if AutoSize is set to False and the label has been resized to a taller height, the long Text property will wrap. Move and resize the buttons as necessary, referring to Figure 1.
You can paste multiple times to create multiple controls. Lock the Controls STEP 1: When you are satisfied with the placement of the controls on the form, display the context menu and select Lock Controls again.
STEP 2: Run your project again. Try clicking on the English button and the Spanish button. Add Comments Good documentation guidelines require some more comments in the project. Always begin each method with comments that tell the purpose of the method. In addition, each project file needs identifying comments at the top.
Make sure that you have an insertion point; if the entire first line is selected, press the left arrow to set the insertion point. Press Enter to create a blank line. Move the insertion point up to the blank line and type the following comments, one per line Figure 1. This project will display a "Hello World" message in two different languages. Test each language button multiple times; then click the Exit button. Click OK. View Event Handlers You also can get to the event-handling methods for a control using the Properties window in design mode.
With a button control selected, click on the Events button lightning bolt in the Properties window; all of the events for that control display Figure 1. When you double-click on the event, the editor takes you to the method in the code window. To write an event-handling method for any of the available events of a control, double-click the event name. You will be transferred to the Code Editor window with the insertion point inside the template for the new event handler.
You also can click in any event name in the Properties window and then drop down a list of all previously written methods and select a method to assign as the event handler. Any event handlers that are already written appear in bold. Doubleclick an event to jump to the Editor window inside the event handler for that method, or drop down the list to select a method to assign as the handler for the event. An explanation of some of the features of the code follows the listing. Generic; System.
ComponentModel; System. Data; System. Drawing; System. Linq; System. Text; System. The IDE adds a group of statements by default and sets up the files for the project to accommodate the majority of applications. Later, when your programs include database tables, you will have to write additional using statements.
The Using Statements The using statements appear at the top of the file after the comments that you wrote. Using statements provide references to standard groups of classes from the language library. For example, the statement using System.
Forms; allows your program to refer to all of the Windows controls that appear in the toolbox. Without the using statement, each time that you wanted to refer to a Label control, for example, you would have to specify the complete reference: System. Instead, in the program with the using statement, you can just refer to messageLabel. The Namespace Statement As mentioned earlier, a namespace provides a way to refer to programming components by location or organization.
You can think of a namespace as similar to a telephone area code: In any one area code, a single phone number can appear only once, but that same phone number can appear in any number of other area codes. Using the. NET Framework, every program component is required to have a namespace. The default namespace is the name of your solution, but you can use a different name if you wish.
Payroll, for example. In Visual Studio, one solution can contain multiple projects. All of the solutions in this text contain only one project, so you can think of a solution and a project as being equal. The Class Statement In object-oriented programming, code is organized into classes. A new class can be based on inherit from another class, which gives the new class all of the properties and methods of the original class the base class.
When you create a new form, you declare a new class HelloForm in the earlier example. The new class inherits from the Form base class, which makes your new form behave like a standard form, with a title bar, maximize and minimize buttons, and resizable borders, among other behaviors. A class may be split into multiple files. The automatically generated statement public partial class HelloForm : Form means that this is a new class called HelloForm that inherits from the Form class.
The new class is a partial class, so another file can exist that also contains statements that are part of the HelloForm class. You will learn more about classes and files in later chapters. Finding and Fixing Errors You already may have seen some errors as you entered the first sample project. Programming errors come in three varieties: syntax errors, run-time errors, and logic errors.
Fortunately, the smart editor finds most syntax errors and even corrects many of them for you. The syntax errors that the editor cannot identify are found and reported by the compiler as it attempts to convert the code into intermediate machine language.
A compiler-reported syntax error may be referred to as a compile error. The editor identifies syntax errors as you move off the offending line.
A red squiggly line appears under the part of the line that the editor cannot interpret. You can view the error message by pausing the mouse pointer over the error, which pops up a box that describes the error Figure 1. You also can display an Error List window, which appears at the bottom of the Editor window and shows all error messages along with the line number of the statement that caused the error. You can display line numbers on the source code Figure 1. Figure You can display the Error List window and line numbers in the source code to help locate the error lines.
The quickest way to jump to an error line is to point to a message in the Error List window and double-click. The line in error will display in the Editor window with the error highlighted Figure 1.
If a syntax error is found by the compiler, you will see the dialog box shown in Figure 1. Click No and return to the editor, correct your errors, and run the program again. Run-Time Errors If your project halts during execution, it is called a run-time error or an exception. C displays a dialog box and highlights the statement causing the problem.
Statements that cannot execute correctly cause run-time errors. The statements are correctly formed C statements that pass the syntax checking; however, the statements fail to execute due to some serious issue. You can cause 1. Double-click anywhere on this line to jump to the error Figure 1. Click No to return to the editor and correct the error. In Chapter 3 you will learn to catch exceptions so that the program does not come to a halt when an error occurs.
Logic Errors When your program contains logic errors, the program runs but produces incorrect results. Perhaps the results of a calculation are incorrect or the wrong text appears or the text is okay but appears in the wrong location.
Beginning programmers often overlook their logic errors. If the project runs, it must be right—right? All too often, that statement is not correct. You may need to use a calculator to check the output. Check all aspects of the project output: computations, text, and spacing. If the contents of the two methods were switched, the program would work, but the results would be incorrect. Finding and fixing these bugs is called debugging.
For syntax errors and run-time errors, your job is easier. C displays the Editor window with the offending line highlighted. However, you must identify and locate logic errors yourself. C also includes a very popular feature: edit-and-continue.
You also can correct the error and restart from the beginning. The debugging tools are covered in Chapter 4. Your goal is to have no errors during the compile process: a clean compile. If you say Yes, the last cleanly compiled version runs rather than the current version.
Modifying an Event Handler When you double-click a Button control to begin writing an event-handling method for the Click event, several things happen. As an example, say that you 1. But behind the scenes, VS also adds a line to the hidden FormName. Deleting an Event Handler Assume that you have double-clicked the form called Form1 and now have an extra event handler that you do not want.
You can delete the line of code that it takes you to, which, in this example, is this. EventHandler this. First, make sure to select the form or control that has the unwanted event handler assigned; then click on the Events button in the Properties window Figure 1.
You can select and delete the name of the method, which removes the assignment statement from the Designer. Renaming a Control You can receive an error if you rename a control after you write the code for its event. For this example, assume that you add a button that is originally called button1. This scenario occurs quite often, especially with beginning programmers. If you simply change the Name property of button1 to exitButton in the Form Designer, your program will still run without an error message.
If you check the events in the Properties window, you will see why Figure 1. One solution is to just cut-and-paste the code from the old method to the new one. Button is renamed Event handler still has the old name Another way to change the name of an event handler is to use refactoring, which allows you to make changes to an existing object.
Click Apply and all references to the old name are changed to the new one, which corrects the line in the Designer. Click Apply to complete the Rename operation. You must follow the C rules for naming objects, methods, and variables. In addition, conscientious programmers also follow certain naming conventions.
Most professional programming shops have a set of standards that their programmers must use. Those standards may differ from the ones you find in this book, but the most important point is this: Good programmers follow standards. You should have a set of standards and always follow them. The Naming Rules When you select a name for an object, C requires the name to begin with a letter or an underscore.
The name can contain letters, digits, and underscores. An object name cannot include a space or punctuation mark and cannot be a reserved word, such as button or Close, but can contain one. For example, exitButton and closeButton are legal.
C is case sensitive, so exitbutton, ExitButton, and exitButton refer to three different objects. The Naming Conventions This text follows standard naming conventions, which help make projects more understandable. When naming controls, use camel casing, which means that you begin the name with a lowercase character and capitalize each additional word in the name. Do not use abbreviations unless it is a commonly used term that everyone will understand.
All names must be meaningful and indicate the purpose of the object. Examples messageLabel exitButton discountRateLabel Do not keep the default names assigned by C , such as button1 and label3. Also, do not name your objects with numbers. The exception to this rule is for labels that never change during program execution. These labels usually hold items such as titles, instructions, and labels for other controls. Leaving these labels with their default names is perfectly acceptable and is practiced in this text.
For forms and other classes, capitalize the first letter of the name and all other words within the name. Always append the word Form to the end of a form name. You can look up any C statement, class, property, method, or programming concept. Many coding examples are available, and you can copy and paste the examples into your own project, modifying them if you wish. You will want to filter the information to display only the Visual C and related information. Depending on how you install C , you are given the option to refer first to online, first to local, or only to local.
You can change this setting later in the Options dialog box Figure 1. Click on Online. You can choose the options to Try online first, then local; Try local first, then online; or Try local only, not online. Notice also that you can select sites to include in Help topics. The extensive Help is a two-edged sword: You have available a wealth of materials, but it may take some time to find the topic you want. You can switch from one window to the other, or resize the windows to view both on the screen if your screen is large enough.
In the Search window, you can choose additional filter options, such as the technology and topic type. Drop down a list and select any desired options Figure 1. In the Help Index window, you see main topics and subtopics indented beneath the main topics. All main topics and some subtopics have multiple entries available. When you choose a topic that has more than one possible entry, the Index Results pane opens up below the main Document window refer to Figure 1.
Click on the entry for which you are searching and the corresponding page appears in the Document window. For most controls, such as the Label control that appears in Figure 1. For now, always choose Windows Forms. The Help topic and Search appear in tabbed windows in the main Document window; Index, Contents, and Help Favorites appear in tabbed windows docked at the left of the main window.
A good way to start using Help is to view the topics that demonstrate how to look up topics in Help. Make sure to visit Managing Help Topics and Windows, which has subtopics describing how to copy topics and print topics. Select a C object, such as a form or a control, or place the insertion point in a word in the editor and press F1.
The Help window pops up with the corresponding Help topic displayed, if possible, saving you a search. Managing Windows At times you may have more windows and tabs open than you want.
You can hide or close any window, or switch to a different window. Only the top window will close. Click on the main topic, Button control [Windows Forms]: and click on the entry for about Button control. The topics included for the Professional Edition are more extensive than those for the Express Edition.
0コメント