data entry and validation with e# and vb .net windows forms978-1-4302-0807-5/1.pdf · data entry...

17
Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Upload: others

Post on 30-Apr-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Data Entry and Validation with e# and VB .NET Windows Forms

NICK SYMMONDS

APress Media, LLC

Page 2: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Data Entry and Validation with C# and VB .NET Windows Forms

Copyright © 2003 by Nick Symmonds

Originally published by Apress in 2003

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.

Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

Technical Reviewer: Adriano Baglioni

Editorial Board: Dan Appleman, Craig Berry, Gary Cornell, Tony Davis, Steven Rycroft, Julian Skinner, Martin Streicher, Jim Sumser, Karen Watterson, Gavin Wright, John Zukowski

Assistant Publisher: Grace Wong

Project Manager: Beth Christmas

Copy Editor: Nicole LeClerc

Production Manager: Kari Brooks

Proofreader: Linda Siefert

Compositor: Susan Glinert Stevens

Indexer: Rebecca Plunkett

Artist: April Milne

Cover Designer: Kurt Krames

Manufacturing Manager: Tom Debolski

Distributed to the book trade in the United States by Springer-Verlag New York, Inc., 175 Fifth Avenue, New York, NY, 10010 and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17, 69112 Heidelberg, Germany.

In the United States: phone I-BOO-SPRINGER, email [email protected]. or visit http:/ /www.springer-ny.com. Outside the United States: fax +496221345229, email orders@springer . de, or visit http://www.springer.de.

The information in this book is distributed on an "as is" basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.

ISBN 978-1-59059-108-6 ISBN 978-1-4302-0807-5 (eBook)DOI 10.1007/978-1-4302-0807-5

Page 3: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

For Celeste. You are the love of my life.

Page 4: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Contents at a Glance

About the Author ................................................................................................. xi

About the Technical Reviewer ..................................................................... xiii

Acknowledgments ................................................................................................... xv

Introduction ...................................................................................................... xvii

Chapter 1 The. NET Data Entry Controls ........................................... 1

Chapter 2 UI Design Considerations for Data Entry ................. 59

Chapter 3 Data Presentation Screen Issues ................................ 117

Chapter 4 Keyboard- and Mouse-Based Data Entry ..................... 203

Chapter 5 The Object-Oriented GUI .................................................. 239

Chapter 6 Advanced Data Entry ........................................................... 327

Chapter 7 Error Handling ..................................................................... 395

Chapter 8 Advanced Validation and Custom Data Validation Controls ........................................................... 445

Chapter 9 XML Data Entry and Validation ..................................... 529

Chapter 10 Keeping Users Happy ........................................................... 573

Chapter 11 Pulling It All Together .................................................. 643

Appendix Application Blocks ............................................................. 705

Index ...................................................................................................................... 709

v

Page 5: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Contents

About the Author .......................................................................................... xi

About. the Technical Reviewer ......................................................... xiii

Acknowledgments ............................................................................................. xv

Introduction ................................................................................................. xvii

Chapter 1 The. NET Data Entry Controls ............................... 1

Validation Defined ............................................................................................. 1 The Simple Data Entry Controls ................................................................... 3 Summary ................................................................................................................... 57

Chapter 2 UI Design Considerations for Data Entry ................................................................. 59

Screen Consistency ........................................................................................... 60 Keeping Information Flow Simple ............................................................... 65 A Different Data Entry Screen: Console Applications ................. 104 Screen Size, Control Manipulation, and other

Screen Management Options ................................................................... 109 Ambient Properties ......................................................................................... 114 Summary ................................................................................................................. 115

Chapter 3 Data Presentation Screen Issues ................... 117

The Single-Document Interface ................................................................. 117 The Mul tiple-Document Interface ............................................................. 140 The Context Menu in MOl Applications .................................................. 152 Making Your Application Available to Everyone .............................. 153 Internationalizing Your Program ............................................................. 154 Accessibility .................................................................................................... 192 Summary ................................................................................................................. 201

vii

Page 6: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Contents

Chapter 4 Keyboard- and Mouse-Based Data Entry ....... 203

The Keyboard and You ..................................................................................... 204 A Better Mouse Trap ....................................................................................... 215 The Mouse~ GDI+~ and You ............................................................................. 230 Summary .................................................................................................................. 238

Chapter 5 The Object-Oriented GUI ........................................ 239

What Is the Object-Oriented Gun ........................................................... 239 Manipulating Data with the ListView Control ................................... 256 Manipulating Data with the TreeView Control ................................... 291

Highlighting Nodes .......................................................................................... 319 Anchoring and Docking ................................................................................... 320 Summary .................................................................................................................. 325

Chapter 6 Advanced Data Entry .................................................. 327

The Database ....................................................................................................... 327 Other Data Sources .......................................................................................... 374

File-Based Data ................................................................................................ 379 Summary .................................................................................................................. 393

Chapter 7 Error Handling ............................................................... 395

Showing Basic Errors ..................................................................................... 395 Advanced Error Reporting ............................................................................. 406 Throwing Errors ................................................................................................ 431 Summary .................................................................................................................. 443

Chapter 8 Advanced Validation and Custom Data Validation Controls ..................................... 445

Regular Expressions in . NET ...................................................................... 445 The Masked Edit Control ............................................................................... 462

Rolling Your Own Masked Edit Control .................................................. 472

Testing the Masked Edit Control ............................................................. 491 Extending Control Properties .................................................................... 494

Summary .............................................................. : ................................................... 528

viii

Page 7: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Contents

Chapter 9 XML Data Entry and Validation ........................ 529

What Is XML to . NET? ..................................................................................... 529

The System.Xml Namespace ............................................................................ 530 The Xml ValidatingReader .............................................................................. 553 Other Types of XML Data .............................................................................. 571 Summary ................................................................................................................. 572

Chapter 10 Keeping Users Happy .................................................. 573

Speeding Up the Controls ............................................................................ 573 Multithreading .................................................................................................. 612 Summary ................................................................................................................. 640

Chapter 11 Pulling It All Together ........................................ 643

The Golf Project .............................................................................................. 643

The Data Structures ....................................................................................... 649

Summary ................................................................................................................. 703

Appendix Application Blocks ..................................................... 705

Finding the Application Blocks ............................................................... 705 Making the Necessary DLLs for Exception Management ................... 706 Using the Exception Management Block .................................................. 707 The Ultimate Error Handler ........................................................................ 708

Index ................................................................................................................... 709

ix

Page 8: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

About the Author

Nick Symmonds started out his professionalllfe as an electronics technician. While getting his bachelor's degree in electrical engineering from the University of Hartford, he started to gravitate toward programming. Nick has spent quite a few years programming in assembly, C, C++, and VB. Recently, he has latched onto .NET like a lamprey and loves digging into the .NET core. Nick has written several articles on programming and has two books currently out: Internationalization and Localization Using Microsoft .NET (Apress, 2002) and GDI+ Programming in C# and VB .NET (Apress, 2002). He works for the Security and Safety Solutions division of Ingersoll-Rand, developing and integrating security software.

Nick lives with his family in the northwest hills of Connecticut and enjoys golfing, biking, and exploring the hills on his motorcycle.

xi

Page 9: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

About the Technical Reviewer

Adriano Baglioni got his first taste of computers as a freshman in high school, using BASIC on a PDP-ll /70. He pursued his interest in computers at Rensselaer Polytechnic Institute (RPI), where he graduated with a bachelor's degree in computer and systems engineering. He followed that up with a master's degree in computer science, also from RPI. He has worked in the computer industry for 20 years, programming mostly in C and C++. His experience runs the gamut from embedded programming on 8051s to scientific programming on mainframes. He currently works at Veeder-Root Co., developing software for environmental monitoring equipment.

When it's time to take a break from the computer, Adriano enjoys hiking, biking, and camping with his wife, Carol.

xiii

Page 10: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Acknowledgments

THIS IS MY THIRD BOOK for Apress. Each time it becomes more enjoyable. The level of professionalism within this company is unparalleled. Thanks to Beth Christmas for keeping me on track as my project manager. Nicole LeClerc did a wonderful job again as copy editor. I can't believe how fast you do what you do. Thanks to all those at Apress who helped and advised me on this book.

Special thanks go out to Adriano Baglioni. Without his technical review comments, this book would not be nearly as good as it is. It was a pleasure working with you again.

xv

Page 11: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Introduction

ANYoNE WHO HAS EVER worked with a computer has had to enter data into it somehow. Anyone who has done any Windows programming (or DOS programming, if you go back far enough) has had to write data entry screens. What is data entry without some kind of validation?

Then again, what is validation? Validation is the process of the receiving data (via the keyboard, the mouse, voice, serial connections, and so on) and making sure that the data meets the specifications you have laid out. For instance, if you are looking for a number but receive a character, your validation code would ignore that character.

I wrote this book because it encompasses pretty much what most Windows programmers do on a day-to-day basis. As programmers, we all work with data. We collect it, massage it, store it, retrieve it, and present results back to the user. As a matter of fact, data entry and validation are likely such constant themes throughout your programming day that I bet you don't even realize you're doing them.

When most new programmers think of data entry, they think "Booooring!" What often comes to mind are endless screens oftext-based data entry fields for insurance companies. Where is the fun in that? After all, there is no chance for any creativity and after a few weeks of this kind of work, life becomes dull. It seems like assembly-line programming at its worst.

Data Entry Code Can Be Interesting

Is data entry and validation really this simple and dull? I think not. If it were, I would have changed professions long ago.

Data entry involves two aspects. One is to collect data and the other is to make sure the data makes sense. The fun part is how you go about programming it.

If you think that writing screen after screen of data entry fields is boring, how do you think end users feel using these screens? I would say they feel even more bored. Your job as a programmer here is twofold. First, you need to make the data entry screens not so boring to use, and second, you need to make the screens not so boring to program. An additional task is to make the screens sensible. The only thing worse to a user than an uninteresting program is a frustrating one. How many times have you used a program and had to hunt down certain data fields in screens where they don't belong? You tend to wonder, what were they thinking?! Perhaps you have received some feedback like this about your own program.

xvii

Page 12: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Introduction

xviii

Who Should Read This Book

This book is for intermediate and well-seasoned programmers who are already writing in .NET or want to change over to .NET. I assume a level of programming knowledge commensurate with a basic understanding of .NET and a good under­standing of programming in general. Readers should know some object-oriented and general programming techniques such as the following:

• Function overloading

• Inheritance

• Class design and instantiation

• Use of threads and the advantages (and pitfalls) of threading

• Exception handling

Readers should also be familiar with some of the .NET-specific topics such as the following:

• Garbage collection

• JIT compiler

• Organization of the .NET namespaces

Why You Should Read This Book

Take a look through your friendly local bookstore's computer book section. You will find quite a few books about .NET. They all seem to fall somewhere in the following categories:

• Books on everything you could possibly know about C# in 1,500 pages (ditto for Visual Basic .NET [VB .NET])

• Books outlining how to do a specific task within .NET, such as writing an ASP page

• All kinds of books about the .NET Framework and the philosophy behind it

• Books for all the "idiots" and "dummies" who write the majority of our com­puter programs

Page 13: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Basically what you will see are "task" books. Rarely will you see a book devoted to a programming specialty that requires knowledge of quite a few tasks along with interesting uses of the .NET Framework and good general practices. Some examples of task book topics that I have seen are as follows:

• Programming games in .NET

• Writing scientific programs in .NET

• Writing a scalable client/ server program in .NET

If you think about some specialties, you may need several books just to get all the information you need to accomplish what you do every day. This book isn't a task book; it's a programming specialty book. In it you will find information on subjects such as

• Programming graphics

• Programming Windows Forms

• Using localization

• UsingXML

• Building user controls

I cover quite a few other topics as well. You see, by including these few subjects in this book, I've saved you from buying five other books. Granted, I don't go into great depth on any of these items, but by the time you finish reading this book, you'll be familiar with them and know how to use them. Isn't that what you're really interested in, anyway?

What Makes This Book Unique

Visual Studio .NET is not new anymore. Since the product's release in early 2002, Microsoft has been evangelizing the advantages of .NET, Web services, and just moving ahead in the programming game in general.

You probably already have a couple of books on .NET.1 Perhaps you have written a program or two just to try things out and kick the tires a little. My local

l. Perhaps you have one of my previous books on .NET: GDI+ Programming in e# and VB .NET or Internationalization and Localization Using Microsoft .NET.

Introduction

xix

Page 14: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Introduction

xx

bookstore has multiple shelves filled with books on .NET. What distinguishes this book from the others is the application-oriented aspect. As I have stated, I present an end result here that you may not see in other books.

You will see quite a few techniques in this book that you can surely find else­where. However, instead of showing you how to program mouse events, for example, I show you how to program mouse events within the context of the all-important data entry screen.

You might consider this book a consolidation of best practices for getting the most out of the .NET Framework with an eye toward the user interface and data validation. Knowing a technique is not the same as knowing how to apply it. This book teaches you how to better apply what you probably do on a daily basis, but within the context of .NET.

What You Will Get Out of This Book

As with my last two books, I decided to include all examples in both C# and VB .NET. I like to do this because it appeals to a wider audience, and it also lets you see what the differences are between C# and VB when you are programming the same task. You will also see how C# and VB .NET really do use the same underlying framework to accomplish the same tasks. As a developer, I feel that this is one of the most awesome advantages to come out of .NET as a whole.

As far as the Framework goes, you will see quite a bit of it in the chapters ahead. Think about all the things necessary for a good data entry screen. Here is some of what you will see:

• Determining which controls to use and when

• Writing a world -ready program

• Creating graphics using the GDI+ namespaces

• Threading

• Using collection classes

• Understanding accessibility issues

• Deciding which type of document interface to use

• Performing everyday data validation

• Extending controls

Page 15: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

• Creating custom data validation controls

• Using error handling

• Understanding XML and hardware 110

Being able to create friendly and usable data entry screens is not really taught in schools or even treated as a subject in most books. This book tries to remedy that situation and get you on the road to writing an effective program.

A Word About the Examples

I encourage you to enter at least some of the examples by hand in both languages. I feel it is good to be familiar with the two flagship languages of .NET: VB .NET and CU. You will see some cases where VB is better than C# and some cases where C# is better for a particular task than VB.

For those of you who want to run the examples without the pain of writing them, you can download all the code from the Downloads section of the Apress Web site (http://www.apress.com).

All the examples in this book have gone through a thorough review process. They are not professional-level, robust products, but they should work as intended. I take responsibility for all programming errors in this book. If you find an error, please let me know about it and I will post the corrected code on the Apress Web site. You can reach me at [email protected].

Some Points About the Code

The code that I wrote for the examples follows some simple guidelines. I describe those guidelines here so you will know what to expect and where to find certain code sections.

Designating Events

I like to know what is happening in my code and I also like to be able to control it. There is quite a bit of functionality in the IDE that allows you to automatically handle events or assign event handlers using the IDE. As far as VB .NET goes, you can get an event handler for a certain control by double-clicking the control. The IDE will generate the event shell for you similar to VB 6.0. This consists of the event handler procedure name followed by the event it handles. It looks like this:

Introduction

xxi

Page 16: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Introduction

xxii

Private Sub cmdClose_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdClose.Click

The C# IDE does much the same thing, except that it creates a delegate for you and assigns the delegate within the "Wmdows Form Designer generated code" section.

I do not use this method of programming for events for the following reasons:

• The IDE will choose the name of my event handler. I can change it later, but in the case of C# I need to dig through the "Wmdows Form Designer generated code" section to find the delegate assignment.

• Using VB, you cannot remove or change the event handler assignment at runtime.

You are also able to assign event handlers for C# using the IDE directly. You can do this by assigning handler names in the Properties screen of the IDE, as shown in Figure 1.

I ProoertIos lot x cmbFlow System.wndows.Forms.ComboBo,.jf;:

lI.ltnDf[~] 6 I Seiett_dlnd_xehang_d I ". ~OIIIITAtedJ

I St-;Ie<:hanoed I ISystemCoiorsChMQ_d

8 oat .. III(Dat~) I 8 Draa I rOp

~OQDrOP J Dr.~Enter --:-' .- --Dr...,...,,_ DrOQOver t ~=IOO.

.. -.-...

QueryConthJeIlrag j 8 Focus

I Enter 1 , Leave I .~ !vOid-;t;d ~ OC<U'S when .. bin Is ct.>sen from the chlpdown -.d the acp down Is closed.

Figure 1. Assigning event handlers via the Properties screen

Page 17: Data Entry and Validation with e# and VB .NET Windows Forms978-1-4302-0807-5/1.pdf · Data Entry and Validation with e# and VB .NET Windows Forms NICK SYMMONDS APress Media, LLC

Although this is all well and good, it has two problems:

• The delegate assignment is done in the "Windows Forms Designer generated code" section.

• If you delete the control, the event handler code still remains.

Here is what I prefer to do. IfI know at design time what I need, I assign all my event handlers in the constructor. This puts them all in one place, one right after the other.

For VB code, I use the AddHandler command to assign delegates to events. This allows me to assign multiple events to one handler, and it also allows me to use RemoveHandler later in the code to remove a delegate from handling an event.

Compartmentalizing Code

I like to use regions. I use a section at the top of each class to hold all the class local variables. I put all the mouse handling events in their own region. I like to put all class properties in their own region.

Using regions is a great way to partition your code and see only the section of code that you are working on.

Included Code

When I provide code in this book, I usually do not include the "Windows Form Designer generated code" region. I instead put a marker to note where this section belongs.

This section contains all the stuff the IDE puts in your code that concerns the controls on your form. It also has the Dispose method for both C# and VB. The constructor for VB is in this section as well, but the C# constructor is not.

Anyway, if you are typing in the project as I describe, the IDE will fill in this code for you. Including it is a waste of paper.

It is time to turn the page and start programming. I hope that you will find this book interesting and gain some insights that help you in your career.

Introduction

xxiii