Download: Beginning ASP.NET 1.1 with Visual C#® .NET 2003 Chris Ullman John Kauffman Chris Hart Dave Sussman Daniel Maharry Wiley Publishing, Inc.

Beginning ASP.NET 1.1 with Visual C#® .NET 2003 Chris Ullman John Kauffman Chris Hart Dave Sussman Daniel Maharry Wiley Publishing, Inc. Beginning ASP.NET 1.1 with Visual C#® .NET 2003 Beginning ASP.NET 1.1 with Visual C#® .NET 2003 Chris Ullman John Kauffman Chris Hart Dave Sussman Daniel Maharry Wiley Publishing, Inc. Beginning ASP.NET 1.1 with Visual C#® .NET 2003 Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada Library of Congress Card Numb...
Author: Walton Shared: 7/30/19
Downloads: 824 Views: 4960

Content

Beginning ASP.NET 1.1

with Visual C#® .NET 2003 Chris Ullman John Kauffman Chris Hart Dave Sussman Daniel Maharry Wiley Publishing, Inc., Beginning ASP.NET 1.1 with Visual C#® .NET 2003,

Beginning ASP.NET 1.1

with Visual C#® .NET 2003 Chris Ullman John Kauffman Chris Hart Dave Sussman Daniel Maharry Wiley Publishing, Inc.,

Beginning ASP.NET 1.1 with Visual C#® .NET 2003

Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada Library of Congress Card Number: 2004100135 ISBN: 0-7645-5708-4 Manufactured in the United States of America 109876543211B/RW/RS/QU No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permis- sion of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8700. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, Email: email is hidden. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEY MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD CONSULT WITH A PROFESSIONAL WHERE APPROPRIATE. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES. For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.,

About the Authors Chris Ullman

Chris Ullman is a freelance Web developer and technical author who has spent many years stewing in ASP/ASP.NET, like a teabag left too long in the pot. Coming from a Computer Science background, he started initially as a UNIX/Linux guru, who gravitated towards MS technologies during the summer of ASP (1997). He cut his teeth on Wrox Press ASP guides, and since then he has written over 20 books, most notably as lead author for Wrox's bestselling Beginning ASP/ASP.NET series, and has contributed chapters to books on PHP, ColdFusion, JavaScript, Web Services, C#, XML and other Internet-related technologies too esoteric to mention, now swallowed up in the quicksands of the dot.com boom. Quitting Wrox as a full-time employee in August 2001, he branched out into VB6 programming and ASP development, maintaining a multitude of sites from http://www.cuasp.co.co.uk, his "work" site, to http://www.atomicwise.com, a selection of his writings on music and art. He now divides his time between being a human punchbag for his 29-month-old son Nye, composing electronic sounds on bits of dilapidated old keyboards for his music project Open E, and tutoring his cats in the art of peaceful co-existence, and not violently mugging each other on the stairs. Chris Ullman contributed Chapters 1, 14, 15, 16, 17, and Appendix E to this book.

John Kauffman

John Kauffman was born in Philadelphia, the son of a chemist and a nurse. He received his degrees from The Pennsylvania State University, the colleges of Science and Agriculture. His early research was for Hershey foods in the genetics of the chocolate tree and the molecular biology of chocolate production. Subsequently, he moved to the Rockefeller University, where he cloned and sequenced DNA regions that control the day and night cycles of plants. Since 1997, John has written ten books, six of which have been on the Amazon Computer Best Seller List. His specialty is programming Web front-ends for enterprise-level databases. In his spare time, John is an avid sailor and youth sailing coach. He represented the USA in the sailing World Championship of 1985 and assisted the Olympic teams of Belgium and China in 1996. He also enjoys jazz music and drumming and manages to read the New Yorker from cover-to-cover each week. My portions of this book are dedicated to the instructors of two drum and bugle corps. These men taught me about precision, accuracy, and discipline: Ken Green and John Flowers of the Belvederes 1976 and Dennis DeLucia and Bobby Hoffman of the Bayonne Bridgemen 1978. John Kauffman contributed Chapters 2, 3, 4, 5, 6, and Appendix B to this book.,

Chris Hart

Chris Hart is a full-time .NET Developer and part-time author who lives in Birmingham (UK) with her husband James. While she's most at home in the world of the Web, she's recently been working with the .NET Compact Framework. In her spare time, Chris spends much of her time playing with beta technologies, and then attempting to write about them. Chris has contributed many chapters to a variety of books, including Beginning ASP.NET (Wrox Press), Beginning Dynamic Websites with ASP.NET Web Matrix (Wrox Press), and most recently, A Programmer's Guide to SQL (Apress). When she gets away from computers, Chris enjoys travel, especially when it involves driving along narrow winding roads to get to out-of-the-way parts of Scotland. She dreams of building her own house somewhere where she can keep a cat. Chris Hart contributed Chapters 10, 11, 12, 13, and Appendices C and D to this book.

Dave Sussman

Dave Sussman is a writer, trainer, and consultant, living in the wilds of the Oxfordshire countryside. He's been working with ASP.NET since before it was first released and still isn't bored with it. You can contact him at email is hidden. Dave Sussman contributed Chapters 7, 8, and 9 to this book.

Daniel Maharry

Dan Maharry is a freelance writer, reviewer, speaker, and editor who has, in no particular order, taught English, Math, and Guitar, directed, crewed, acted in, and produced several plays and short films, been a film and music columnist for four years, co-founded ASPToday.com, rewritten his own at HMobius.com several times, opened an office in India, variously edited, reviewed, and written pieces of over 40 programming books, qualified as a sound engineer, and consumed enough caffeine in his lifetime to keep most of China awake for a week. Occasionally, he sleeps. Sometimes. Contact him at email is hidden. "With deep-felt love to Jane, and in memoriam to John Kauffman's father." Dan Maharry contributed Chapters 5 and 6 to this book.,

Credits

Authors Executive Editorial Director Chris Ullman Mary Bednarek John Kauffman Chris Hart Project Coordinator Dave Sussman Mary Richards Daniel Maharry Project Manager Senior Acquisitions Editor Ami Frank Sullivan Jim Minatel Senior Production Manager Vice President & Executive Group Fred Bernardi Publisher Richard Swadley Editorial Manager Mary Beth Wakefield Vice President and Executive Publisher Bob Ipsen Book Producer Peer Technical Services Pvt. Ltd. Vice President and Publisher Joseph B. Wikert,

Contents Introduction xxi Chapter 1: Getting Started with ASP.NET 1

What Is a Static Web Page? 2 How Are Static Web Pages Served? 3 Limitations of Static Web Pages 4 What Is a Web Server? 5 How Are Dynamic Web Pages Served? 6 Client-Side Dynamic Web Pages 6 Server-Side Dynamic Web Pages 7 What Is ASP.NET? 9 How Does ASP.NET Differ from ASP? 9 Using C# with ASP.NET 10 I'm Still Confused about ASP, ASP.NET, and C# 11 The Installation Process 11 Which Operating System Do You Have? 11 Prerequisites for Installing ASP.NET 12 Try It Out Installing MDAC 2.8 13 Installing ASP.NET and the .NET Framework 13 Try It Out Installing the .NET Framework Redistributable 14 Installing Web Matrix 15 Try It Out Installing Web Matrix 16 Configuring Web Matrix to Run with .NET Framework 1.1 18 Try It Out Configuring Web Matrix 18 Running Web Matrix and Setting Up the Web Server 19 Try It Out Starting the Web Server 19 ASP.NET Test Example 25 Try It Out Your First ASP.NET Web Page 25 ASP.NET Troubleshooting 28 Page Cannot Be Displayed: HTTP Error 403 29 Page Cannot Be Found: HTTP Error 404 30 Web Page Unavailable While Offline 31 I Just Get a Blank Page 31 The Page Displays the Message But Not the Time 31 I Get an Error Statement Citing a Server Error 32 I Have a Different Problem 33 Summary 33,

Contents Chapter 2: Anatomy of an ASP.NET Page 35

What Is .NET? 35 From Your Code to Machine Code 37 Introducing Two Intermediate Languages 37 Objects 38 The .NET Base Classes 39 The Class Browser 40 How ASP.NET Works 41 Saving Your ASP.NET Files with an ASPX Suffix 42 Inserting ASP.NET Code into Our Web Pages 42 Try It Out Inserting Server-Side (ASP.NET) Code 44 Try It Out Interweaving ASP.NET Output with HTML 49 ASP.NET in Action 51 Binding to a Database 51 Try It Out Binding to a Database 51 Binding to a Simple XML File 54 Try It Out Binding to a Simple XML Document 54 Summary 57 Exercises 58

Chapter 3: Server Controls and Variables 59

Forms 60 Web Pages, HTML Forms, and Web Forms 60 Request and Response in Non-ASP.NET Pages 61 Where ASP.NET Fits in with the .NET Framework 63 The
Tag in ASP.NET 64 Using ASP.NET Server Controls 64 65 Try It Out Using the Control 67 Modifying ASP.NET Controls 68 69 Try It Out Using the Control 69 73 Try It Out Using the Control 73 75 Try It Out Using the Control 75 and 77 Try It Out Using the Control 78 and 79 Try It Out Using the Control 80 Storing Information in C# Variables 82 Declaring Value Type Variables 82 Try It Out Using Variables 83 Datatypes 86 Numeric 86 Text Datatypes 88 Other Datatypes 89 Naming Variables 90 x,

Contents

Variable Scope 91 Try It Out Creating Block and Function-Level Variables 92 Constants 97 Conversion Functions 97 Arrays 98 Try It Out Using Arrays 99 Data Collections 103 ArrayList 103 Try It Out Using an ArrayList 105 Hashtables 106 Try It Out Using Hashtables 108 SortedList 110 Summary 111 Exercises 112

Chapter 4: Control Structures and Procedural Programming 113

Operators 113 Assignment Operator 114 Arithmetic Operators 114 Try It Out Tax Calculator Using Arithmetic Operators 115 String Concatenation 118 Numeric Comparison Operators 119 Logical Operators 120 Try It Out Tax Calculator Using Logical Operators 122 Control Structures 125 Overview of Branching Structures 125 Overview of Looping Structures 126 Overview of Jumping Structures 126 Uses of Control Structures 127 Branching Structures 128 The if Structure 129 Try It Out Using the if Structure 134 The switch Structure 138 Try It Out Using the switch Structure 141 Looping Structures 144 The for Loop Structure 144 Try It Out Using the for Loop 146 The while Loop 148 Try It Out Using the while Loop 150 The do...while Structure 151 Try It Out Using do...while 152 The foreach...in Loop 155 Summary 156 Exercises 157

Chapter 5: Functions 159

Overview 159 Modularization 160 xi,

Contents

Defining and Using Functions 161 Try It Out Defining and Using a Simple Function 161 Passing Parameters to Functions 164 Try It Out Functions with Parameters 165 Web Controls as Parameters 169 Try It Out Using Web Controls as Parameters 170 Return Values 173 Using Return Values in Your Code 173 Try It Out Handling Function Return Types 175 Value, Reference, and Out Parameters 181 Try It Out Using Value, Reference, and Out Parameters 183 Modularization Best Practices 188 Summary 189 Exercises 190

Chapter 6: Event-Driven Programming and Postback 191

What Is an Event? 192 What Is Event-Driven Programming? 192 HTML Events 193 ASP.NET's Trace Feature 195 ASP.NET Page Events 197 ASP.NET Web Control Events 199 Try It Out Creating Event Handlers with Web Matrix 201 Event-Driven Programming and Postback 202 Try It Out Reacting to Events in HTML and ASP.NET 203 The IsPostBack Test 205 Try It Out Calculator 206 Summary 211 Exercises 212

Chapter 7: Objects 215

Classes and Instances 216 Properties, Methods, and Events 216 Objects in .NET 216 Why Use Objects? 217 Defining Classes 218 Try It Out Creating a Class 218 Property Variables 223 Property Types 224 Try It Out Read-Only Properties 224 Initializing Objects 226 Try It Out Overloading a Constructor 226 Implementing Methods 227 Try It Out Adding Methods to a Class 227 Consolidating Overloaded Methods 230 Advanced Classes 231 xii,

Contents

Shared or Static Properties and Methods 231 Inheritance 232 Try It Out Inheritance 233 Interfaces 237 Try It Out Creating an Interface 238 .NET Objects 243 Namespaces 243 The Class Browser 243 Summary 245 Exercises 245

Chapter 8: Reading from Databases 247

Understanding Databases 247 Tables 248 Normalization 249 SQL and Stored Procedures 251 The Web Matrix Data Explorer 251 Try It Out Connecting to a Database 251 Creating Data Pages 253 Displaying Data Using the Data Explorer 253 Try It Out Creating a Grid 253 Displaying Data Using the Web Matrix Template Pages 256 Try It Out Creating a Data Page 257 Displaying Data Using the Code Wizards 262 Try It Out Creating a Data Page 262 ADO.NET 269 The OleDbConnection Object 271 The OleDbCommand Object 271 Try It Out Using Parameters 273 The OleDataAdapter Object 278 The DataSet Object 278 The DataReader Object 278 Try It Out Using a DataReader 279 Summary 281 Exercises 281

Chapter 9: Advanced Data Handling 283

More Data Objects 283 The DataTable Object 284 The DataRow Object 285 Try It Out The DataTable and DataRow Objects 286 Updating Databases 288 ADO.NET versus ADO 289 Updating Data in a DataSet 289 Try It Out Adding, Editing, and Deleting Rows 289 Updating the Original Data Source 297 Try It Out Auto-Generated Commands 298 Updating the Database 301 xiii,

Contents

Try It Out Updating the Database 302 Updating Databases Using a Command 307 Try It Out Executing Commands Directly 307 Summary 310 Exercises 311

Chapter 10: ASP.NET Server Controls 313

The Wrox United Application 314 ASP.NET Web Controls 315 HTML Server Controls 316 HTML Server Controls versus Web Controls 318 Web Controls 319 Rich Object Model 320 Automatic Browser Detection 320 Properties 320 Events 322 Try It Out Creating an Event Handler 322 Page Lifecycle 324 Page_Load() 325 Event Handling 326 Page_Unload() 326 Understanding Web Controls: The Wrox United Application 327 Try It Out Wrox United Main Page – Default.aspx 328 Intrinsic Controls 331 Try It Out Wrox United – Teams.aspx 332 Data Rendering Controls 340 Try It Out Wrox United – Teams.aspx, Part 2 343 Rich Controls 352 Try It Out Wrox United – Default.aspx, Part 2, the Event Calendar 354 Try It Out Wrox United – Displaying Fixture Details 360 Web Matrix Controls 366 Try It Out Wrox United – Players.aspx and the Web Matrix MX DataGrid 367 Validation Controls 372 Try It Out Wrox United – Registering for Email Updates (Default.aspx) 373 Summary 378 Exercises 378

Chapter 11: Users and Applications 381

Remembering Information in a Web Application 382 Cookies 383 Try It Out Using Cookies 386 Sessions 393 Try It Out Using Session State 395 Applications 404 How Do Applications Work? 405 Try It Out Using Application State 405 Reacting to Application and Session Events 410 Global.asax 410 xiv,

Contents

Try it Out Global.asax – Global Settings 411 Caching 413 Try It Out Wrox United – Caching Objects 415 State Management Recommendations 418 When to Use Cookies 419 When to Use Sessions 419 When to Use Applications 419 When to Use Caching 419 Other State Management Techniques 420 Using Multiple State Management Techniques on a Page 421 Try it Out Wrox United – Adding Some Style! 421 Summary 429 Exercises 430

Chapter 12: Reusable Code for ASP.NET 431

Encapsulation 431 Components 432 Why Use Components? 434 Applying Component Theory to Applications 434 User Controls 435 Try It Out Our First User Control 437 Try It Out Wrox United – Header Control 440 Try It Out Wrox United – Navigation User Control 446 Code-Behind 451 Try It Out Our First Code-Behind File 452 Try It Out Using Code-Behind in Wrox United 457 Summary 459 Exercises 459

Chapter 13: .NET Assemblies and Custom Controls 463

Three-Tier Application Design 464 ASP.NET Application Design 465 .NET Assemblies 466 Try It Out Our First ASP.NET Component 467 What Is Compilation? 470 Try It Out Compiling Our First ASP.NET Component 470 Accessing a Component from within an ASP.NET Page 474 Try It Out Using a Compiled Component 474 XCopy Deployment 476 Accessing Assemblies in Other Locations 477 Writing Code in Other Languages 477 Try It Out Writing a Component in VB.NET 478 Data Access Components 482 Try It Out Encapsulating Data Access Code in a Component 482 Custom Server Controls 489 What Are Custom Controls? 490 Try It Out Our First ASP.NET Custom Control 491 Composite Custom Controls 499 xv,

Contents

Try It Out Wrox United – Custom Composite Control 499 Summary 506 Exercises 507

Chapter 14: Debugging and Error Handling 509

A Few Good Habits 510 Tips on Coding 510 Indent Your Code 511 Structure Your Code 511 Comment Your Code 512 Convert Variables to the Correct Data Types (Validation) 512 Try to Break Your Code 513 Sources of Errors 514 Syntax Errors 514 Try It Out Syntax Error 515 Try It Out Generate a Compiler Error 516 Logical (Runtime) Errors 518 Try It Out Generate a Runtime Error 519 Try It Out Catching Illegal Values 521 Try It Out Using RequiredFieldValidator 524 System Errors 525 Finding Errors 525 Try It Out Viewing the Call-Stack 526 Debug Mode 527 Try It Out Disable the Debug Mode 527 Tracing 529 Try It Out Enabling Trace at the Page Level 529 Try It Out Writing to the Trace Log 532 Handling Errors 535 Try It Out Using try...catch...finally 542 Try It Out Using Page_Error() 548 Error Notification and Logging 550 Try It Out Creating Error Pages 551 Writing to the Event Log 553 Try It Out Writing to the Windows Error Log 554 Mailing the Site Administrator 557 Summary 559 Exercises 559

Chapter 15: Configuration and Optimization 561

Configuration Overview 562 Browsing .config Files 562 The Configuration Files 564 The Structure of the Configuration Files 567 Performance Optimization 574 Caching 574 Try It Out Output Caching 576 The Cache Object 578 xvi,

Contents

Expiring Information in the Cache 581 Try It Out Creating a File Dependency 582 Try It Out Creating a Key Dependency 586 Tips and Tricks 590 Summary 591 Exercises 591

Chapter 16: Web Services 593

What Is a Web Service? 594 Try It Out Creating Our First Web Service 595 HTTP, XML, and Web Services 598 HTTP GET 599 HTTP POST 600 Simple Object Access Protocol (SOAP) 601 Building an ASP.NET Web Service 603 Processing Directive 603 Namespaces 603 Public Class 604 Web Methods 604 Try It Out Creating a Web Service with Multiple Web Methods 605 Testing Your Web Service 607 Try It Out Conversions Test Page 607 Using Your Web Service 608 Try It Out Viewing the WSDL Contract 609 Try It Out ISBN Search Web Service 610 Consuming a Web Service 613 How Does a Proxy Work? 613 Creating a Proxy 615 Try It Out Accessing the ISBN Web Service from an ASP.NET Page 615 Creating a Web Service for the Wrox United Application 618 Try It Out Adding a Results Page 619 Try It Out Creating the Web Service 621 Web Service Discovery 626 Securing a Web Service 627 Username-Password Combination or Registration Keys 627 Try It Out Securing a Web Service with Username and Password 627 Secure Sockets Layer (SSL) 630 IP Address Restriction 630 Web Services Enhancements (WSE) 631 Other Web Services Considerations 631 Network Connectivity 631 Asynchronous Method Calls 631 Service Hijacking (or Piggybacking) 632 Provider Solvency 633 The Interdependency Scenario 633 Summary 633 Exercises 634 xvii,

Contents Chapter 17: ASP.NET Security 635

What Is Security? 636 The ASP.NET Security Model 636 Authentication 637 Implementing Forms-Based Authentication 638 Try It Out Forms-Based Authentication 639 Forms-Based Authentication Using a Database 646 Try It Out Authenticating against a Database 646 Authorization 650 Try It Out Authorization for email is hidden 651 Authentication in Wrox United 653 Try It Out Adding a Login Page to WroxUnited 653 Encryption Using SSL 664 Try It Out Enabling SSL 665 Summary 666 Exercises 666

Appendix A: Exercise Solutions 667

Chapter 2 667 Chapter 3 669 Chapter 4 672 Chapter 5 675 Chapter 6 678 Chapter 7 681 Chapter 8 684 Chapter 9 686 Chapter 10 688 Chapter 11 693 Chapter 12 697 Chapter 13 702 Chapter 14 708 Chapter 15 713 Chapter 16 715 Chapter 17 720

Appendix B: Web Matrix Quick Start 725

What Is Web Matrix? 725 Starting ASP.NET Web Matrix 727 The Screen 727 How to Enter Code 730 Try It Out Code Entry 731 Saving and Viewing Pages 731 Try It Out Formatting Modes, Views, and Serving Pages 733 Reusing Code 735 Try It Out Saving and Using Snippets 735 xviii,

Contents

Class Browser 735 Try It Out Class Browser Property Look-Up 736 What to Study Next 738 Summary 738

Appendix C: The Wrox United Database 741

The Database Design 741 Players 742 Status 742 Teams 743 PlayerTeams 743 Positions 744 Games 744 GameTypes 745 Locations 745 Opponents 746 Fans 746 Installing the Database 747 Installing the Access Database 747 Installing the MSDE Database 747

Appendix D: Web Application Development Using Visual Studio .NET 753

Creating a Web Application Project 754 Features of the Visual Studio .NET Environment 755 Visual Studio .NET Solutions and Projects 756 Files in a Web Application Project 757 Working with Web Pages 757 Compiling and Running Pages 761 Adding Code to the Code-Behind Class 762 Features of Code View 763 Adding Code to Methods 763 Styling Controls and Pages in Visual Studio .NET 769 Working in HTML View 776 Creating User Controls 777 Formatting Blocks of Code 782 Developing the User Control 784 Creating an XML File 786 Adding a User Control to a Page 789 Adding Custom Classes 791 Working with Databases Using the Server Explorer 794 Debugging in Visual Studio .NET 797 Using Breakpoints 798 Fixing Design-Time Errors 799 Suggested Exercises and Further Reading 801 xix,

Contents Appendix E: Installing and Configuring IIS 803

Try It Out Locating and Installing IIS on Your Web Server Machine 803 Working with IIS 806 The Microsoft Management Console (MMC) 806 Testing Your Installation 807 Identifying Your Web Server's Name 807 Managing Directories on Your Web Server 808 Try It Out Creating a Virtual Directory and Setting Up Permissions 810 Permissions 814 Browsing to a Page on Your Web Server 818

Index 825

xx,

Introduction

ASP.NET is a radical update of Microsoft's Active Server Pages (ASP). ASP.NET is a powerful server based technology designed to create dynamic and interactive HTML pages on demand for your Web site or corporate intranet. Its design improves upon nearly every feature of classic ASP, from reducing the amount of code you need to write to giving you more power and flexibility. ASP.NET is a key element in Microsoft's .NET Framework, providing Web-based access to the immensely powerful .NET development environment. It allows us to create Web applications in a new, flexible way by placing commonly used code into reusable controls of various kinds that can fire events initiated by the users of a site. ASP.NET branches out into many other technologies, such as Web services, ADO.NET, custom controls, and security. We will briefly touch upon its relationship with these fields throughout the book to provide a solid, comprehensive understanding of how ASP.NET can benefit your work in a practical way. ASP.NET 1.1 itself is a fairly light update to the complete wholesale changes that occurred in ASP.NET 1.0. This book by and large covers features that are available in both 1.0 and 1.1, but it covers the pertinent new features of 1.1 in additional depth, which will be of interest to both the novice and experienced users. So if you are already running ASP.NET 1.0, you will be expected to upgrade to 1.1. By the end of this book you will be familiar with the anatomy of ASP.NET 1.1 and be able to create powerful, secure, and robust Web sites that can collect and work with information in a multitude of ways to the benefit of both you and your users.

Who Is This Book For?

The purpose of this book is to teach you from scratch how to use ASP.NET to write Web pages and Web applications in which content can be programmatically tailored each time an individual client browser calls them up. This not only saves you a lot of effort in presenting and updating your Web pages, but also offers tremendous scope for adding sophisticated functionality to your site. As ASP.NET is not a programming language in its own right, but rather a technology (as we shall explain in the book), we will be teaching some basic programming principles in Chapters 2 to 7 in C#, our chosen language for implementing ASP.NET. This book is therefore ideal for somebody who knows some basic HTML but has never programmed before, or somebody who is familiar with the basics of old style ASP, but hasn't investigated ASP.NET in any detail. If you are an experienced programmer looking for a quick crash course on ASP.NET, or somebody who's worked extensively with ASP, we suggest that you refer to Professional ASP.NET 1.1 Special Edition, Wiley ISBN: 0-7645-58900 instead, as you'll most likely find that the early chapters here just reiterate things you already know. If are not familiar with HTML, then we suggest that you master the basics of building Web pages before moving on to learning ASP.NET.,

Introduction What Does This Book Cover?

This book teaches everything the novice user needs to know, from installing ASP.NET and the relevant bits and pieces to creating pages and putting together the concepts to create a whole application using ASP.NET 1.1. Although ASP.NET 1.1 isn't a huge update on version 1.0, this book has been considerably overhauled since edition 1.0. Plenty of the old chapters have been removed and many new ones introduced. We've removed three chapters because we wanted to simplify the experience of learning ASP.NET. We've created a brand new case study – an amateur sports league Web site – which is then used throughout the latter chapters in the book to provide a more practical guide on how to implement ASP.NET applications. If you see the previous edition, you will find this one to be more cohesive, aimed towards the complete novice and the developer with some ASP experience, and written with the benefit of hindsight from experienced developers who have have been employed in creating ASP.NET applications. We trust that you will find it a great improvement over the last, just as every new edition should be. In the course of this book you will learn: ❑ What is ASP.NET ❑ How to install ASP.NET and get it up and running ❑ The structure of ASP.NET and how it sits on the .NET Framework ❑ How to use ASP.NET to produce dynamic, flexible, interactive Web pages ❑ Basic programming principles such as variables, controls structures, procedural programming, and objects ❑ How to use ASP.NET to interface with different data sources, from databases to XML documents ❑ What ready-made controls ASP.NET offers for common situations ❑ How to create your own controls ❑ How to debug your ASP.NET pages ❑ How to deal with unexpected events and inputs ❑ How to create your own Web application ❑ How to integrate your applications with Web services and how to create your own ❑ Some simple security features and how to create a login for an application

How This Book Is Structured

Here is a quick breakdown of what you will find in this book: ❑ Chapter 1 – Getting Started with ASP.NET: In the first chapter, we introduce ASP.NET and look at some of the reasons that you'd want to use server-side code for creating Web pages as well as the technologies that are available to do so. This done, we spend the bulk of the chapter xxii,

Introduction

explaining the ASP.NET installation process in detail, how to install a Web server to run ASP.NET on (we will be using the Web server that accompanies Web Matrix), along with the ancillary installation of MDAC. We finish up with a simple example ASP.NET page to check that our installation is working correctly. ❑ Chapter 2 – Anatomy of an ASP.NET Page: Having completed the installation in the previous chapter, we consider the structure of an ASP.NET page and the way that it functions in relation to the .NET Framework. We use examples to demonstrate how the ASP.NET module parses the page. ❑ Chapter 3 – Server Controls and Variables: After familiarizing ourselves with the basics of ASP.NET controls, this chapter considers the use of variables for holding data in C#. We look at how variables are implemented, what they can contain, and how they can be placed into your ASP.NET pages. ❑ Chapter 4 – Control Structures and Procedural Programming: This chapter takes a whirlwind tour of the key building blocks of C# in the context of an ASP.NET page. We learn how to make our ASP.NET pages more responsive through the use of C# branching and looping structures that enable us to control the order in which our program's statements execute. ❑ Chapter 5 –Functions: We cover how the modularization and reusable ASP.NET code works in this chapter. We look at functions and how they are used together with Web controls. We learn how to pass parameters within ASP.NET pages and the different ways in which ASP.NET can handle them. ❑ Chapter 6 – Event-Driven Programming and Postback: We talk about how ASP.NET revolves around an event-driven model, and how things occur in strict order and ways in which the ASP.NET page can react to user intervention. We also look at the concept of postback and how it is used to send information back from the user to the Web server for preserving the 'state' of a page. ❑ Chapter 7 – Objects: This chapter deals with the thorny subject of objects. ASP.NET pages derive a great deal of their flexibility and power from the object-oriented way they are structured. This chapter introduces concepts such as properties, methods, constructors, collections, and overloading with many examples related to real-world objects to aid your understanding. We also discuss the concepts that make objects very powerful to use such as inheritance and encapsulation, and how they greatly reduce the amount of code you need to use. ❑ Chapter 8 – Reading from Databases: At this point in the book we're familiar with the basic anatomy of ASP.NET pages and objects, so we branch out to look at ADO.NET in the context of ASP.NET. Most specifically we look at the use of the Connection and Command objects for opening data sources and retrieving information into a DataSet. ❑ Chapter 9 – Advanced Data Handling: After mastering the basics of reading data in the previous chapter, we take things further by looking in detail at the way we can manipulate the information in a DataReader and DataSet and store the results back to the data source. ❑ Chapter 10 – ASP.NET Server Controls: This chapter explains how ASP.NET server controls derive their properties and methods from the various classes and objects that make up the .NET Framework. It explains the syntax required to make their functionality available along with a look at the benefits that these controls can give. We also start to create the Wrox United application case study that is used throughout the rest of the book. ❑ Chapter 11 – Users and Applications: This chapter deals mainly with the process of tracking users across pages. We look at the objects that ASP.NET uses to enable this. We also tie this into our case study by creating the facility for adding valid email addresses and passwords to a site via xxiii,

Introduction

an admin interface, and then we play the part of one of those users logging in and viewing pages. ❑ Chapter 12 – Reusable Code for ASP.NET: Here we consider the great benefits that can be achieved by encapsulating our code to make it more maintainable. Firstly, we cover the idea of user controls designed to store sections of your ASP.NET code that are repeated on multiple pages of your site. Then we go on to consider the idea of code-behind, where the Since the <%@ Page language> tag specifies C# .NET as our language of choice, the language attribute of the All code enclosed within the ,

Chapter 2

We won't go into detail explaining this format; suffice to say that when the page is loaded, the code block that we've labeled Page_Load() is triggered automatically. Any code we want to run when the page starts up should be located here.

Try It Out Inserting Server-Side (ASP.NET) Code

In this example, we're only concerned with how we insert code and not with how the ASP.NET code works, so the code is trivial. This example demonstrates how Web pages are affected by the placement of ASP.NET code. 1. Let's start with a file containing just HTML – no code for ASP to execute. Open Web Matrix and create a new ASPX page named messageHTML.aspx in your test directory. If you've followed the steps from Chapter 1, this will be C:\BegASPNET11\Ch02\. Go to All view, remove all existing code, and type in the following code: Inserting ASP.NET code Example Line1: First HTML Line
Line2: Second HTML Line
Line3: Third HTML Line
2. Click on the arrow icon to run messageHTML.aspx from Web Matrix or press the F5 key. An instance of Internet Explorer appears as shown in Figure 2-2: Figure 2-2 3. Now go back to Web Matrix and place the following code at the top of the page in the All view: <%@ Page Language="C#" debug="true"%> Inserting ASP.NET code Example Line1: First HTML Line
Line2: Second HTML Line
Line3: Third HTML Line
The tags), and paste it at the end of the body section as follows: Inserting ASP.NET code Example Line1: First HTML Line
Line2: Second HTML Line
Line3: Third HTML Line
,

Chapter 2

6. Call up messageASPXbottom.aspx in your browser. Notice that the browser still displays the ASP.NET code first, as shown in Figure 2-4: Figure 2-4

How It Works

The first thing to note is that although this is ASP.NET code, we're not actually creating a dynamic Web page that can display different pages to different users. All we're doing is demonstrating the order in which ASP.NET code and HTML are executed. The next point is that all three examples use the .aspx suffix despite the fact that the first page, messageHTML.aspx, contained only HTML code. So, as far as the Web server is concerned, all three pages are ASP.NET pages and will be checked for script to be executed. This also demonstrates that HTML is treated in the same way in both pure HTML pages and ASP.NET pages. The code in the first page, messageHTML.aspx, just displays some HTML lines and some plain text. When the code is parsed in your browser, the lines are displayed in order, as you would expect. Inserting ASP.NET code Example Line1: First HTML Line
Line2: Second HTML Line
Line3: Third HTML Line
,

Anatomy of an ASP.NET Page

In the second Web page, messageASPXtop.aspx, we have a combination of some pure HTML, some plain text, and a little server-side script. By using runat="server", we specified that the following script should be processed on the server, before the page is sent to the browser: Whenever ASP.NET loads a page, it executes any code contained within the Page_Load() method first. So if you place code that writes to the page in this method, that text will always precede any text from the HTML part of the file even if you had physically put the code after the HTML lines (as in messageASPXBottom.aspx). The ASP.NET code uses a Response.Write statement to display three ASP.NET lines. We'll talk more about Response.Write in Chapter 3. Take a moment here to understand another important ASP.NET concept. Open messageHTML.aspx in your browser and look at the source (in Internet Explorer, go to View | Source). You will see a page that starts with the following line: First ASP.NET Line
Second ASP.NET Line
Third ASP.NET Line
... The ASP.NET module on the server interprets the code Response.Write and performs that writing to the page on the server. IIS only sends plain HTML to the browser. Thus, no special plug-ins or interpreters are needed on the browser. Because no browser modifications are needed, any browser can display the results of ASP.NET code. Finally, we moved the ASP.NET code to follow the HTML lines. The browser still displays the ASP.NET code first. The Web server first scans the file to see if there is a ... HTML code here ...

Try It Out Interweaving ASP.NET Output with HTML

You may still be wondering, "How do we intersperse static content with dynamic content if the code and the HTML are separated like this?" Let's take a quick look at how to get round this problem; you'll soon realize that this doesn't restrict us nearly as much as you might think. 1. Enter the following code into a new page and save it as messageServerControl.aspx: Inserting ASP.NET code Example First HTML Line

Second HTML Line
,

Chapter 2

2. Point your browser to messageServerControl.aspx to see Figure 2-6: Figure 2-6

How It Works

You might have noticed that we completely avoided the use of <%...%> delimiters to create inline code blocks. First, we have a difference in the HTML code. Notice that we have added a special tag, which creates an HTML tag with the id set to message: Inserting ASP.NET code Example First HTML Line

Second HTML Line
This named object is now available for manipulation by our ASP.NET code. Instead of having Response.Write statements that send text to the browser as we did in the previous example, we have code that sets a property (or attribute) of a Label control. This contains text that the label will display: ,

Anatomy of an ASP.NET Page

First, the following HTML has a special tag known as a server control created by the . That control has a runat="server" attribute, which instructs that the code be executed by the ASP.NET module in IIS and not on the browser:
Second, we have a method named Page_Load() that changes the text of the label from nothing to "The ASP.NET line". This leaves us with much cleaner code that is easier to write and easier to maintain.

ASP.NET in Action

This has been a very theoretical chapter until now. Let's now see a couple of examples. Since we've still not looked at much of ASP.NET code, the commands in these examples won't make a lot of sense at this stage. However, you will get an overview of the basic tasks that the code performs, and later in the book you can build up a more detailed picture of the syntax as your understanding grows. We'll do two exercises, of which both read data and display the information on your ASP.NET page. The first reads from an Access (.mdb) file, and the second from an XML file.

Binding to a Database

For most people, the key reason for using ASP.NET is the ability to connect a Web page to a database, and then read and update data from the browser. ASP.NET does this task more easily than classic ASP. In classic ASP, binding a page to data took many lines of code. ASP.NET provides a set of server controls that significantly cuts the amount and complexity of coding.

Try It Out Binding to a Database

1. In this exercise, we'll use one of the example databases provided with the .NET Framework, the grocertogo database (MS Access format), to build a quick Web page that allows us to browse the contents of the Products table. There's a copy of grocertogo in the code download from http://www.wrox.com/, but you'll have to alter the path name to point to where you've saved it on your system. If you don't have the grocertogo database, modify the lines beginning with strConnect += @"Data Source= to point to any database that you have on your system. 2. If you cannot find the database, search your drives for grocertogo.mdb. Alternatively, you can download it from http://www.wrox.com/. If you want to become familiar with the database, you can open it in Access but that is not necessary for this exercise. Copy the .mdb file into the C:\BegASPNET11 folder. As we will use it for more then one chapter, do not store it in the Ch02 subfolder. 3. Open Web Matrix, create DataControlMDB.aspx, and type in the following: <%@ Page Language="C#" %> <%@ import Namespace="System.Data" %> <%@ import Namespace="System.Data.OleDb" %> Data Grid Control example 4. Open DataControlMDB.aspx in your browser as shown in Figure 2-7: Figure 2-7,

Anatomy of an ASP.NET Page How It Works

The ASP.NET code looks quite daunting, but we can understand it when we examine the different sections. First, let's look at the tag: We have a tag here that creates a DataGrid object named DataGrid1 in the page. This will be an object that we can manipulate in our code, but when the page is requested by a user and built by the ASP.NET module in IIS, the DataGrid object will create in its place the , , and
,
HTML tags so that a table appears in the browser. Now let's go back up in the code and examine the Page_Load() method. We'll not enter into a detailed discussion about all of these lines (see Chapters 8 and 9). However, we can break it into several parts. We start by establishing our language. Second, we import the namespaces (collections of objects) that we will need for working with the data: <%@ Page Language="C#" debug="true"%> <%@ import Namespace="System.Data" %> <%@ import Namespace="System.Data.OleDb" %> Then we enter our function and create some variables to hold information that we will need: void Page_Load(Object sender, EventArgs e) { OleDbConnection objConnection; OleDbDataAdapter objCommand; String strConnect; String strCommand; DataSet DataSet1 = new DataSet(); Next, we create a string of text in a variable called strConnect, which will inform the connection what kind of database we are using (the Microsoft Jet provider in the case of Access), where to find the file, and how to handle security settings: strConnect = @"Provider=Microsoft.Jet.OLEDB.4.0;"; strConnect += @"Data Source=C:\BegASPNET11\grocertogo.mdb;"; strConnect += @"Persist Security Info=false"; Next, ASP.NET needs query that it can use to retrieve data from the database. This is written as a SQL statement. You don't need to know SQL at this point because the general syntax is obvious. We want to read (SELECT) values from two fields (ProductName and UnitPrice) located in the Products table: strCommand = "SELECT ProductName, UnitPrice FROM Products"; The next three lines take the information above and use it to create two objects (Connection and Command) and fill our DataSet1 object with data read from grocertogo:,

Chapter 2

objConnection = new OleDbConnection(strConnect); objCommand = new OleDbDataAdapter(strCommand, objConnection); objCommand.Fill(DataSet1, "products"); Lastly, we use two lines to instruct the DataGrid (from the HTML section) to use DataSet1 as the source of its values as follows: DataGrid1.DataSource=DataSet1.Tables["Products"].DefaultView; DataGrid1.DataBind(); } As always, with ASP.NET, this code is interpreted on the server by the ASP.NET module of IIS to render the page from pure HTML, which sent to the browser. If you open datacontrol.aspx in your browser and then view the source, you will see only standard HTML table tags but none of the ASP.NET code.

Binding to a Simple XML File

ASP.NET is not limited to connecting with relational databases. We'll now look at how we can use the data controls to connect to a short XML document. This book does not go into the theory of XML. In case you are not familiar with the standard, XML is a format for holding data normally in a text file. The file is self-describing in that each piece of data has a label that identifies its classification in the scheme of records and fields. XML is becoming the standard for data exchange. To learn more about XML, refer to Beginning XML, 2nd Edition (ISBN 0-7645-4394-6) by Wrox Press. Let's create a short XML document and then an ASPX page that demonstrates the technique to create a DataGrid control and bind it to the contents of an XML document. Overall, the procedure is even easier than connecting to a database.

Try It Out Binding to a Simple XML Document

1. Open up your Web page editor and create a document named artists.xml in your Ch02 folder. Type in the following XML document. Alternatively, you can download the file from http://www.wrox.com/: Vincent Van Gogh Dutch Post Impressionism 30th March 1853 Paul Klee Swiss Abstract Expressionism 18th December 1879 Max Ernst German ,

Anatomy of an ASP.NET Page

Surrealism 2nd April 1891
2. Keeping your Web page editor open, create a second file named DataControlXML.aspx containing the following lines: <%@ Page Language="C#" runat="server" debug="true"%> <%@ import Namespace="System.Data" %> <%@ import Namespace="System.Xml" %> Data Grid Control example 3. View this page in your browser; the result should look like Figure 2-8: Figure 2-8

How It Works

Our XML file is pretty much like a database table. We've kept it simple, so that you can see what is happening. The first line notifies users that the file is an XML file. An overall pair of tags, , encapsulates all of the data:,

Chapter 2

... There are three artists. Each artist's individual entry is held with a single set of item tags structured as follows: Vincent Van Gogh Dutch Post Impressionism 30th March 1853 Within each artist, we can see four elements (which are like fields or columns in other data systems), one each for name, nationality, movement, and birthdate. Notice that each data value is inside a pair of tags and that the same set of tag names is used for each artist. Even without knowledge of XML, it is easy to see how the file is organized. Now let's look at the datacontrolXML.aspx ASP.NET page. At the top of the page, we must establish the language and import the namespaces that hold objects we will need to work with XML data: <%@ Page Language="C#" runat="server" debug="true"%> <%@ import Namespace="System.Data" %> <%@ import Namespace="System.Xml" %> Next, jump down to the , where we use the DataGrid control to format and display the information as an HTML table. Again, the code is very neat and simple. It is crucial to include the attribute runat="server" for ASP.NET to work. Furthermore, every control must have a name (specified using the id attribute); in this case DataGrid1. Last, we will examine the ASP.NET code. Because it is in the Page_Load() method, it is automatically executed when the page is created. The first few lines record the name of the file into a variable: As you can see, reading from an XML file is even simpler than the code we used for connecting to a database. However, at this point do not be concerned about the details of each line of code. We will discuss the exact meaning of each statement in Chapters 8 and 9.

Summary

This chapter has been mostly theoretical, but contained simple applications ranging from a simple display of text up to two types of data connections. You should now understand several basic points about .NET and ASP.NET. The .NET Framework is a guideline and standard for the tools that Microsoft produces for programmers. It is flexible across languages and is suitable for both desktop and Web-based applications. .NET is based on objects, a programming convention which puts related code together in a structure that represents an entity in the real world. The model from which objects are copied is called a class and a group of related classes is called a namespace. ASP.NET is a module that adds on to IIS. ASP.NET checks pages for code and executes that code to create an HTML page. The resulting pages are pure HTML and require no add-ins for the browser because of which they can be viewed on any browser. After writing an ASP page, it is partially compiled to MSIL and stored on the server. When requested, the page is run through the CLR for a final compilation. This two-stage compilation gives both performance advantages and optimization for different servers. When we write an ASP.NET page, we must include several key parts, such as: ❑ The .aspx filename extension ❑ A directive to import namespaces and a directive designating the language ❑ HTML and text ❑ ASP.NET controls such as that have an id and runat="server" attributes ❑ Code scripts Although scripts can be designated in line by <% %>, it is better to designate them by If you run the example again, you'll see that the output has changed to that shown in Figure 3-4: Figure 3-4 The Page_Load() section is executed whenever the page is requested or refreshed; we will discuss this in more detail in Chapter 6. Let's ignore this statement for now, it's the code it contains that's important. The following line refers to the text contained by your first control. Here we're changing the Text attribute of Message1 to Vervain. Message1.Text = "Vervain",

Server Controls and Variables

This example allowed you to change the contents of an control by modifying code. Future chapters will discuss how to modify the values in more sophisticated ways, including changing the text to be values read from a database. All of the ASP.NET control attributes (properties) can be changed in the code in the same way. For example: Message1.Text = "Vervain" Message1.backcolor = Drawing.color.red Message1.font.italic=true Message1.font.size = FontUnit.large Before moving onto the control, let's pause to look at its HTML form control equivalent. Dropdown listboxes are a series of The control will produce the same output when coded in the following way: Madrid Oslo Lisbon The three important differences between the ASP.NET control and the HTML form control are: ❑ The tag directly replaces the 2. Run this file in your browser and the page should be displayed as shown in Figure 3-5: Figure 3-5 3. Select Oslo and click on Submit Query. 4. Now click on View | Source. You should see something like the following; don't worry if your version isn't exactly the same – the code is tailored to your personal browser: Drop Down List Example You have selected Oslo
Which city interests you?

How It Works

As you can see, everything that has been sent to the browser is HTML code and text; there are no proprietary tags or script to run on the browser. Also note that this is a one-page solution, in contrast to the old two-page approach with HTML forms. This form page submits to itself. To explain how it works, we're going to reference the source code that we can view in our browser, and compare it to our original ASPX code. Let's start from the
section of the script. The attribute is set that tells ASP.NET to execute the form on the server. If you compare this line to what has been returned to the browser, you can see a large difference: ASP.NET has generated four new attributes. The name and id attributes serve a similar purpose - to uniquely identify the form. However, it's the other two that are of interest. HTML forms require a page to receive the form data and a method of transmission. We didn't specify either of these in our ASPX code, so ASP.NET specified them for us by default to be the same page. It also specifies the POST method by default. The main item on the form is the control: Which city interests you?
Madrid Oslo Lisbon It's crucial to note how this is rendered. If you view the source code that's sent back to the browser, you should see the following: Which city interests you?
It's the first line that is of particular note. It contains a hidden control called VIEWSTATE, which contains an encoded representation of the overall state of the form when last submitted. This is used by ASP.NET to keep track of all the server control settings from one page refresh to another. Without this record of the state of the page controls, the dropdownlist would revert to its default setting every time you submitted a value. It may not be immediately obvious how useful this can be – consider a non-ASP.NET registration form in which you have to enter a full set of personal details. If you forget to fill in a required field, and then submit the form, you may well be prompted with the same empty form again. ASP.NET solves this problem for us with the VIEWSTATE; all that data is automatically persisted through to the refreshed page, and you have barely raised a finger to code this functionality! The string of characters contained in the value attribute is a condensed and encoded depiction of each control on the page as it was when the submit button was clicked. When this information is sent back to IIS on a subsequent submit, it is decoded and ASP.NET can work with the values. The second half is just a 2. Run this page in your browser, use the Ctrl or Shift key to select multiple choices, and then click on Submit Query to see the page as depicted in Figure 3-6: Figure 3-6

How It Works

The controls in this example have hardly changed from the previous listpage.aspx example. All we've done is switched from DropDownList to a ListBox and set the selectionmode attribute to allow multiple selections: However, we've had to completely overhaul the ASP.NET code to accommodate the possibility of several cities selected. We will build the list to be displayed in a variable named msgCitiesList: string msgCitiesList = "";,

Server Controls and Variables

Then for each possible city choice, we check if it was selected; if yes, we add the city name to the msgCitiesList variable. The trick here is to understand that the choices are numbered (indexed) in the listbox, and if they are selected, the selected property is switched to true. Finally, we assign the value of the variable msgCitiesList (a string of text and HTML) to the Text attribute of the Message label so that it can be seen on the page. This is slightly more complicated than handling the results of single selections. This control is ASP.NET's version of the HTML and