beginning visual basic - download.e-bookshelf.de · chapter 1: welcome to visual basic 2015 1...
TRANSCRIPT
Beginning Visual Basic® 2015
introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxvii
chapter 1 Welcome to Visual Basic 2015 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
chapter 2 The Microsoft .NET Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
chapter 3 Writing Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
chapter 4 Controlling the Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
chapter 5 Working with Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
chapter 6 Building Windows Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
chapter 7 Displaying Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
chapter 8 Creating Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
chapter 9 Debugging and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
chapter 10 Building Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
chapter 11 Advanced Object-Oriented Techniques . . . . . . . . . . . . . . . . . . . . . 367
chapter 12 Accessing Data Using Structured Query Language . . . . . . . . . . . . 405
chapter 13 Database Programming with SQL Server and ADO .NET . . . . . . . . 427
chapter 14 ASP .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
chapter 15 Deploying Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
chapter 16 Windows 8 Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
appendix Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
Beginning
Visual Basic® 2015
Beginning
Visual Basic® 2015
Bryan Newsome
Beginning Visual Basic® 2015
Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com
Copyright © 2016 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-119-09211-7
ISBN: 978-1-119-09207-0 (ebk)
ISBN: 978-1-119-09208-7 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
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 permission 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-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or pro-motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the pub-lisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with stan-dard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://book-support.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2015953114
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-marks 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. Visual Basic is a registered trademark of Microsoft Corporation. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
For my girls, Jennifer and Katelyn.
aBout the author
Bryan newsome leads a team of top developers specializing in Microsoft solutions. Since starting building Visual Basic 5 solutions, he has embraced each new version of Visual Basic and now cre-ates all new solutions leveraging the .NET platform and VB.NET. He provides clients with solutions and mentoring on leading-edge Microsoft technologies. For VB.NET, Bryan is a Microsoft Certified Application Developer.
aBout the technical editor
Valan money is a Microsoft Certified Solution Developer for Web and Windows applications. He has been using Visual Basic since 1996 and got his first certification in Visual Basic 4.0. Since then, he has also received certifications in newer versions of VB and VB.NET. He works as Technical Team Lead and Senior Consultant for projects using Microsoft technologies. He holds a Masters degree in Computer Science from St. Joseph’s College, Tiruchirappalli, India.
senior acquisitions editorKenyon Brown
project editorMaureen S . Tullis
technical editorValan Money
production editorDassi Zeidel
copy editorScott D . Tullis
manager of content development & assemblyMary Beth Wakefield
marketing directorDavid Mayhew
marketing managerCarrie Sherrill
professional technology & strategy directorBarry Pruett
Business managerAmy Knies
associate publisherJim Minatel
project coordinator, coverBrent Savage
proofreaderNancy Carrasco
indexerJohnna VanHoose Dinse
cover designerWiley
cover image©anasimin/iStockphoto
credits
acknowledgments
Thanks to those who worked so hard to get this book on the shelves at Wiley and Wrox. Special thanks (again) to Maureen Tullis who went above and beyond to help me finish mostly on schedule.
Contents
IntroductIon xxvii
Chapter 1: WelCome to Visual BasiC 2015 1
Implementing Event-Driven Programming 2Installing Visual Basic 2015 3The Visual Studio 2015 IDE 5
The Profile Setup Page 5The Menu 6The Toolbars 8
Creating a Simple Application 9Windows in the Visual Studio 2015 IDE 10Modified Hungarian Notation 17The Code Editor 18
Using the Help System 22Summary 23
Chapter 2: the miCrosoft .net frameWork 25
The .NET Vision 25This Sounds Like Java 26Where Now? 27
Writing Software for Windows 27The .NET Framework Classes 28Executing Code 30
Common Language Runtime 31Code Loading and Execution 31Application Isolation 31Security 32Interoperability 33Exception Handling 33
The Common Type System and Common Language Specification 33Summary 34
Chapter 3: Writing softWare 37
Information and Data 37Algorithms 38
xviii
CoNTENTS
What Is a Programming Language? 39Working with Variables 40Comments and Whitespace 43
Comments 43Whitespace 45
Data Types 45Working with Numbers 45Common Integer Math Operations 46Integer Math Shorthand 49The Problem with Integer Math 50Floating-Point Math 50Working with Strings 53Using Dates 62Boolean 69
Storing Variables 69Binary 69Bits and Bytes 70Representing Values 70Converting Values 72
Methods 74Why Use Methods? 74Methods You’ve Already Seen 75Building a Method 78Choosing Method Names 81Scope 82
Summary 84
Chapter 4: Controlling the floW 87
Making Decisions 87The If Statement 88
The Else Statement 90Allowing Multiple Alternatives with ElseIf 90Nested If Statements 92Single-Line If Statement 92Comparison Operators 92String Comparison 101
Select Case 102Case-Insensitive Select Case 106Multiple Selections 108The Case Else Statement 109Different Data Types with Select Case 110
xix
CoNTENTS
Loops 110The For...Next Loop 110The Do...Loop Loops 116Nested Loops 120Quitting Early 121Quitting Do...Loops 123Infinite Loops 124
Summary 125
Chapter 5: Working With Data struCtures 127
Understanding Arrays 128Defining and Using Arrays 128Using For Each...Next 131Passing Arrays as Parameters 133Sorting Arrays 136Going Backward 137Initializing Arrays with Values 138
Understanding Enumerations 139Using Enumerations 140Determining the State 143Setting Invalid Values 146
Understanding Constants 146Using Constants 146Different Constant Types 148
Structures 148Building Structures 149Adding Properties to Structures 152
Working with ArrayLists 153Using an ArrayList 153Deleting from an ArrayList 158Showing Items in the ArrayList 161
Working with Collections 162Creating CustomerCollection 163Adding an Item Property 164
Building Lookup Tables with Hashtable 166Using Hashtables 166Cleaning Up: Remove, RemoveAt, and Clear 169Case Sensitivity 172
Advanced Array Manipulation 173Dynamic Arrays 173Using Preserve 175
Summary 176
xx
CoNTENTS
Chapter 6: BuilDing WinDoWs appliCations 179
Responding to Events 180Counting Characters 184Counting Words 188Creating More Complex Applications 191Creating the Toolbar 192Creating the Status Bar 195Creating an Edit Box 196Clearing the Edit Box 197Responding to Toolbar Buttons 199Using Multiple Forms 202About Dialog 202Summary 206
Chapter 7: Displaying Dialogs 209
The MessageBox 210Available Icons for MessageBox 210Available Buttons for MessageBox 211Setting the Default Button 211Miscellaneous Options 212The Show Method Syntax 212Example Message Boxes 214
The openFileDialog Control 218The OpenFileDialog Control 218The Properties of OpenFileDialog 218OpenFileDialog Methods 220Using the OpenFileDialog Control 221
The SaveDialog Control 226The Properties of SaveFileDialog 226SaveFileDialog Methods 227Using the SaveFileDialog Control 227
The FontDialog Control 231The Properties of FontDialog 231The Methods of FontDialog 232Using the FontDialog Control 232
The ColorDialog Control 235The Properties of ColorDialog 236Using the ColorDialog Control 237
The PrintDialog Control 238The Properties of PrintDialog 239
xxi
CoNTENTS
Using the PrintDialog Control 240The PrintDocument Class 240The Properties of the PrintDocument Class 240Printing a Document 241
The FolderBrowserDialog Control 248The Properties of FolderBrowserDialog 248Using the FolderBrowserDialog Control 249
Summary 252
Chapter 8: Creating menus 255
Understanding Menu Features 255Images 256Access Keys 256Shortcut Keys 256Check Marks 256The Properties Window 257
Creating Menus 259Designing the Menus 259Adding Toolbars and Controls 261Coding Menus 263Coding the View Menu and Toolbars 267Testing Your Code 269
Context Menus 272Creating Context Menus 272Enabling and Disabling Menu Items and Toolbar Buttons 275
Summary 279
Chapter 9: DeBugging anD error hanDling 283
Major Error Types 284Syntax Errors 284Execution Errors 288Logic Errors 288
Debugging 289Creating a Sample Project 289Setting Breakpoints 306Debugging Using the Watch Window and QuickWatch Dialog Box 313Debugging with the Autos Window 316Debugging with the Locals Window 316
Error Handling 318Using Structured Error Handling 319Summary 321
xxii
CoNTENTS
Chapter 10: BuilDing oBjeCts 325
Understanding objects 326Encapsulation 327Methods and Properties 327Events 328Visibility 328What Is a Class? 329
Building Classes 330Reusability 330Designing an object 332
State 332Behavior 333Storing State 333Real Properties 336Read/Write Properties 339Auto-Implemented Properties 342The IsMoving Method 343
Constructors 345Inheritance 346
Adding New Methods and Properties 348Adding a GetPowerToWeightRatio Method 350Changing Defaults 352Polymorphism: Scary Word, Simple Concept 354Overriding More Methods 354Inheriting from the Object Class 356
objects and Structures 357The Framework Classes 357
Namespaces 358The Imports Statement 360Creating Your Own Namespace 361Inheritance in the .NET Framework 364
Summary 365
Chapter 11: aDVanCeD oBjeCt-orienteD teChniques 367
Building a Favorites Viewer 368Internet Shortcuts and Favorites 368Using Classes 371Scanning Favorites 377Viewing Favorites 384
An Alternative Favorite Viewer 386
xxiii
CoNTENTS
Building a Favorites Tray 387Displaying Favorites 388
Using Shared Properties and Methods 392Using Shared Properties 392Using Shared Methods 397
Understanding object-oriented Programming and Memory Management 398
Garbage Collection 400Releasing Resources 400Defragmentation and Compaction 401
Summary 402
Chapter 12: aCCessing Data using struCtureD query language 405
What You Need to Complete This Chapter’s Exercises 406What Is a Database? 407
Database Tables 407Primary and Foreign Keys 413Queries 415
Understanding Basic SQL Syntax 415Using SELECT Statement 416Using the JOIN Statement 417Using the UPDATE Statement 419Using the DELETE Statement 419Using the INSERT Statement 420Using the SQL Comment 421
Executing Queries in SQL Server 421Summary 425
Chapter 13: DataBase programming With sql serVer anD aDo.net 427
ADo.NET 428ADo.NET Data Namespaces 428
The SqlConnection Class 429Working with the Connection String Parameters 430Opening and Closing the Connection 431The SqlCommand Class 431The SqlDataAdapter Class 434The DataSet Class 438DataView 438
The ADo.NET Classes in Action 440
xxiv
CoNTENTS
Data Binding 450BindingContext and CurrencyManager 450Binding Controls 451Binding Examples 452
Summary 480
Chapter 14: asp.net 483
Thin‐Client Architecture 484Web Forms versus Windows Forms 485
Windows Forms Advantages 485Web Forms Advantages 485
Web Applications: The Basic Pieces 486Web Servers 486Browsers 486HyperText Markup Language 487JavaScript 487Cascading Style Sheets 487
Active Server Pages 488Benefits of ASP.NET Web Pages 488Special Website Files 488Development 489Controls: The Toolbox 489
Building Websites 490Creating a Web Form for Client‐ and Server‐Side Processing 490Website Locations with VS 2015 495Performing Data Entry and Validation 498Using the GridView to Build a Data‐Driven Web Form 507
Summary 512
Chapter 15: Deploying your appliCation 515
What Is Deployment? 516ClickOnce Deployment 516XCOPY Deployment 521
Visual Studio 2015 Setup Application options 522Deploying Different Solutions 522
Private Assemblies 523Shared Assemblies 523Deploying Desktop Applications 524Deploying Web Applications 524
xxv
CoNTENTS
Deploying XML Web Services 524Useful Tools 525
Summary 525
Chapter 16: WinDoWs 8 apps 529
Windows 8 Application Design Principles 530Using Touch 530Application Commands 531Windows 8 Controls 532Coding Windows 8 Apps with XAML 533Creating Your First Windows 8 App 534
Application Layout 548Application Views 548Screen Sizes and Orientation 548
Summary 553
APPENDIx: ExERCISE SoLUTIoNS 557
Index 569
IntroductIon
VIsual BasIc 2015 Is Microsoft’s latest version of the highly popular Visual Basic .NET programming language, one of the many languages supported in Visual Studio 2015. Visual Basic 2015’s strength lies in its ease of use and the speed at which you can create Windows Forms and Windows 8 applications, web applications, and mobile device applications.
In this book, we introduce you to programming with Visual Basic 2015 and show you how to create these types of applications and services. Along the way you’ll also learn about object-oriented tech-niques and learn how to create your own business objects and Windows controls.
Microsoft’s .NET Framework provides Visual Basic 2015 programmers with the capability to create full object-oriented programs, just like the ones created using C# or C++. The .NET Framework provides a set of base classes that are common to all programming languages in Visual Studio 2015, which provides you with the same capability to create object-oriented programs as a programmer using C# or C++.
This book will give you a thorough grounding in the basics of programming using Visual Basic 2015; from there the world is your oyster.
Who thIs Book Is For
This book is designed to teach you how to write useful programs in Visual Basic 2015 as quickly and easily as possible.
There are two kinds of beginners for whom this book is ideal:
➤ You’re a beginner to programming and you’ve chosen Visual Basic 2015 as the place to start. That’s a great choice! Visual Basic 2015 is not only easy to learn, it’s also fun to use and very powerful.
➤ You can program in another language but you’re a beginner to .NET programming. Again, you’ve made a great choice! Whether you’ve come from Fortran or Cobol, you’ll find that this book quickly gets you up to speed on what you need to know to get the most from Visual Basic 2015.
What thIs Book coVers
Visual Basic 2015 offers a great deal of functionality in both tools and language. No one book could ever cover Visual Basic 2015 in its entirety—you would need a library of books. What this book aims to do is to get you started as quickly and easily as possible. It shows you the roadmap, so to speak, of what there is and where to go. Once we’ve taught you the basics of creating working appli-cations (creating the windows and controls, how your code should handle unexpected events, what
xxviii
introduction
object-oriented programming is, how to use it in your applications, and so on) we’ll show you some of the areas you might want to try your hand at next:
➤ Chapters 1 through 8 provide an introduction to Visual Studio 2015 and Windows programming.
➤ Chapter 9 provides an introduction to application debugging and error handling.
➤ Chapter 10 provides an introduction to object-oriented programming and building objects.
➤ Chapter 11 provides an introduction to creating Windows Forms user controls.
➤ Chapters 12 and 13 provide an introduction to programming with databases and covers Structured Query Language, SQL Server, and ADO.NET.
➤ Chapter 14 provides an introduction to ASP.NET and shows you how to write applications for the web.
➤ Chapter 15 introduces you to deploying applications using ClickOnce technology.
➤ Chapter 16 show you how to build your first Windows 8 application and introduces you to design principles for touch interfaces.
What You need to use thIs Book
Apart from a willingness to learn, all you’ll need are a PC running Windows 8 (preferred), Windows 7, Windows Server 2008 R2, Windows Server 2015; Internet Explorer; and of course:
➤ Microsoft Visual Basic 2015Community Edition or higher
For the database chapters, you should install SQL Server 2014 Express, although, any edition you have should work with little to no changes required.
conVentIons
To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.
trY It out
The Try It Out is an exercise you should work through, following the text in the book.
1. They usually consist of a set of steps.
2. Each step has a number.
3. Follow the steps through with your copy of the database.
How It Works
After each Try It Out, the code you’ve typed will be explained in detail.