James'sexperience in creating certified Office-compatible software hasmade him an authority on application interface and behaviorstandards of applications for the Microsoft Windows andMi
Trang 1Sams Teach Yourself C# in 24 Hours provides
readers with 24 structured lessons that provide
a light, but thorough introduction to C# JamesFoxall moves beyond the pure syntax covered
in existing books, to guide readers step through a cohesive presentation of thebasics of C# Once the basics are understood,Foxall shows the reader how to apply this
programming tasks using C# Each chaptercontains exercises that reinforce the lessonslearned in each chapter Tips, Notes, andCautions provide additional advice from theauthors on how to get up to speed andprogramming quickly with C# Sidebarsprovide the more experienced reader with tipsthat will ease their migration from Visual Basic
6 and Visual C++ to C#
Trang 10Top
Trang 13Copyright © 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 patentliability is assumed with respect to the use of the informationcontained herein Although every precaution has been taken inthe preparation of this book, the publisher and author assume
no responsibility for errors or omissions Nor is any liabilityassumed for damages resulting from the use of the informationcontained herein
Warning and Disclaimer
Trang 14as accurate as possible, but no warranty or fitness is implied.The information provided is on an "as is" basis The author andthe publisher shall have neither liability nor responsibility to anyperson or entity with respect to any loss or damages arisingfrom the information contained in this book
Trang 16Top
Trang 18James Foxall is Vice President of Development and Support for
Tigerpaw Software, Inc (www.tigerpawsoftware.com)—anOmaha, Nebraska, Microsoft Certified Partner specializing incommercial database applications James manages acommercial suite of programs designed to automate contactmanagement, marketing, service and repair, proposalgeneration, and inventory control and purchasing James'sexperience in creating certified Office-compatible software hasmade him an authority on application interface and behaviorstandards of applications for the Microsoft Windows andMicrosoft Office environments
James has personally written more than 150,000 lines ofcommercial production code, both in single programmer andmultiple 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 onMicrosoft programming technologies When not programming orwriting about programming, he enjoys spending time with hisfamily, 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
VB, ADO, and Microsoft SQL Server Wendy has also served as
Trang 19technical editor and reviewer on numerous computertechnology books She lives in Miami with her husband, Dave,and her two beagles, Buster and Belle She can be reached at
wharo@bellsouth.net
Top
Trang 21To 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 constantsupport in all my projects and for always believing in me
Trang 22To 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 thisbook!
Top
Trang 24As the reader of this book, you are our most important criticand commentator We value your opinion and want to knowwhat we're doing right, what we could do better, what areasyou'd like to see us publish in, and any other words of wisdomyou're willing to pass our way
As an Associate Publisher for Sams Publishing, I welcome yourcomments You can fax, e-mail, or write me directly to let meknow what you did or didn't like about this book—as well aswhat we can do to make our books stronger
Please note that I cannot help you with technical problemsrelated to the topic of this book, and that because of the highvolume of mail I receive, I might not be able to reply to everymessage
When you write, please be sure to include this book's title andauthor as well as your name and phone or fax number I willcarefully review your comments and share them with the authorand editors who worked on the book
E-mail: feedback@samspublishing.com
Mail:
Linda EngelmanSams Publishing
201 West 103rd StreetIndianapolis, IN 46290 USA
Top
Trang 26With Microsoft's introduction of the NET platform, a new,exciting programming language was born C# is the language ofchoice for developing on the NET platform, and Microsoft haseven written a majority of the NET Framework using C# C# is
a modern object-oriented language designed and developedfrom the ground up with a best-of-breed mentality,implementing and expanding on the best features and functionsfound in other languages C# combines the power and flexibility
of C++ with the simplicity of Visual Basic
Top
Trang 27
Audience and Organization
This book is targeted toward those who have little or noprogramming experience The book has been structured andwritten with a purpose, and that is to get you productive asquickly and as smoothly as possible I've used my experiencesfrom writing large commercial applications to create a bookthat, hopefully, cuts through the fluff and teaches you what youneed to know All too often, authors fall into the trap of focusing
on the technology rather than on the practical application of thetechnology I've worked hard to keep this book focused onteaching you practical skills that you can apply immediatelytoward a development project Please feel free to send me your
jamesf@tigerpawsoftware.com
This book is divided into five parts, each of which focuses on adifferent aspect of developing applications with C# These partsgenerally follow the flow of tasks you'll perform as you begincreating your own programs using C# I recommend that youread them in the order in which they appear
Part I The Visual Studio Environment teaches you aboutthe Visual Studio's C# development environment, includinghow to navigate and access 'numerous tools In addition,you'll learn some key development concepts such asobjects, collections, and events
Part II Building a User Interface shows you how to buildattractive and functional user interfaces In this part, you'lllearn about forms and controls—the user-interface elementssuch as text boxes and list boxes
Part III Making Things Happen—Programming! teaches
Trang 28you the nuts and bolts of C# programming—and there's alot to learn You'll discover how to create methods, as wellhas 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 anddebugging applications
Part IV Working with Data introduces you to working with adatabase and shows you how to automate externalapplications such as Word and Excel In addition, this partteaches you how to manipulate a user's file system
Part V Deploying Solutions and Beyond shows you how todistribute an application that you've created to an enduser's computer Then, the focus is brought back a bit totake a look at Web programming and Microsoft's NETinitiative from a higher, less-technical level
Top
Trang 29New Term icons signal places where new terminology is
first used and defined Such terminology appears in an italictypeface for emphasis
In addition, this book uses various typefaces to help youdistinguish code from regular English Code is presented in amonospace font Placeholders—words or characters usedtemporarily to represent the real words or characters you wouldtype in code—are typeset in italic monospace
Some code statements presented in this book are too long toappear on a single line In these cases, a line-continuationcharacter (an underscore) is used to indicate that the followingline is a continuation of the current statement
Top
Trang 30Top
Trang 32Before you can begin to create C# applications for Windowsand the Web, you need to have a thorough grasp of the C#environment as well as some key development concepts Inthis part, you'll get an overview of developing a project inC#, you'll learn all about the C# interface, and you'll learnabout objects, collections, and events—concepts that arecritical to your success as a C# developer
Trang 34Learning a new programming language can be intimidating Ifyou've never programmed before, the act of typing seeminglycryptic text to produce sleek and powerful applications probablyseems like a black art, and you may wonder how you'll everlearn everything you need to know The answer is, of course,one step at a time The first step to learning a language is thesame as that of any other activity—building confidence.Programming is part art and part science Although it may seemlike magic, it's more akin to illusion; after you know how thingswork, a lot of the mysticism goes away, freeing you to focus onthe mechanics necessary to produce the desired result
In this hour, you'll complete a quick tour that takes you by-step through creating a complete, albeit small, C# program.I've yet to see a "Hello World" program that's the least bithelpful (they usually do nothing more than print "hello world" tothe screen—oh, fun) So instead, you'll create a picture-viewerapplication that lets you view Windows bitmaps and icons onyour computer You'll learn how to let a user browse for a fileand how to display a selected picture file on the screen, both ofwhich are skills that will come in handy in later applications thatyou create Creating large, commercial solutions isaccomplished by way of a series of small steps After you'vefinished creating this small project, you'll have an overall feelfor the development process
step-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
Trang 35Learning about the Visual Studio—C# IDE
I hope that by the end of this hour, you'll realize just how muchfun it is to program using C#
Top
Trang 36
Starting C#
You must become familiar with a few terms before you begin tocreate programs in C#:
Distributable Component The final, compiled version of aproject Components can be distributed to other people andother computers and do not require C# to run (although the.NET Framework is required, which you'll learn about incoming hours) Distributable components are also calledprograms In Hour 22, "Deploying a Solution," you'll learnhow to distribute the Picture Viewer program that you'reabout to build to other computers
Project A collection of files that can be compiled to create adistributable component (program) There are many types
of projects, and complex applications may consist of manyprojects, such as a Windows Application project and supportDLL projects
Solution A collection of projects and files that compose anapplication or component
C# is a complete development environment; every tool you'll need to create your C# projects is accessed from within Visual Studio The Visual Studio-C# environment is called the IDE, short for Integrated Development Environment, and it is the design framework in which you build applications To work with C# projects, you must first start the Visual Studio IDE.
Trang 37from within the Microsoft Visual Studio NET folder on your Startmenu
Top
Trang 38
Creating a New Project
When you first start Visual Studio NET, you're shown the VisualStudio Start Page tab within the IDE Using this page, you canopen projects created previously or create new ones (see Figure1.1) For this quick tour, you're going to create a new Windowsapplication, so click New Project to display the New Projectdialog 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.
Trang 39If you don't see the Visual Studio Start page, chances are that you've changed the default settings Hour 2,
"Navigating C#," shows you how to change them back For now, be aware that you can create a new project from the File menu in addition to using the techniques described in this hour.
You can create many types of projects with C#, as well as withthe other supported languages of the NET platform The NewProject dialog box is used to specify the type of C# project youwant to create If the Visual C# Projects folder isn't selected,click it to display the C# project types and then make sure theWindows Application icon is selected (if it's not, click it once toselect it) At the bottom of the New Project dialog box is aName text box, in which you specify the name of the projectyou're creating; in the Location text box, you can enter thelocation in which to save the project files
Trang 40You should always set these values to something meaningful before creating a project, or you'll have more work to do later if you want to move or rename the project.
Type Picture Viewer into the Name text box to name your
project There's no need to change the location where theproject files are to be saved at this time, so go ahead andcreate the new Windows Application project by clicking OK C#creates the new project, complete with one form (designwindow) for you to begin building the interface for yourapplication (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
Trang 41figures of this hour, depending on the edition of C# you'reusing, whether you've already played with C#, and other factorssuch as the resolution of your monitor All the elementsdiscussed in this hour, however, exist in all editions of C# (Ifyour IDE doesn't have a window displayed that is shown in afigure, use the View menu to display the window.)
To create a program that can be run on another computer, you start by creating a project, and then you compile the project into a component, such as an executable (a program a user can run) or a DLL (a component that can be used by other programs and components) The compilation process is discussed in detail in Hour 22, "Deploying a Solution." The important thing to note at this time is that when you hear someone refer to creating or writing a program, just as you are creating the Picture Viewer program now, they're referring to the completion of all steps up
to and including compiling the project to a distributable file.
Top