Sams Teach Yourself C# in 24 Hours
More InformationLearn C#, Microsoft's newest programming language, one step at a time from leading expert, James Foxall. ...
Table of Contents
- Copyright
- About the Authors
- Acknowledgments
- Tell Us What You Think!
- Introduction
- Audience and Organization
- Conventions Used in This Book
- Onward and Upward!
- Part I. The Visual Studio Environment
- Hour 1. A C# Programming Tour
- Hour 2. Navigating C#
- Hour 3. Understanding Objects and Collections
- Hour 4. Understanding Events
- Part II. Building a User Interface
- Hour 5. Building FormsPart I
- Hour 6. Building FormsPart II
- Hour 7. Working with the Traditional Controls
- Hour 8. Advanced Controls
- Hour 9. Adding Menus and Toolbars to Forms
- Hour 10. Drawing and Printing
- Part III. Making Things HappenProgramming!
- Hour 11. Creating and Calling Methods
- Hour 12. Using Constants, Data Types, Variables, and Arrays
- Hour 13. Performing Arithmetic, String Manipulation, and Date/Time Adjustments
- Hour 14. Making Decisions in C# Code
- Hour 15. Looping for Efficiency
- Hour 16. Debugging Your Code
- Hour 17. Designing Objects Using Classes
- Hour 18. Interacting with Users
- Part IV. Working with Data
- Hour 19. Performing File Operations
- Hour 20. Controlling Other Applications Using Automation
- Hour 21. Working with a Database
- Part V. Deploying Solutions and Beyond
- Hour 22. Deploying a Solution
- Hour 23. Introduction to Web Development
- Hour 24. The 10,000-Foot View
- Appendix A. Answers to Quizzes/Exercises
Copyright
Copyright © 2002 by Sams Publishing
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.Library of Congress Catalog Card Number: 2001093572
Printed in the United States of America
First Printing: February 2002
05 04 03 02 4 3 2 1
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an "as is" basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.Credits
Associate Publisher
Linda Engelman
Acquisitions Editor
Sondra Scott
Development Editor
Ginny Bess
Managing Editor
Charlotte Clapp
Project Editor
Carol Bowers
Copy Editor
Barbara Hacha
Indexer
Erika Millen
Proofreader
Jody Larsen
Technical Editors
Joel Mueller
Deon Schaffer
Team Coordinator
Lynne Williams
Media Developer
Dan Scherf
Interior Designer
Gary Adair
Cover Designer
Aren Howell
Page Layout
D&G Limited, LLC
Dedication
To my children, Ethan and Tess.—James Foxall
To my parents, Olga and Alfonso, and my love, Dave.
—Wendy Haro-Chun
About the Authors
James Foxall is Vice President of Development and Support for Tigerpaw Software, Inc. (www.tigerpawsoftware.com)—an Omaha, Nebraska, Microsoft Certified Partner specializing in commercial database applications. James manages a commercial suite of programs designed to automate contact management, marketing, service and repair, proposal generation, and inventory control and purchasing. James's experience in creating certified Office-compatible software has made him an authority on application interface and behavior standards of applications for the Microsoft Windows and Microsoft Office environments.James has personally written more than 150,000 lines of commercial production code, both in single programmer and multiple programmer environments. He is the author of numerous books, including Practical Standards for Microsoft Visual Basic and MCSD in a Nutshell: The Visual Basic Exams, and he has written articles for Access-Office-VBA Advisor and Visual Basic Programmer's Journal. James is a Microsoft Certified Solution Developer and an international speaker on Microsoft programming technologies. When not programming or writing about programming, he enjoys spending time with his family, playing guitar, doing battle over the chess board, listening to Pink Floyd, playing computer games, and (believe it or not) programming! You can reach James at jamesf@tigerpawsoftware.com.
Wendy Haro-Chun, MCSD, holds a B.S. in Computer Science and an M.B.A. with an emphasis in International Business. She is Assistant Vice President of Research and Development for SunGard Insurance Systems. Her areas of technological expertise include .NET, C#, ASP, DHTML, JavaScript, XML, COM, VB, ADO, and Microsoft SQL Server. Wendy has also served as technical editor and reviewer on numerous computer technology books. She lives in Miami with her husband, Dave, and her two beagles, Buster and Belle. She can be reached at wharo@bellsouth.net.
Acknowledgments
James's acknowledgements:To Sondra Scott, both for the opportunity to do this book as well as just being a great person to work for!
To Wendy for her wonderful contributions, Carol Bowers, Ginny Bess, Joel Mueller, Deon Schaffer, and everyone else that had a hand in this book—thanks guys!
To Matt Wagner at Waterside Productions for all his help behind the scenes.
To my wife and children for always supporting and encouraging me through these projects. You are the best!
Finally, a special thanks to Mike Pizzo at Microsoft for his contributions to the ADO.NET chapter.
Wendy's acknowledgements:
I would like to thank Sondra Scott for giving me the opportunity to work on this great project. I would also like to thank Ginny Bess and Carol Bowers for making sure everything came together and technical editors Joel and Deon for making sure this new technology worked the way I said it did. Also, special thanks to Peter Farquharson, David Marcato, Deon Schaffer, and Larry Wall for helping to get this project started on a good foundation.
To James Foxall, I have enjoyed reading your VB .NET book, and it has been a great pleasure working with you on this C# book.
A big thanks goes out to my husband, Dave, for his constant support in all my projects and for always believing in me.
To Olga and Alfonso, thank you for all the support, encouragement, and love you have always given me.
Finally, thanks to all my relatives and friends for buying this book!
Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way.As an Associate Publisher for Sams Publishing, I welcome your comments. You can fax, e-mail, or write me directly to let me know what you did or didn't like about this book—as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this book, and that because of the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book's title and author as well as your name and phone or fax number. I will carefully review your comments and share them with the author and editors who worked on the book.
Fax: | 317-581-4770 |
E-mail: | feedback@samspublishing.com |
Mail: | Linda Engelman Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA |
Introduction
With Microsoft's introduction of the .NET platform, a new, exciting programming language was born. C# is the language of choice for developing on the .NET platform, and Microsoft has even written a majority of the .NET Framework using C#. C# is a modern object-oriented language designed and developed from the ground up with a best-of-breed mentality, implementing and expanding on the best features and functions found in other languages. C# combines the power and flexibility of C++ with the simplicity of Visual Basic.Audience and Organization
This book is targeted toward those who have little or no programming experience. The book has been structured and written with a purpose, and that is to get you productive as quickly and as smoothly as possible. I've used my experiences from writing large commercial applications to create a book that, hopefully, cuts through the fluff and teaches you what you need to know. All too often, authors fall into the trap of focusing on the technology rather than on the practical application of the technology. I've worked hard to keep this book focused on teaching you practical skills that you can apply immediately toward a development project. Please feel free to send me your suggestions or success stories at jamesf@tigerpawsoftware.com.This book is divided into five parts, each of which focuses on a different aspect of developing applications with C#. These parts generally follow the flow of tasks you'll perform as you begin creating your own programs using C#. I recommend that you read them in the order in which they appear.
- Part I The Visual Studio Environment teaches you about the Visual Studio's C# development environment, including how to navigate and access 'numerous tools. In addition, you'll learn some key development concepts such as objects, collections, and events.
- Part II Building a User Interface shows you how to build attractive and functional user interfaces. In this part, you'll learn about forms and controlsthe user-interface elements such as text boxes and list boxes.
- Part III Making Things HappenProgramming! teaches you the nuts and bolts of C# programmingand there's a lot to learn. You'll discover how to create methods, as well has how to store data, perform loops, and make decisions in code. After you've learned the core programming skills, you'll move into object-oriented programming and debugging applications.
- Part IV Working with Data introduces you to working with a database and shows you how to automate external applications such as Word and Excel. In addition, this part teaches you how to manipulate a user's file system.
- Part V Deploying Solutions and Beyond shows you how to distribute an application that you've created to an end user's computer. Then, the focus is brought back a bit to take a look at Web programming and Microsoft's .NET initiative from a higher, less-technical level.
Conventions Used in This Book
This book uses several conventions to help you prioritize and reference the information it contains:- Tips highlight information that can make your C# programming more effective.
- Cautions focus your attention on problems or side effects that can occur in specific situations.
- Notes provide useful sidebar information that you can read immediately or circle back to without losing the flow of the topic at hand.
- New Term icons signal places where new terminology is first used and defined. Such terminology appears in an italic typeface for emphasis.
Some code statements presented in this book are too long to appear on a single line. In these cases, a line-continuation character (an underscore) is used to indicate that the following line is a continuation of the current statement.
Onward and Upward!
This is an exciting time to be learning how to program, and it's my sincerest wish that when you finish this book, you will feel capable of creating, debugging, and deploying modest C# programs using many C# and Visual Studio tools. Although you won't be an expert, you'll be surprised at how much you've learned. And hopefully, this book will help you determine your future direction as you proceed down the road to C# mastery.Part I: The Visual Studio Environment
Before you can begin to create C# applications for Windows and the Web, you need to have a thorough grasp of the C# environment as well as some key development concepts. In this part, you'll get an overview of developing a project in C#, you'll learn all about the C# interface, and you'll learn about objects, collections, and events—concepts that are critical to your success as a C# developer.- Hour 1: A C# Programming Tour
- Hour 2: Navigating C#
- Hour 3: Understanding Objects and Collections
- Hour 4: Understanding Events
Hour 1. A C# Programming Tour
Learning a new programming language can be intimidating. If you've never programmed before, the act of typing seemingly cryptic text to produce sleek and powerful applications probably seems like a black art, and you may wonder how you'll ever learn everything you need to know. The answer is, of course, one step at a time. The first step to learning a language is the same as that of any other activity—building confidence. Programming is part art and part science. Although it may seem like magic, it's more akin to illusion; after you know how things work, a lot of the mysticism goes away, freeing you to focus on the mechanics necessary to produce the desired result.In this hour, you'll complete a quick tour that takes you step-by-step through creating a complete, albeit small, C# program. I've yet to see a "Hello World" program that's the least bit helpful (they usually do nothing more than print "hello world" to the screen—oh, fun). So instead, you'll create a picture-viewer application that lets you view Windows bitmaps and icons on your computer. You'll learn how to let a user browse for a file and how to display a selected picture file on the screen, both of which are skills that will come in handy in later applications that you create. Creating large, commercial solutions is accomplished by way of a series of small steps. After you've finished creating this small project, you'll have an overall feel for the development process.
The highlights of this hour include the following:
- Building a simple, yet functional, C# application
- Letting a user browse a hard drive
- Displaying a picture from a file on disk
- Getting familiar with some programming lingo
- Learning about the Visual Studio—C# IDE
Starting C#
You must become familiar with a few terms before you begin to create programs in C#:- Distributable Component The final, compiled version of a project. Components can be distributed to other people and other computers and do not require C# to run (although the .NET Framework is required, which you'll learn about in coming hours). Distributable components are also called programs. In Hour 22, "Deploying a Solution," you'll learn how to distribute the Picture Viewer program that you're about to build to other computers.
- Project A collection of files that can be compiled to create a distributable component (program). There are many types of projects, and complex applications may consist of many projects, such as a Windows Application project and support DLL projects.
- Solution A collection of projects and files that compose an application or component.
Creating a New Project
When you first start Visual Studio .NET, you're shown the Visual Studio Start Page tab within the IDE. Using this page, you can open projects created previously or create new ones (see Figure 1.1). For this quick tour, you're going to create a new Windows application, so click New Project to display the New Project dialog box shown in Figure 1.2. Figure 1.1 You can open existing projects or create new projects from the Visual Studio Start page.
Figure 1.2 The New Project dialog box allows you to create many types of .NET projects.
You can create many types of projects with C#, as well as with the other supported languages of the .NET platform. The New Project dialog box is used to specify the type of C# project you want to create. If the Visual C# Projects folder isn't selected, click it to display the C# project types and then make sure the Windows Application icon is selected (if it's not, click it once to select it). At the bottom of the New Project dialog box is a Name text box, in which you specify the name of the project you're creating; in the Location text box, you can enter the location in which to save the project files.Type Picture Viewer into the Name text box to name your project. There's no need to change the location where the project files are to be saved at this time, so go ahead and create the new Windows Application project by clicking OK. C# creates the new project, complete with one form (design window) for you to begin building the interface for your application (see Figure 1.3).
Figure 1.3 New Windows applications start with a blank form; the fun is just beginning!
Your C# environment may look different from that shown in the figures of this hour, depending on the edition of C# you're using, whether you've already played with C#, and other factors such as the resolution of your monitor. All the elements discussed in this hour, however, exist in all editions of C#. (If your IDE doesn't have a window displayed that is shown in a figure, use the View menu to display the window.)Giving the Form an Icon
Everyone who has used Windows is familiar with icons, which are the little pictures used to represent programs. Icons most commonly appear in the Start menu next to the name of their respective programs. In C#, you not only have control over the icon of your program file, you can also give every form in your program a unique icon if you want to.To give the form an icon, follow these steps:
- In the Properties window, click the Icon property to select it.
- When you click the Icon property, a small button with three dots appears to the right of the property. Click this button.
- To locate the HourOne.ico file or another ico file of your choice, use the Open dialog box that appears. When you've found the icon, double-click it, or click it once to select it and then click Open.
Changing the Size of the Form
Next, you're going to change the Width and Height properties of the form. The Width and Height values are shown collectively under the Size property; Width appears to the left of the comma, Height to the right. You can change the Width or Height by changing the corresponding number in the Size property. Both values represent the number of pixels of the dimension. To display and adjust the Width and Height properties separately, click the small plus sign (+) next to the Size property (see Figure 1.4). Figure 1.4 Some properties can be expanded to show more specific properties.
Change the Width property to 400 and the Height to 325. To commit a property change, press Tab or click a different property or window. Your screen should now look like the one in Figure 1.5. Figure 1.5 A change in the Properties window is reflected as soon as the change is committed.
When you first created this project, C# saved a copy of the source files in their initial state. The changes you've made so far exist only in memory; if you were to turn your computer off at this time (don't do this), you would lose any and all work up to this point. You should get into the habit of saving your work frequently. Save the project now by choosing Save All from the File menu or by clicking the Save All button on the toolbar (it has a picture of stacked disks on it).Adding Controls to a Form
Figure 1.6 The toolbox is used to select controls to build a user interface.
The toolbox closes itself soon after you've added a control to a form and the pointer is no longer over the toolbox. To make the toolbox stay visible, click the little picture of a pushpin located in the toolbox's title bar.Your Picture Viewer interface will consist of the following controls:
- Two Button controls
- A PictureBox control
- An OpenFileDialog control
Designing an Interface
It's generally best to design the user interface of a form and then add the code behind the interface that makes the form functional. The user interface for your Picture Viewer program will consist of a View Picture button, a Close button, and a PictureBox in which to display a picture.Adding a Visible Control to a Form
Start by adding a Button control to the form. Do this by double-clicking the Button item in the toolbox. C# then creates a new button and places it in the upper-left corner of the form (see Figure 1.7). Figure 1.7 When you double-click a control in the toolbox, the control is added to the upper-left corner of the form.
Using the Properties window, set the button's properties as follows (note that you may want to change the Properties list to alphabetical, if it is not already, to make it easier to find these properties by name):Property | Value |
Name | btnSelectPicture |
Text | Select Picture |
Location | 301,10 (Note: 301 is the x coordinate, 10 is the y coordinate.) |
Size | 85,23 |
Property | Value |
Name | btnQuit |
Text | Quit |
Location | 301,40 |
Property | Value |
Name | picShowPicture |
BorderStle | FixedSingle |
Location | 8,8 |
Size | 282, 275 |
Figure 1.8 An application's interface doesn't have to be complex to be useful.
Scroll the toolbox until you can see the OpenFileDialog control, and then double-click it to add it to your form. (You may have to scroll the toolbox, which is done by clicking the up arrow toward the top of the window or the down arrow toward the bottom.) Note that the control isn't placed on the form, but it appears in a special area below the form (see Figure 1.9). This happens because the OpenFileDialog control has no interface to display to a user. It does have an interface, a dialog box that you can display as necessary, but it has nothing to display directly on a form.
The Filter property determines the filtering of the control. The text that appears before the pipe symbol (|) is the descriptive text of the file type, whereas the text after the pipe symbol is the pattern to use to filter files; you can specify more than one filter type. Text entered into the Title property appears in the title bar of the Open File dialog box.
You're going to write code to accomplish two tasks. First, you're going to write code that lets the user browse his or her hard drives to locate and select a picture file and then display the file in the picture box (this sounds a lot harder than it is). Second, you're going to add code to the Quit button that shuts down the program when the user clicks the button.
Enter the following statement:
To update the entry point in this sample, press Ctrl+F to open the Find window, enter Form1, and click Find Next. Close the Find window and replace the text Form1 with fclsViewer. The updated statement should now read:
Enter the following code in the Quit button's Click event handler:
Adding an Invisible Control to a Form
To allow the user to select a picture to display, you need to give her the capability to locate a file on her hard drive. You've probably noticed in the past that whenever you choose to open a file from within any Windows application, the dialog box displayed is almost always the same. It doesn't make any sense to force each and every developer to write the code necessary to perform standard file operations. Instead, Microsoft has exposed the functionality via a control that you can use in your project. This control is called the OpenFileDialog control, and it will save you dozens of hours that you would otherwise spend trying to duplicate common functionality.Scroll the toolbox until you can see the OpenFileDialog control, and then double-click it to add it to your form. (You may have to scroll the toolbox, which is done by clicking the up arrow toward the top of the window or the down arrow toward the bottom.) Note that the control isn't placed on the form, but it appears in a special area below the form (see Figure 1.9). This happens because the OpenFileDialog control has no interface to display to a user. It does have an interface, a dialog box that you can display as necessary, but it has nothing to display directly on a form.
Figure 1.9 Controls that have no interface appear below the form designer.
Select the OpenFileDialog control and change its properties as follows:Property | Value |
Name | ofdSelectPicture |
Filter | Windows Bitmaps|*.BMP|JPEG Files|*.JPG |
Title | Select Picture |
Coding an Interface
The graphical interface for your Picture Viewer program is now complete, so click the pushpin in the title bar of the toolbox to close it. Now, you have to write code for the program to be capable of performing actions. C# is an event-driven language, which means that code is executed in response to events. These events may come from users, such as a user clicking a button, or from Windows itself (see Hour 4, "Understanding Events," for a complete explanation of events). Currently, your application looks nice but it won't do a darn thing. The user can click the Select Picture button, for example, until the cows come home, but nothing will happen because you haven't told the program what to do when the user clicks the button.You're going to write code to accomplish two tasks. First, you're going to write code that lets the user browse his or her hard drives to locate and select a picture file and then display the file in the picture box (this sounds a lot harder than it is). Second, you're going to add code to the Quit button that shuts down the program when the user clicks the button.
Letting a User Browse for a File
The first bit of code you're going to write will allow the user to browse his or her hard drives, select a file, and then show the selected picture in the PictureBox control. This code will execute when the user clicks the Select Picture button; therefore, it's added to the Click event of that button (you'll learn all about events in later hours). When you double-click a control on a form in Design view, the default event for that control is created and displayed in a code window. The default event for a Button control is its Click event, which makes sense because clicking a button is its most common purpose. Double-click the Select Picture button now to access its Click event in the code window (see Figure 1.10). Figure 1.10 You will write all code in a window such as this.
It's very important that you get in the habit of commenting your code, so the first line you're going to enter is a comment. Beginning a statement with the characters // designates the statement as a comment; the compiler won't do anything with the statement, so you can enter whatever text you want after the double slashes. Type the following statement exactly as it appears and press the Enter key at the end of the line.// Show the open file dialog box.The next statement you'll enter triggers a method of the OpenFileDialog control that you added to the form. You'll learn all about methods in Hour 3, "Understanding Objects and Collections." For now, think of a method as a mechanism to make a control take action. The ShowDialog method tells the control to show its Open dialog box and let the user select a file. The ShowDialog method returns a value that indicates its success or failure, which we are then comparing to a predefined result (DialogResult.OK). Don't worry too much about what is happening here, because you'll be learning the details of this in later hours. In a nutshell, the ShowDialog method is called to let a user browse for a file, and if the user selects a file, more code gets executed. Of course, there is a lot more to using the OpenFileDialog control than I present in this basic example, but this simple statement gets the job done. Enter the following if statement followed by an open brace:
if (ofdSelectPicture.ShowDialog() == DialogResult.OK) {Time for another comment. Enter this statement and remember to press Enter at the end of each code line.
// Load the picture into the picture box.You're now going to enter the next line of code. This statement, which appears within the if construct, is the line of code that actually displays the picture in the picture box. (If you're itching to know more about graphics, take a look at Hour 10, "Drawing and Printing.")
Enter the following statement:
picShowPicture.Image = Image.FromFile(ofdSelectPicture.FileName);In addition to displaying the selected picture, your program is going to display the path and filename of the picture in the title bar. When you first created the form, you changed the Text property of the form using the Properties window. To create dynamic applications, properties need to be constantly adjusted at runtime, and this is done using code. Enter the following three lines of code:
// Show the name of the file in the form's caption. this.Text = String.Concat("Picture Viewer (" + ofdSelectPicture.FileName + ")");
}
Checking Your Program Entry Point
All C# programs must contain an entry point. The Main() method is the entry point. In this sample you need to change the reference from Form1 to fclsViewer (this is necessary because we renamed the form earlier) . This statement will invoke the constructor on the form. C++ programmers will be familiar with the Main() entry point method, but they should take notice of the capitalization of Main. We will talk a bit more about the program entry point later in the book.To update the entry point in this sample, press Ctrl+F to open the Find window, enter Form1, and click Find Next. Close the Find window and replace the text Form1 with fclsViewer. The updated statement should now read:
Application.Run(new fclsViewer());After you've entered all the code, your editor should look like that shown in Figure 1.11.
Figure 1.11 Make sure your code exactly matches the code shown here.
Terminating a Program Using Code
The last bit of code you'll write will terminate the application when the user clicks the Quit button. To do this, you'll need to access the Click event handler of the btnQuit button. At the top of the code window are two tabs. The current tab has the text fclsViewer.cs. Next to this is a tab that contains the text fclsViewer.cs [Design]. Click this tab now to switch from Code view to the form designer. If you receive an error when you click the tab, the code you entered is incorrect, and you need to edit it to make it the same as I've presented it. After the form designer is displayed, double-click the Quit button to access its Click event.Enter the following code in the Quit button's Click event handler:
this.Close();
Running a Project
Your application is now complete. Click the Save All button (it looks like a stack of disks) on the toolbar, and then run your program by pressing F5. You can also run the program by clicking the button on the toolbar that looks like a right-facing triangle and resembles the Play button on a VCR (this button is also found on the Debug menu, and it is called Start). However, learning the keyboard shortcuts will make your development process move along faster. When you run the program, the C# interface changes, and the form you've designed appears floating over the design environment (see Figure 1.12). Figure 1.12 When in Run mode, your program executes the same as it would for an end user.
You're now running your program as though it were a standalone application running on another user's machine; what you see is exactly what someone else would see if they ran the program (without the C# design environment in the background, of course). Click the Select Picture button to display the Select Picture dialog box (see Figure 1.13). Use the dialog box to locate a picture file. When you've found a file, double-click it, or click once to select it and then click Open. The selected picture is then displayed in the PictureBox control, as shown in Figure 1.14. Figure 1.13 The OpenFileDialog control handles all the details of browsing for files. Cool, huh?
Figure 1.14 C# makes it easy to display pictures with very little work.
Summary
When you're done playing with the program, click the Quit button and then save your project by clicking Save All on the C# toolbar.That's it! You've just created a bona fide C# program. You've used the toolbox to build an interface with which users can interact with your program, and you've written code in strategic event handlers to empower your program to do things. These are the basics of application development in C#. Even the most complicated programs are built using this basic approach; you build the interface and add code to make the application do things. Of course, writing code to do things exactly the way you want things done is where the process can get complicated, but you're on your way.
If you take a close look at the organization of the hours in this book, you'll see that I start out by teaching you the C# environment. I then move on to building an interface, and later I teach you all about writing code. This organization is deliberate. You might be a little anxious to jump in and start writing serious code, but writing code is only part of the equation. As you progress through the hours, you'll be building a solid foundation of development skills.
Soon, you'll pay no attention to the man behind the curtain—you'll be that man (or woman)!
Q&A
- Can I show bitmaps of file types other than BMP and JPG?
Yes. The PictureBox supports the display of images with the extensions BMP, JPG, ICO, EMF, WMF, and GIF. The PictureBox can even save images to a file. - Is it possible to show pictures in other controls?
The PictureBox is the control to use when you are just displaying images. However, many other controls allow you to display pictures as part of the control. For instance, you can display an image on a Button control by setting the button's Image property to a valid picture
Workshop
The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in Appendix A,"Answers to Quizzes/Exercises."
Quiz
- What type of C# project creates a standard Windows program?
- What window is used to change the attributes (location, size, and so on) of a form or control?
- How do you access the default event (code) of a control?
- What property of a PictureBox do you set to display an image?
- What is the default event for a Button control?
Exercise
- Change your Picture Viewer program so that the user can also locate and select GIF files. (Hint: Change the Filter property of the OpenFileDialog control.)
- Alter the form in your Picture Viewer project so that the buttons are side by side in the lower-right corner of the form, rather than vertically aligned in the upper-right corner.