1. Trang chủ
  2. » Khoa Học Tự Nhiên

2003 ms ms visual c sharp net step by step version 200

965 225 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 965
Dung lượng 6,28 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Microsoft Visual C# .NET Step by Step - Version 2003by John Sharp and Jon Jagger ISBN:0735619093 Microsoft Press © 2003 635pages Teach yourself Visual C# .NET version 2003—and start dev

Trang 1

Microsoft Visual C# NET Step by Step - Version 2003

by John Sharp and Jon Jagger

ISBN:0735619093

Microsoft Press © 2003 (635pages)

Teach yourself Visual C#

.NET version 2003—and start developing Microsoft NET–

connected applications—one step at a time Master

language fundamentals at your own pace and use the learn-by-doing exercises to dig in and code!

Trang 4

Build your dexterity with Visual C# and begin writing Microsoft.NET-connected applications—one step at a time! This practical, hands-on tutorial expertly guides you through the fundamentals—from learning Visual C# syntax to writing and running your first

components, Web services, and applications Work at your own pace through easy-to-follow lessons and

hands-on exercises to teach yourself essential

techniques And stay ahead of the curve by working with real-world examples and best practices for Visual C# development.

Discover how to:

Declare variables, define methods, and construct statements

Define operators to enhance class usability

Create GUI components and user controls

Access data sources using Microsoft ADO.NET

Trang 5

the ACCU Overload journal.

Trang 6

Microsoft Visual C# NET Step by Step, Version 2003

Library of Congress Cataloging-in-Publication Data

Sharp, John, 1964-Microsoft Visual C# NET Step by Step: Version 2003 / John Sharp, JonJagger

p cm

Includes index

ISBN 0-7356-1909-3

1 C# (Computer program language) 2 Microsoft NET I Jagger, Jon,1966- II Title

Trang 7

Microsoft Press books are available through booksellers and distributorsworldwide For further information about international editions, contactyour local Microsoft Corporation office or contact Microsoft Press

International directly at fax (425) 936-7329 Visit our Web site at

www.microsoft.com/mspress Send comments to

mspinput@microsoft.com.

ActiveX, IntelliSense, JScript, Microsoft, Microsoft Press, Visual Basic,Visual C++, Visual C#, Visual Studio, Windows, and Windows NT areeither registered trademarks or trademarks of Microsoft Corporation inthe United States and/or other countries Other product and companynames mentioned herein may be the trademarks of their respective

owners

The example companies, organizations, products, domain names, e-mailaddresses, logos, people, places, and events depicted herein are

fictitious No association with any real company, organization, product,domain name, e-mail address, logo, person, place, or event is intended

Trang 8

Edmundson, Elisabeth Knottingham, and Lonnon Foster, and thank themfor their enduring patience with my endless typos, grammatical errors,and jargon I would also like to thank Suzanne Carlino, my project

manager at Content Master, who beat me up and made sure I stuck tothe schedule, and Robert Burbidge, who stepped in at the last minuteand spent many thankless hours reviewing my work—and we are stillfriends!

For the second edition of this book, I would also like to thank everyonewho submitted reports to the Microsoft Press Web site identifying typos,mistakes, and making requests I hope we have incorporated everything!Furthermore, I am indebted to David Glanville, my project manager atContent Master, who guided me though the process of performing theseupdates and made sure I had the necessary time available (mainly aftermidnight!)

Finally, I would like to acknowledge the support and help given to me by

my family—to Diana, who had to put up with me creeping to bed at 2:00

in the morning on many occasions (at least some occurrences of whichwere related to my book-writing activities), to James, who kept asking “IsDaddy STILL on that computer?” and to Francesca, who just wants tosee her name in a book

And finally, finally,“Up the Gills!”

John Sharp

I’d like to dedicate this book to the five most important people in my life:

my mother for having such a strong but gentle influence on me; my wife,Natalie, for making my life infinitely richer; and our three children, Ellie,Penny, and Patrick, who teach me important new things every day

I’d also like to thank everyone who has helped me learn interesting

things, particularly Douglas Adams, Christopher Alexander, Sean

Corfield, Richard Gabriel, Kevlin Henney, John Holt, and David Pye

Finally, I’d like to pay tribute to the elegance of the two-seater sports cars

Trang 9

Python, the grass roots programming support provided by ACCU

(http://www.accu.org), and the quality of life generated by the people ofthe village I live in

Jon Jagger

About the Authors

John Sharp is a principal technologist at Content Master Ltd., a technicalauthoring company in the United Kingdom He develops and deliversinstruction on everything from C#, J#, ASP.NET, and NET development

to UNIX and Java programming John is deeply involved with Microsoft.NET development, writing courses, building tutorials, and delivering

conference presentations covering Microsoft Visual C# development andMicrosoft ASP.NET He lives in Tetbury, Gloucestershire, in the UnitedKingdom

Keyhole Saw

Saws have been in use since prehistoric times One dating from 1450B.C., taken from an Egyptian tomb, doesn’t look much different from

some saws in use today Different saws fill different needs For cuttingholes, there is the compass saw or the shorter, thinner-bladed keyholesaw, which as the name implies is used to cut keyholes.*

Trang 10

developers and IT professionals Tools very simply and powerfully

symbolize human inventiveness They’re a metaphor for people

extending their capabilities, precision, and reach From simple calipersand pliers to digital micrometers and lasers, these stylized illustrationsgive each book a visual identity, and a personality to the series Withtools and knowledge, there’s no limit to creativity and innovation Our

tagline says it all: the tools you need to put technology to work.

*The Great Tool Emporium © 1979 by David X Manners Published byBook Division, Times Mirror Magazines, Inc

The manuscript for this book was prepared and submitted to MicrosoftPress in electronic form Pages were composed by Microsoft Press usingAdobe FrameMaker+SGML for Windows, with text in Sabon and displaytype in ITC Franklin Gothic Composed pages were delivered to the

Trang 11

Microsoft Visual C# NET is a powerful but simple language aimed

primarily at developers creating applications for the Microsoft NET

platform It inherits many of the best features of C++ and Microsoft VisualBasic but with some of the inconsistencies and anachronisms removed,resulting in a cleaner and more logical language C# also contains a

variety of useful features that accelerate application development,

especially when used in conjunction with Microsoft Visual Studio NET

The aim of this book is to teach you the fundamentals of programmingwith C# using Visual Studio NET and the NET Framework You will learnthe features of the C# language, and then use them to build applicationsrunning the Microsoft Windows operating system By the time you havecompleted this book, you will have a thorough understanding of C# andwill have used it to build Windows Forms applications, manipulate XML,access SQL Server, control Windows services, develop ASP.NET

applications, and build and consume a Web service

Trang 12

This book is designed to help you build skills in a number of essentialareas You can use this book if you are new to programming or you areswitching from another programming language such as C, C++, SunMicrosystems’s Java, or Microsoft Visual Basic 6 Use the following table

3 Complete Parts 4, 5, and 6 as your level ofexperience and interest dictates

on Chapters 6 through 17

2 Complete Parts 4, 5, and 6 as your level ofexperience and interest dictates

Migrating

1 Install the practice files as described in the

next section of this chapter, “Installing andUsing the Practice Files.”

Trang 13

Java

2 Skim the first seven chapters to get anoverview of C# and Visual Studio NET,and then concentrate on Chapters 8through 17

3 For information about building Windowsapplications and using a database, read

Parts 4 and 5

4 For information about building Webapplications and Web services, read Part 6

3 For information about building Windowsapplications, read Part 4

4 For information about accessing adatabase, read Part 5

5 For information about creating Webapplications and Web services, read Part 6

6 Read the Quick Reference sections at theend of the chapters for information aboutspecific C# and Visual Studio NET

constructs

Referencing

The book after

1 Use the index or the Table of Contents tofind information about particular subjects

2 Read the Quick Reference sections at the

Trang 14

the exercises

end of each chapter to find a brief review ofthe syntax and techniques presented in thechapter

Trang 15

You’ll need the following hardware and software to complete the

exercises in this book:

Microsoft Windows XP Professional Edition, Microsoft WindowsServer 2003, Microsoft Windows 2000 Professional, or MicrosoftWindows 2000 Server with Service Pack 3

Microsoft Visual Studio NET 2003 Professional or EnterpriseEdition (If you’re using the Standard Edition of Visual C# NET

2003 you can’t create controls, but you can complete the otherexercises in this book.)

Microsoft Desktop Engine (MSDE) installed and configured, if youare running Microsoft Visual Studio NET 2003 Professional oraccess to Microsoft SQL Server 2000 or later, if you are runningMicrosoft Visual Studio NET 2003 Enterprise Edition

Access to the Northwind Traders database running under MSDE

or SQL Server

Microsoft Internet Information Services 5 (or later) installed andrunning

450 MHz Pentium II-class or compatible processor (600 MHzPentium III-class recommended)

Trang 16

The CD-ROM inside this book contains the practice files that you’ll use asyou perform the exercises in the book For example, when you’re

learning about if statements, you’ll use a pre-written project called

Selection By using the practice files, you won’t waste time creating

objects that aren’t relevant to the exercise Instead, you can concentrate

on learning object-oriented programming with Visual C# NET The filesand the step-by-step instructions in the lessons also let you learn by

doing, which is an easy and effective way to acquire and remember newskills

Installing the Practice Files

Follow these steps to install the practice files on your computer’s harddisk so that you can use them with the exercises in this book

1 Remove the CD-ROM from the package inside this book andinsert it into your CD-ROM drive

Note A Starting menu should launch automatically If this

menu does not appear, double-click the My Computericon on the desktop, double- click the icon for yourCD-ROM drive, and then double-click StartCD.exe

2 Click Install Practice Files

3 Follow the onscreen instructions

4 When the files have been installed, remove the CD-ROM fromyour CD-ROM drive and replace it in the package inside thebook

A folder named Microsoft Press\Visual C# Step by Step hasbeen created in your My Documents folder on your hard disk,and the practice files have been placed in that folder

Using the Practice Files

Trang 17

For those of you who like to know all the details, here’s a list of the VisualC# projects on the practice disk

Chapter 1

TextHello

This project gets you started It steps throughthe creation of a simple program that displays atext-based greeting

structured by using methods

DailyRate

This project walks you through writing your ownmethods (both manually and by using a wizard),running the methods, and stepping through themethod calls using the Visual Studio debugger

Chapter 4

Trang 18

Iteration

This project displays code fragments for each ofthe different iteration statements and the outputthat each generates

whileStatement

This project uses a while statement to read the

contents of a source file one line at a time anddisplay each line in a Windows text box

parameters It demonstrates how to use the ref and out keywords.

Trang 19

UsingStatement

This project revisits a small piece of code fromthe previous chapter and reveals that it is notexception-safe It shows you how to make the

code exception-safe with a using statement.

Chapter 14

Properties

This project presents a simple Windowsapplication that uses several properties tocontinually display the size of its main window

Trang 20

Indexers

This project uses two indexers: one to look up aperson’s phone number when given a name,and the other to look up a person’s name whengiven a phone number

Chapter 16

Delegates

This project displays the time in digital formatusing delegate callbacks The code is thensimplified by using events

Chapter 20

CustomerDetails

This project demonstrates how to validate userinput using customer information as an

example

Chapter 21

SplitterDemo

This project shows how to use the Splitter control, and shows how the Dock property of

various controls can be used

Trang 21

LoginControl

This project is a Windows Control It providesthe logic for logging in to a system in a genericmanner

information in the Products table using an

SqlDataAdapter and a DataSet control.

ReportOrders

This project shows how to access a databaseusing Microsoft ADO.NET code rather than adata link and data controls The applicationretrieves information from the Orders table

Chapter 25

Trang 22

This project shows how to use simple databinding to bind properties of controls to singlevalues in various data sources

ComplexBindingDemo

This project shows how to use complex databinding to display a list of values from a datasource

ManageTerritories

This project demonstrates how to use data

binding and a disconnected DataSet to retrieve

and maintain information from the Territoriestable in the Northwind Traders database

and shows how to validate user input in anASP.NET Web application

Chapter 29

CustomerInfo

This project shows how to use Forms-basedsecurity for authenticating the user Theapplication also demonstrates how to useADO.NET from an ASP.NET Web form,showing how to manipulate a database in ascalable manner

Trang 23

ProductCategories

This project shows techniques for navigatingbetween Web forms in an ASP.NET application,passing information from one Web form to

another

Chapter 31

NorthwindServices

This project implements an XML Web service,providing remote access across the Internet todata in the Products table in the NorthwindTraders database

Chapter 32

OrderCost

This project shows how to create a Windowsapplication that consumes an XML Web service

It shows how to synchronously invoke the XMLWeb service created in Chapter 31

ProductInfo

This project is another XML Web serviceconsumer It shows how to invoke a Webservice asynchronously

In addition to these projects, several projects have solutions available forthe practice exercises The solutions for each project are included on theCD-ROM in the folder for each chapter and are labeled Complete

Uninstalling the Practice Files

Follow these steps to remove the practice files from your computer

These steps are written for Windows XP Professional operating system

Trang 24

1 Click Start, and then click Control Panel

2 Click Add/Remove Programs

3 From the list of Currently Installed Programs, select MicrosoftVisual C# NET Step By Step (2003) Sample Files

Trang 25

This book presents information using conventions designed to make theinformation readable and easy to follow Before you start the book, readthe following list, which explains conventions you’ll see throughout thebook and points out helpful features in the book that you might want touse

Conventions

Each exercise is a series of tasks Each task is presented as aseries of numbered steps (1, 2, and so on) A round bullet (•)indicates an exercise that has only one step

Notes labeled “Tip” provide additional information or alternativemethods for completing a step successfully

Notes labeled “Important” alert you to information you need tocheck before continuing

Text that you type appears in bold.

A plus sign (+) between two key names means that you mustpress those keys at the same time For example, “Press Alt+Tab”means that you hold down the Alt key while you press the Tabkey

Other Features

Shaded sidebars throughout the book provide more in-depthinformation about the exercise The sidebars might contain

background information, design tips, or features related to theinformation being discussed

Each chapter ends with a Quick Reference section The QuickReference section contains quick reminders of how to performthe tasks you learned in the chapter

Trang 26

Every effort has been made to ensure the accuracy of this book and thecontents of the practice files on the CD-ROM Microsoft Press providescorrections and additional content for its books through the World WideWeb at this location:

http:/ www.microsoft.com/mspress/support/

To connect directly to the Microsoft Press Knowledge Base and enter aquery regarding a question or issue that you may have, go to

http://www.microsoft.com/mspress/support/search.asp.

ROM, please send them to Microsoft Press

Microsoft Support Network Sales at (800) 936-3500

Trang 27

You are also invited to visit the Microsoft Press World Wide Web site atthe following location:

http://www.microsoft.com/mspress/

You’ll find descriptions for the complete line of Microsoft Press books,information about ordering titles, notice of special features and events,additional content for Microsoft Press books, and much more

You can also find out the latest in Microsoft NET software developmentsand news from Microsoft Corporation by visiting the following Web site:

http://msdn.microsoft.com/net

Check it out!

Trang 28

Part I: Introducing Microsoft Visual C# and Visual Studio NET

Trang 30

Download CD Content

Trang 31

declare variables and how to use operators such as the plus sign (+) andthe minus sign ( ) to create values You’ll see how to write methods andpass arguments to methods You’ll also learn how to use selection

statements such as if and iteration statements such as while Finally,

you’ll understand how C# uses exceptions to handle errors in a graceful,easy-to-use manner These topics form the core of C#, and from thissolid foundation you’ll progress to more advanced features in Part 2through Part 6

Trang 32

Beginning Programming with the Visual Studio NET Environment

Visual Studio NET is a tool-rich programming environment containing allthe functionality you’ll need to create large or small C# projects (You caneven create projects that seamlessly combine modules from differentlanguages.) In the first exercise, you’ll start the Visual Studio NET

3 On the File menu, point to New, and then click Project The NewProject dialog box opens This dialog box allows you to create anew project using various templates such as Windows

Application, Class Library, and Console Application that specifythe type of application you want to create

Trang 33

4 In the Project Types pane, click the Visual C# Projects folder.

5 In the Templates pane, click the Console Application icon (Youmight need to use the Templates pane scrollbar to reveal thisicon.)

6 In the Location field, type C:\Visual C# Step by Step\Chapter 1.

based programs The toolbar is located beneath the menu bar and

provides button shortcuts to run the most frequently used commands.The Code pane displays the source files In a multi- file project, eachsource file has its own tab labeled with the name of the source file Youcan click the tab once to bring the named source file to the foreground inthe Code pane The Solution Explorer displays the names of the filesassociated with the project You can also double-click a filename in theSolution Explorer to bring that source file to the foreground in the Code

Trang 34

Before writing the code, examine the files listed in the Solution Explorerthat Visual Studio NET has created as part of your project:

TextHello.sln This is the top-level solution file, of which there

is one per application Each solution file contains one or moreproject files In the file system, each solution file has the

extension sln In the Solution Explorer, it appears with a namethat is easier to read, such as “Solution ‘TextHello’” in this project

TextHello.csproj This is a C# project file Each project file

contains one or more source files The source files in a singleproject must be written in the same programming language Thisfile type is displayed in the Solution Explorer using only the

project’s name; however, it is stored on the file system with theextension csproj

Class1.cs This is a C# source file You will write your code in

this file It contains some code that Visual Studio NET providesautomatically, which you will examine shortly

AssemblyInfo.cs This is another C# source file You can use

this file to add attributes to your program, such as the name ofthe author, the date the program was written, and so on Thereare other more advanced attributes you can use to modify the

Trang 35

App.ico This is the icon that is associated with the

application All Windows applications that have a user interfacehave an icon that appears minimized on the taskbar when theapplication is running

If you use Windows Explorer to navigate to the C:\Visual C# Step byStep\Chapter 1 folder specified as the project location, you’ll find a foldernamed TextHello (This folder might be hidden depending on your

Windows settings.) This folder contains the files listed in the SolutionExplorer

Trang 36

The Class1.cs file defines a class called Class1 that contains a method called Main All methods must be defined inside a class The Main

method is special— it designates the program’s entry point It must be astatic method (Methods are discussed in Chapter 3, static methods arediscussed in Chapter 7, and the Main method is discussed in Chapter

11.)

Important C# is a case-sensitive language You must spell Main with

a capital M.

In the following exercises, you’ll write the code to display Hello World tothe console; you’ll build and run your Hello World console application;you’ll learn how namespaces are used to partition code elements; andyou’ll learn how to comment your code using XML and then view yourXML comments as HTML documents

Trang 37

for displaying messages on the screen and gettinginput from the keyboard

3 Type a dot after Console An IntelliSense list appears This list contains all the methods, properties, and fields of the Console

methods are discussed in Chapter 3.) Main should now look like

Trang 38

IntelliSense displays the name of every member of a class To the left

of each member name is an icon that depicts the type of member Theicons and their types include the following:

method (discussed in Chapter 3)

property (discussed in Chapter 14)

class (discussed in Chapter 7)

Trang 39

Note An asterisk after the filename in the Code pane

indicates that the file has been changed since it waslast saved There is no need to manually save the filebefore building because the Build Solution commandsaves automatically

2 On the Debug menu, click Start Without Debugging The

program runs in a Command window, writing Hello World to theconsole, as shown in the next illustration

Note Be sure to click Start Without Debugging and not

Start The Start command runs the program in aCommand shell but does not pause at the end of therun

Trang 40

3 Ensure the Command shell has the focus, and then press anykey The Command window closes and you return to the VisualStudio NET programming environment.

4 In the Solution Explorer, click Show All Files Entries named bin and obj appear above the C# source filenames.

These correspond directly to folders named bin and obj in theproject folder These folders are created when you build yourapplication, and they contain the executable version of theprogram and other files used for debugging the program

5 In the Solution Explorer, click the + to the left of the bin entry Anested entry named Debug appears

6 In the Solution Explorer, click the + to the left of the Debugentry Two entries named TextHello.exe and TextHello.pdb

appear

These are files in the bin\Debug folder The Solution Explorershould now look like the following illustration:

Ngày đăng: 25/03/2019, 16:43

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN