database programming with visual basic net and ado net - tips, tutorials, and code

751
 [ Team LiB ]  Table of Contents Index Database Programming with Visual Basic® .NET and ADO.NET: Tips, Tutorials, and Code By F. Scott Barker  Publisher : Sams Publishing Pub Dat e : Sept ember 12, 2002 ISBN : 0-672-32247-1 Pages : 544 The topic combination of VB .NET and ADO.NET is unbeatable. VB .NET is the most popular language in which to code. And, every developer needs to understand ADO.NET to allow data to be accessed from a Web site. In this book Developers will be shown numerouse code examples that will illustr4ate how to program database driven applications within the .NET Framework. The book is aimed at both established and new VB Developers. Important topics covered include: Visual Studio development environment, ASP.NET applications, Windows Forms application, using VB .NET with ADO.NET, complex queries, security, COM interop., and application deployment. [ Team LiB ]  [ Team LiB ]  Table of Contents Index Database Programming with Visual Basic® .NET and ADO.NET: Tips, Tutorials, and Code By F. Scott Barker  Publisher : Sams Publishing Pub Dat e : Sept ember 12, 2002 ISBN : 0-672-32247-1 Pages : 544 The topic combination of VB .NET and ADO.NET is unbeatable. VB .NET is the most popular language in which to code. And, every developer needs to understand ADO.NET to allow data to be accessed from a Web site. In this book Developers will be shown numerouse code examples that will illustr4ate how to program database driven applications within the .NET Framework. The book is aimed at both established and new VB Developers. Important topics covered include: Visual Studio development environment, ASP.NET applications, Windows Forms application, using VB .NET with ADO.NET, complex queries, security, COM interop., and application deployment. [ Team LiB ]

Upload: oseuka

Post on 08-Oct-2015

75 views

Category:

Documents


23 download

DESCRIPTION

Database Programming With Visual Basic Net and Ado Net - Tips, Tutorials, And Code

TRANSCRIPT

  • [ Team LiB ]

    Table of Contents

    Index

    Database Programming with Visual Basic .NET andADO.NET: Tips, Tutorials, and CodeBy F. Scott Barker

    Publisher : Sams Publishing

    Pub Date : September 12, 2002

    ISBN : 0-672-32247-1

    Pages : 544

    The topic combination of VB .NET and ADO.NET is unbeatable. VB .NET is the most popular language inwhich to code. And, every developer needs to understand ADO.NET to allow data to be accessed from a Website. In this book Developers will be shown numerouse code examples that will illustr4ate how to programdatabase driven applications within the .NET Framework. The book is aimed at both established and new VBDevelopers. Important topics covered include: Visual Studio development environment, ASP.NETapplications, Windows Forms application, using VB .NET with ADO.NET, complex queries, security, COMinterop., and application deployment.

    [ Team LiB ]

    [ Team LiB ]

    Table of Contents

    Index

    Database Programming with Visual Basic .NET andADO.NET: Tips, Tutorials, and CodeBy F. Scott Barker

    Publisher : Sams Publishing

    Pub Date : September 12, 2002

    ISBN : 0-672-32247-1

    Pages : 544

    The topic combination of VB .NET and ADO.NET is unbeatable. VB .NET is the most popular language inwhich to code. And, every developer needs to understand ADO.NET to allow data to be accessed from a Website. In this book Developers will be shown numerouse code examples that will illustr4ate how to programdatabase driven applications within the .NET Framework. The book is aimed at both established and new VBDevelopers. Important topics covered include: Visual Studio development environment, ASP.NETapplications, Windows Forms application, using VB .NET with ADO.NET, complex queries, security, COMinterop., and application deployment.

    [ Team LiB ]

  • [ Team LiB ]

    Table of Contents

    Index

    Database Programming with Visual Basic .NET andADO.NET: Tips, Tutorials, and CodeBy F. Scott Barker

    Publisher : Sams Publishing

    Pub Date : September 12, 2002

    ISBN : 0-672-32247-1

    Pages : 544

    Copyright

    About the Author

    Acknowledgments

    Tell Us What You Think!

    Introduction

    Who Is This Book For?

    What's Covered in Database Programming with Visual Basic .NET and ADO.NET: Tips, Tutorials, and

    Code? Chapter 1. Developing Windows Forms Using Bound Controls

    Section 1.1. Create a Bound List Box

    Section 1.2. Limit the Data Displayed in a Bound List Box

    Section 1.3. Bind and View Individual Text Boxes Based Off a Selected List Box Item

    Section 1.4. Edit and Update Data Using Bound Controls

    Section 1.5. Add and Delete Records Using Bound Controls

    Section 1.6. Take Care of Error Handling with Bound Controls

    Section 1.7. Put the Finishing Touches on a Data Bound Form

    Section 1.8. Bind Data to ComboBox and DataGrid Controls

    Section 1.9. Drill Down to Data in the DataGrid Control Chapter 2. Creating SQL Server Database Objects From Visual Studio .NET

    Working with Tables, Columns, and Rows

    Utilizing Properties for Tables and Columns

    Section 2.1. Create a New SQL Server Database from Within Visual Studio .NET

    Section 2.2. Define Tables and Fields

  • Section 2.3. Define a Primary Key and Other Indexes

    Section 2.4. Define Relations Between Tables

    Section 2.5. Define Defaults and Constraints

    Section 2.6. Create Views

    Section 2.7. Create Stored Procedures Chapter 3. Viewing Data With ADO.NET

    Differences Between ADO and ADO.NET

    Objects That Are Found in ADO.NET

    Section 3.1. Retrieve Data by Using the DataReader Object

    Section 3.2. Retrieve Results from SQL Server by Using the DataTable Object

    Section 3.3. Locate Records with the DataTable Object

    Section 3.4. Filter and Sort Records Using the DataView Object Chapter 4. Manipulating Data With ADO.NET

    Section 4.1. Edit Data and Update Changes That Are Made to an ADO.NET DataSet Object

    Section 4.2. Add and Delete Rows in a Dataset with ADO.NET

    Section 4.3. Execute Parameterized Stored Procedures in ADO.NET

    Section 4.4. Create and Execute On-the-Fly Batch Updates by Using ADO.NET Chapter 5. Working With Data In Web Forms

    Dealing with Stateless Programming

    Section 5.1. Use Bound Controls with Web Forms

    Section 5.2. Validate Data Using Validation Controls

    Section 5.3. Populate DropDown and ListBox Controls

    Section 5.4. Display Data Using the Table Control

    Section 5.5. Display Data Using the Repeater Control

    Comments

    Section 5.6. Display, Sort, and Page Data in the DataGrid Control

    Section 5.7. Add, Edit, and Delete Data Using the DataGrid Control

    Section 5.8. Hyperlink from a Row in the Data Grid to a Detail Page Chapter 6. Creating Transact-SQL Commands

    Section 6.1. Retrieve Unique Records Using Only a Select Query

    Section 6.2. Use Variables and Functions in T-SQL

    Section 6.3. Use Wildcards and Ranges of Values in a SQL Query

    Section 6.4. Find Records in a Table Without Corresponding Entries in a Related Table

    Section 6.5. Take Advantage of Using Subqueries

    Section 6.6. Create, Modify, and Delete Tables

    Section 6.7. Create a New Table with Data from Existing Tables

    Section 6.8. Create and Call SQL Server 2000 User-Defined Functions Chapter 7. Performing Common Database Tasks Using SQL-DMO

    Looking at the SQL Server DMF APIs

    Setting References in .NET for the SQL APIs

    Section 7.1. Create a Dialog Box to Connect to a New Database, Including Listing Available SQL

    Servers and Databases Section 7.2. Back Up and Verify a SQL Server Database

    Section 7.3. Restore a SQL Server Database

    Section 7.4. Transfer Tables Between SQL Server Databases

    Section 7.5. Create a Detach/Attach SQL Server Database Dialog Box

  • Chapter 8. Taking Advantage of Data-Driven Techniques

    Section 8.1. Work with Data-Bound Multi-Select List Boxes Using Windows Forms

    Section 8.2. Use a Single Windows Form to Update Multiple Lookup Tables

    Section 8.3. Create a Point-and-Click SQL Server Query Tool for Users Using a Windows Form

    Section 8.4. Make a Generic Search Form in a Visual Basic .NET Desktop Application

    Section 8.5. Work with Data-Bound Multi-Select List Boxes Using Web Forms

    Section 8.6. Use a Single Web Form to Update Multiple Lookup Tables

    Section 8.7. Create a Point-and-Click Query Tool for Users Using a Web Form

    Section 8.8. Make a Generic Search Form in an ASP.NET Web Application Chapter 9. Using Classes With Databases to Make Life Easier

    Section 9.1. Define a Class in Visual Basic .NET

    Section 9.2. Create a Class That Implements the Interface You Defined

    Section 9.3. Use Visual Studio .NET Tools to Speed Up Writing ADO.NET Code

    Section 9.4. Control the Creation and Behavior of Classes

    Section 9.5. Implement the Methods That Update the Database

    Section 9.6. Validate Data Passed to Properties and Communicate Errors to Developers

    Section 9.7. Write Data Validation Code That Can Be Reused in Other Classes Chapter 10. Creating Reports Using Crystal Reports

    Section 10.1. Create a Report Using Crystal Reports Report Expert

    Section 10.2. Display a Report That Was Created

    Section 10.3. Add Calculated Fields to the Crystal Reports Report

    Section 10.4. Select Whether the Report Will Be Displayed, Printed, or Exported Using Visual Basic

    .NET Code Section 10.5. Determine Which Records Will Be Printed at Runtime

    Section 10.6. Print Labels and Control the Order in Which Records Will Be Printed

    Section 10.7. Create an Onscreen Report That Contains Hyperlinks Chapter 11. Managing SQL Server Security

    Section 11.1. Create Windows NT/2000 Users

    Section 11.2. Create Windows NT/2000 Groups

    Section 11.3. Establish a Windows NT/2000 Authentication Mode

    Section 11.4. Establish Mixed-Mode Authentication

    Section 11.5. Create a Standard Login

    Section 11.6. Create a Windows NT/2000 Login

    Section 11.7. Use a Fixed Server Role

    Section 11.8. Create a Database User Account

    Section 11.9. Use Statement Permissions

    Section 11.10. Use Object Permissions

    Section 11.11. Use Fixed Database Roles

    Section 11.12. Create Custom Database Roles

    Section 11.13. Create Application Roles Chapter 12. Utilizing XML Data In Your Visual Basic .NET Applications

    Ways of Utilizing XML in .NET

    XML Namespaces in .NET

    Section 12.1. Use XMLWriter to Create an XML Document

    Section 12.2. Use XMLReader to Read an XML Document

    Section 12.3. Work with the XML Document Object Model

  • Section 12.4. Retrieve XML from SQL Server 2000

    Section 12.5. Work with Datasets and XML Chapter 13. Creating XML Web Services

    Overview of the XML Web Services Infrastructure

    Section 13.1. Get Started with XML Web Services

    Section 13.2. Create a Simple XML Web Service Using Parameters

    Section 13.3. Consume XML Web Services

    Section 13.4. Pass a Dataset Back from an XML Web Service Appendix A. Desktop Development With ADO

    When to Use ADO (Local Database/Single Tier Applications)

    Looking At the ADO Object Models

    Referencing the Type Libraries

    Using the Connection Object Working with the ADO Recordset Object Executing a SQL Server Stored Procedure By Using ActiveX Data Objects

    Executing Batch Updates with ADO and SQL Server

    Creating SQL Server Objects with ActiveX Data Objects

    Conclusion Index

    [ Team LiB ]

  • [ Team LiB ]

    Copyright

    Copyright 2003 by Sams Publishing

    All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted byany means, electronic, mechanical, photocopying, recording, or otherwise, without written permission fromthe publisher. No patent liability is assumed with respect to the use of the information contained herein.Although every precaution has been taken in the preparation of this book, the publisher and author assumeno responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use ofthe information contained herein.

    Library of Congress Catalog Card Number: 2001094459

    Printed in the United States of America

    First Printing: September 2002

    05 04 03 02 4 3 2 1

    Trademarks

    All terms mentioned in this book that are known to be trademarks or service marks have been appropriatelycapitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this bookshould not be regarded as affecting the validity of any trademark or service mark.

    Warning and Disclaimer

    Every effort has been made to make this book as complete and as accurate as possible, but no warranty orfitness is implied. The information provided is on an "as is" basis. The author and the publisher shall haveneither liability nor responsibility to any person or entity with respect to any loss or damages arising from theinformation contained in this book.

    Credits

    ASSOCIATE PUBLISHER

    Michael Stephens

    ACQUISITIONS EDITOR

    Neil Rowe

    DEVELOPMENT EDITOR

    Kevin Howard

    MANAGING EDITOR

    Charlotte Clapp

    PROJECT EDITORS

  • Matt Purcell

    Tony Reitz

    COPY EDITOR

    Karen A. Gill

    INDEXER

    Sandy Henselmeier

    PROOFREADER

    Linda Seifert

    TECHNICAL EDITOR

    Shawn Nanto

    TEAM COORDINATOR

    Lynne Williams

    INTERIOR DESIGNER

    Gary Adair

    COVER DESIGNER

    Alan Clements

    PAGE LAYOUT

    Stacey Richwine-DeRome

    Dedication

    I would like to dedicate this book to the innocent men, women, and children who died in the September 11,2001 attack in New York, at the Pentagon, and those in the airplanes as well. God bless you, and God blessAmerica!

    [ Team LiB ]

  • [ Team LiB ]

    About the Author

    F. Scott Barker holds a bachelor of science in computer science and has worked as a developer in thedatabase field for more than 16 years, first with Clipper, and then with Visual Basic, SQL Server, andMicrosoft Access for the past 10 years. Scott has already created and deployed a number of ASP.NET Websites for his clients.

    Working at Microsoft for two years, Scott was a member of the Microsoft Access and FoxPro teams. Sinceleaving, he has been a contractor with Microsoft developing in-house tools used throughout Microsoft. Withhis company, Applications Plus, Scott has also been doing contract development for many Fortune 500companies, developing in ASP.NET, Visual Basic .NET, C#, Visual Basic/Access/Office, and SQL Server.

    Scott has trained for Application Developers Training Company and others all around the U.S. and is afrequent speaker at Microsoft conferences throughout the U.S., Canada, South Asia, and Europe. Throughhis classes and conferences, Scott has trained thousands of developers.

    Scott is a writer for a number of development magazines and is the author of F. Scott Barker's MicrosoftAccess 2002 Power Programming, published by Sams, and Access 97 Power Programming, published byQue.

    Scott can be reached at his Web site at www.appsplus.com, or via e-mail at [email protected].

    [ Team LiB ]

  • [ Team LiB ]

    Acknowledgments

    To start off, I want to acknowledge Neil Rowe, my acquisitions editor, for putting up with me for anotherbook. Thanks also to Kevin Howard, my development editor. Bud, you had me scared at first.

    A big thanks goes to my longtime friends Paul Sheriff, Ken Getz, Mike Groh, and Tom Howe, for putting upwith me that week at Paul's class, helping me hammer out the outline, and being around for me to bounceideas off of.

    A really special thanks goes to Michael O'Neil for his work on the Classes chapter. He is a man who has a lotof class. Good luck with NYU!

    Another thanks to Mike Groh for his work on the Security chapter, you are a great friend Mike, and knowyour stuff!

    Thanks to the students who attended my .NET classes and helped to shape the contents of this book as Iwas writing it. No, you don't get any of my royalties, but you have my thanks.

    As usual, I want to thank some people from Microsoft for putting up with my questions, listening to mybeefs, and not telling me where to go when I got on their nerves. Ari Bixhorn, you are one of the mostenthusiastic guys I know. My thanks to you and Ed Robinson for being so patient with me and letting yourexcitement for .NET show through so honestly.

    My thanks to Woodinville #2 Starbucks for putting up with me rearranging their furniture so I could work byboth the plug-in and the fireplace while I cranked on this book and for keeping those lattes and cappuccinoscoming.

    Finally, I need to acknowledge those people who put up with me the most: my wife Diana, and my kidsChristopher, Kari Anne, Nichole, David, and Joseph. Let's go skiing!

    [ Team LiB ]

  • [ Team LiB ]

    Tell Us What You Think!

    As the reader of this book, you are our most important critic and commentator. We value your opinion andwant to know what we're doing right, what we could do better, what areas you'd like to see us publish in,and any other words of wisdom you're willing to pass our way.

    As an associate publisher for Sams, I welcome your comments. You can fax, e-mail, or write me directly tolet me know what you did or didn't like about this bookas well as what we can do to make our booksstronger.

    Please note that I cannot help you with technical problems related to the topic of this book, and that due tothe high volume of mail I receive, I might not be able to reply to every message.

    When you write, please be sure to include this book's title and author as well as your name and phone or faxnumber. I will carefully review your comments and share them with the author and editors who worked onthe book.

    Fax: 317-581-4770

    E-mail: [email protected]

    Mail: Michael StephensSams Publishing201 West 103rd StreetIndianapolis, IN 46290 USA

    [ Team LiB ]

  • [ Team LiB ]

    Introduction

    Dear Reader,

    Here we are on the brink of what feels like another revolution of computing: .NET. Now I know what somepeople are saying: .NET is merely evolutionary, not revolutionary. I disagree. Here I sit at the San Franciscoairport, waiting for my return flight home to Seattle, sipping on my ice quad venti vanilla latte (yes, that is acoffee drink) pondering all wonderful technology I witnessed this week.

    You see, I spent the past five days sitting in on Paul Sheriff's "Jumpstart Introduction to VB.NET Week."Along with around 20 regular students, Paul had asked a few of his friends who were also interested inpresenting the training down for what is called "Train the Trainer."

    By the time you read this, I will have presented the training myself a few times. I have to admit I have notbeen as excited about a product like this since my early days of working on the Access team. (No snideremarks about Access, please.) I have been working primarily in Access/Visual Basic/SQL Server for the past10 yearsand making a good living at it. The Web daunted me with all that there was to develop for it usingproducts such as ASP and HTML. That has all changed.

    Now the line between developing for the Web and desktop has become almost invisible. Developing withVisual Basic .NET and databases is more powerful than ever, and you can easily blend creating WindowsForms (Visual Basic .NET) and Web Forms (ASP.NET) into the same solution. One of the most exciting thingsis that when you know how to work with ADO.NET using Windows Forms, you can use similar techniques andthe same objects in Web Forms.

    I hope that, with this book, you will become as excited as I am about creating database applications usingVisual Basic .NET!

    Sincerely,

    F. Scott BarkerAuthor, Database Programming with Visual Basic .NET and ADO.NET: Tips, Tutorials, and Code

    [ Team LiB ]

  • [ Team LiB ]

    Who Is This Book For?

    This book is for the serious developer, whether corporate or independent, who wants to create databaseapplications using Visual Basic .NET. If you are looking for a primer on .NET or even a beginner book forVisual Basic .NET, then you would be wise to pick up another book to give you the basics on those topics.This book focuses on the topic I love best: database development.

    Current Visual Basic developers will get quite a bit out of this book. Although you will find that much of VisualBasic .NET looks familiar, the language has grown up quite a bit and even gets more of the respect itdeserves since we can now use the Visual Basic we know and love in Web Forms as well as Windows Forms.Those who are familiar with ADO will appreciate the samples that show how to use ADO.NET. Hopefully, evenhard-core Visual Basic developers will appreciate the chapter on wrapping up some of the ADO.NET dataaccess into classes for simplified coding.

    Those Access developers who are attempting to take the plunge and expand their horizons hopefully will beplaced at ease with how similar developing databases between Access and Visual Basic is. If you havealready worked with SQL Server and ADO, then you are ahead of the game. Even if you haven't developed inVisual Basic previously, this book will give you some great sample code to get started.

    Corporate management will find this book useful for getting an idea of what their developers can do withVisual Basic .NET, both on the desktop and Web sides.

    [ Team LiB ]

  • [ Team LiB ]

    What's Covered in Database Programming with Visual Basic .NET and ADO.NET: Tips, Tutorials, andCode?

    I have laid out this book to logically follow the course of learning how to use the database features of VisualBasic .NET and be as productive as possible, as quickly as possible. Hopefully, you can see this even with theway I have laid out and labeled the chapters:

    Chapter 1, "Developing Windows Forms Using Bound Controls," gets you started being productive fromthe get-go. You will get a great start on creating Windows Forms in Visual Basic .NET that you can usenot only to view data, but also to add, edit, and delete data. You will accomplish this quickly by usingbound controls that are more robust than what is found in previous versions of Visual Basic.

    Chapter 2, "Creating SQL Server Database Objects from Visual Studio .NET," shows you how to usesome of the design tools found inside Visual Studio .NET to create and maintain SQL Server databases.

    Chapter 3, "Viewing Data with ADO.NET," takes you into using the objects found in ADO.NET, such asthe OleDbDataReader and OleDbDataSet. These objects and more are used to view data and load itinto various controls such as list boxes and combo boxes.

    Chapter 4, "Manipulating Data with ADO.NET," takes you further into using the objects found inADO.NET. You will see how to use the various objects in ADO.NET to add, edit, and delete records andmanipulate data.

    Chapter 5, "Working with Data in Web Forms," takes what you learned in the previous chapters andshows you how to create useful Web Forms using ASP.NET, including taking advantage of the DataGridcontrol.

    Chapter 6, "Creating Transact-SQL Commands," brings you deeper into the language that makes SQLServer such a powerful database. It teaches you how to take advantage of the Transact-SQLcommands to update and manipulate your SQL Server database from Visual Basic .NET.

    Chapter 7, "Performing Common Database Tasks Using SQL-DMO," explains how to perform day-to-daytasks in your Visual Basic .NET application that an administrator would normally have to do. Thisincludes common tasks such as importing/exporting data and backing up/restoring databases.

    Chapter 8, "Taking Advantage of Data-Driven Techniques," takes what you have learned in the book sofar and puts it to even more practical use. This chapter shows you how to create utilities that performmore tasks with less code. This chapter demonstrates how to create a point-and-click interface for aquery tool for your users.

    Chapter 9, "Using Classes with Databases to Make Life Easier," shows that even though it can takequite a bit of code to perform data access tasks, you can use classes to wrap that code for accessingdata. By taking table definitions up into properties and methods, you can make accessing data intables more intuitive and simpler to access throughout your applications.

    Chapter 10, "Creating Reports Using Crystal Reports," gets into using crystal reports with Visual Basic.NET. Besides learning how to generate standard reports, you will see how to create some of the moreadvanced features that really take advantage of the engine.

    Chapter 11, "Managing SQL Server Security," discusses the SQL Server security scheme and explainsthe options available to you as a Visual Basic developer. Authentication modes are discussed, as arethe various permissions you might set on SQL Server objects.

  • Chapter 12, "Utilizing XML Data in Your Visual Basic .NET Applications," shows you just how much youcan use XML from within your applications. You are shown how to load and manipulate XML documentobjects, as well as retrieve XML from SQL Server 2000.

    Chapter 13, "Creating XML Web Services," show you how to take advantage of the one of the coolestnew features in .NET. You can create a XML Web Service that both Internet and Desktop applicationscan take advantage of, and even pass ADO datasets.

    Appendix A, "Desktop Development with ADO," discusses the use of ADO in your .NET applications.Although .NET uses ADO.NET, you might have a lot invested in ADO development. This Appendix showshow you can create a reference in your .NET application and what objects there are.

    [ Team LiB ]

  • [ Team LiB ]

    Chapter 1. Developing Windows Forms Using Bound Controls

    In this chapter you will

    Create a bound list box

    Limit the data displayed in a bound list box

    Bind and view individual text boxes based off a selected list box item

    Edit and update data using bound controls

    Add records using bound controls

    Take care of error handling with bound controls

    Put the finishing touches on an add/edit/delete form

    Bind data to ComboBox and DataGrid controls

    Drill down to data in the DataGrid control

    Visual Basic .NET, one of the languages that ships with Visual Studio .NET, is a far more robust languagethan what was found in Visual Basic 6.0. Now, before you VB 6 developers go off and start cussing me forsaying this, read on.

    As in previous versions of Visual Basic, you can use code to bind controls manually, which takes more workthan using bound controls. The other method is to use data bound controls, which in the past were avoidedbecause of not having total control over the way data is handled. In VB .NET, Microsoft has done a better jobof not only creating the data bound controls, but because everything is class-based in the .NET languages,you also can see the code that is generated when you place data bound controls onto a form.

    In the prior versions of Visual Basic, the Microsoft Jet Database Engine was the database flavor of choice forsmall- to medium-sized databases, as well as books such as this one. Now, Visual Basic ships with theMicrosoft SQL Server 2000 Desktop Edition (MSDE). This is a scaled-down version of SQL Server 2000,allowing you to create databases on your local machine and then distribute them for use on a user'sindividual local version of the MSDE or a larger SQL Server 2000 installation. If this sounds intimidating,don't worry. You will learn how to use SQL Server from within Visual Studio and your application. Thisincludes creating utilities for connecting to new databases, as well as backing up and restoring databases.

    Although this book uses the MSDE for the database, you only have to adjust the ConnectionStringproperty of the OleDbConnection object on forms and the ConnectionString property of theOleDbConnection object discussed in Chapter 4, "Manipulating Data with ADO.NET." In the code in Chapter4, you will see a commented line of code that provides an example of using a Jet database version ofNorthwind.

    [ Team LiB ]

  • [ Team LiB ]

    1.1 Create a Bound List Box

    It used to be that when you wanted to create a data entry form, you just assigned a recordset to the datacontrol and allowed the users to scroll through the data, making changes as needed. When you're dealingwith Client Server or Web applications, this just doesn't cut it.

    One of the first things you need to do is provide a method to limit the amount of data so that users can pickwhich record they want to edit/view, without pulling all the fields of a table over the Neteither LAN orInternet. List boxes and combo boxes help with that. In this How-To, you will learn how to set up two datacontrols: OleDbDataAdapter and DataSet. These controls enable you to populate a list box with one lineof code.

    You want to see a list of customers on your Windows form in a ListBox control. You don't want to writecode at this point. You only want to prototype a form, so you just want to use bound data controls. How doyou create a list box and bind it using the data controls?

    Technique

    To get started with learning about any of the objects used for data in .NET, it's important to talk about what.NET Namespaces are and how to use them.

    Using .NET Namespaces

    The .NET Framework contains a big class library. This class library consists of a number of Namespaces.These Namespaces are made up of various classes that allow us to create our objects. All of the objects andclasses that make up the .NET objects, such as forms, controls, and the various data objects, can be foundin Namespaces.

    Namespaces also can be made up of other Namespaces. For example, there is a Namespace calledSystem.Data. Although this Namespace has classes in it, such as DataSet and DataTable, it also hasNamespaces within it called System.Data.OleDb and System.Data.SQLClient, as well as others. Tocheck out the .NET Namespaces, choose Object Browser from the View menu. You can then expand theSystem.Data Namespace to see the other Namespaces contained within.

    If you are positive that the database you are going to be working with is SQL Server, then you would be farbetter served performance-wise to use the classes found in the System.Data.SQLClient Namespace.However, if you are not sure what database you will be working against, you should use the classes found inSystem.Data.OleDb.

    For this book, I am using objects created from the classes in the System.Data.OleDb Namespace. Thatway, you can use the routines against other databases with less modifications.

    Tip

  • If you know that the back end that you will be accessing is SQLServer, then use the SQL Server type data controls because they areoptimized for it.

    Eight data controls are available for Windows forms. Table 1.1 lists these controls and their uses. You canfind these controls by clicking on the Data group in the toolbox.

    Table 1.1. Data Controls Used in Windows Forms

    Control Name Purpose

    DataSet This control is used in conjunction with the other data controls, storing the results thatare returned by commands and the DataAdapters. Unlike the recordset from ADOand DAO, the DataSet actually brings back a hierarchical view of the data. Usingproperties and collections in the DataSet object, you can get all the way down toindividual tables, rows, and columns.

    OleDbDataAdapter This control stores and manages the commands you want to use against an OleDbprovider such as Jet, Oracle, or SQL Server. The commands for selecting, updating,inserting, and deleting records can be used. The Connection against which to use thecommands is also tracked.

    OleDbConnection This control maintains connection information for an OleDb provider. This control isused with the OleDbDataAdapter.

    OleDbCommand Similar to the ADO command object, this control allows you to execute SQLstatements or stored procedures to either run bulk operations or return data.

    SqlDataAdapter This control is the same as the OleDbDataAdapter except that it is for use onlyagainst SQL Server stores.

    SqlConnection This control is the same as the OleDbConnection except that it is for use onlyagainst SQL Server stores.

    SqlCommand This control is the same as the OleDbCommand except that it is for use only againstSQL Server stores.

    DataView This control creates multiple views of the same table. This includes looking at data invarious states such as deleted, changed, or sorted differently.

    Creating two types of the data controls just mentioned, OleDbDataAdapter and DataSet, bind them to alist box to display a list of customers. Note that an OleDbConnection control is also created, but VisualStudio .NET creates it. You then add a line of code to fill the dataset.

    Steps

    To preview this How-To, open the solution called VB.NetChapter1 found in the chapter folder. When yourun the project, the first form that comes up is the main switchboard with each of the How-Tos listed for thischapter. Click on How-To 1.1 to open the form for How-To 1.1 (see Figure 1.1).

    Figure 1.1. Main form and How-To form 1.1 from the first chapter's solution.

  • Note

    You can find the source code for all the chapters in the book atwww.samspublishing.com. After you are there, just type the bookISBN (0672322471).

    Create a new Visual Studio .NET project using the Windows Application project template. This createsthe initial form called Form1 that you will use.

    1.

    Drag the OleDbDataAdapter control from the Data Controls group located in the toolbox and drop itonto the form. The Data Adapter Configuration Wizard appears. Read the introductory screen, and thenclick Next to choose your data connection. At this point, if you don't see a data connection toNorthwind database in the drop-down list of data connections to use, click the New Connection button.You then see the Data Link Properties dialog box with which you are familiar if you have used otherMicrosoft products such as Visual Studio 6.0. Type (local) for the server name, select Use Windows NTIntegrated Security, and select Northwind for the database (see Figure 1.2.) Click OK.

    Figure 1.2. From now on, this data connection will show up in Visual Studio .NET's ServerExplorer on this machine.

    2.

  • Now you will be back on the Choose Your Data Connection page of the Data Adapter ConfigurationWizard, with the Northwind database in the Data Connection drop-down list. Click Next. This brings youto the page to select the query type on which the data adapter will be based. Leave the default of UseSQL Statements, and click Next. In the text box that asks What Data Should the Data Adapter Loadinto the Dataset?, type the following:

    3.

    Select CustomerID, CompanyName From Customers

    Note

    By default, the Data Adapter Configuration Wizard creates selectstatements not only for selecting (viewing) data, but also forinserting, updating, and deleting. If you don't need these otheroptions, click the Advanced Options button at the bottom-left cornerof the dialog box. Deselect the check box that reads GenerateInsert, Update, and Delete statements. You don't need this becausewe are just using the data to fill a ListBox control. Click OK toclose the Advanced Options dialog box.

    Click Next to see results of your select statement, as shown in Figure 1.3. If you see something4.

  • different from Figure 1.3, you either have entered your select statement incorrectly, or you haveforgotten to deselect the advanced options.

    Figure 1.3. Success in creating the data adapter.

    4.

    Click Finished to create a data adapter and connection object. You then see a new data adapter controlcalled OleDbDataAdapter1 and a Connection control called OleDbConnection1. Both controls are inthe Components tray below the Form designer.

    5.

    After you have created the first two controls, it is time to create the Dataset object. Right-click on theData Adapter and choose Generate Dataset from the pop-up menu. This opens the Generate Datasetdialog box. You can keep all the defaults and simply click OK to create a dataset control calledDataSet. (The sequential number might vary if you have generated other dataset controls.)

    6.

    Now you are ready to create the ListBox control. Drag the ListBox control from the Windows Formsgroup in the toolbox and drop it on your form. Stretch the control to the size of your form, and then setthe following properties in Table 1.2 on the ListBox control.

    Table 1.2. ListBox Control Property Settings Needed to Bind a DataSet Control

    7.

  • Property Setting

    DataSource DataSetDisplayMember Customers.CompanyNameValueMember Customers.CustomerID

    Although you have bound the dataset to the correct properties in the ListBox control, if you run theform at this point, you will still see a blank ListBox control on the form.

    Now it is time for the one line of code in this sample, in the Load event of the form. Click on the ViewCode button in the Solution Explorer, or choose Code from the View menu. In the Code Editor, select(Base Class Objects) from the Class Name drop-down list, and then select Load from the Methodsdrop-down list. Next, type the line of code as displayed here, which tells the data adapter to fill thedataset with data:

    8.

    OleDbDataAdapter1.Fill(DataSet1)

    Be sure to use the names of the controls you created. Listing 1.1 presents the Load event codefor the form called frmHowTo1_1 in the samples.

    Listing 1.1 frmHowTo1_1.vb: Filling the Data Set on Which ListBox1 Is Based

    Private Sub frmHowTo1_1_Load(ByVal sender As Object, _ByVal e As System.EventArgs) Handles MyBase.Load

    Me.OleDbDataAdapter1.Fill(Me.DataSet1)

    End Sub

    How It Works

    When the form called frmHowTo1_1 loads, the Fill method of the OleDbDataAdapter1 is called, with theDataSet1 being passed. Because the DataSource property of ListBox1 was specified as being DataSet1and the ValueMember and DisplayMember properties are both set appropriately, ListBox1 is populatedwith the CustomerID and CompanyName from the Customers table in Northwind. Figure 1.4 shows what thefinal form looks like in Design view, and Figure 1.5 shows what it looks like when running.

    Figure 1.4. The final design view for your first database how-to.

  • Figure 1.5. This list is based on the Customers table in the Northwind SQL Server database.

    Comments

    In the .NET version of Visual Basic, Microsoft went to considerable effort to make the data controls morerobust than ever. One cool thing is that most of the tasks that are done for you in Visual Basic .NET arediscoverable. Even though you are using the data controls on your form, Visual Studio creates the codeunder the covers. You can see this code by clicking on the #Region statement that reads like this:

    #Region " Windows Form Designer generated code "

  • Beware: There is much code here, and you don't want to change it. You can learn a lot from reading itthough.

    As you continue to use the Data Controls shown here, you will become comfortable with changing variousproperties and getting more power and use out of them.

    [ Team LiB ]

  • [ Team LiB ]

    1.2 Limit the Data Displayed in a Bound List Box

    Even populating a list box with a couple of columns from a table full of data can be a big performance hit.This How-To shows you how to create a parameterized SQL statement to limit the items that are displayed inthe list box, thus giving you better performance on your forms.

    You have hundreds of thousands of customers in your database, and you don't want the list box loaded upwith the whole customer table. How can you limit the data that is displayed in your list box?

    Technique

    You are going to make a copy of the form that you created in How-To 1.1. You will then add a Label andTextBox control that the Select statement contained within the OleDbDataAdapter control will queryagainst to limit the data displayed in the list box. A command button will be added to allow you to call the Fillmethod of the OleDbDataAdapter control whenever you update the text box, and then you can click thecommand button (see Figure 1.6 ).

    Figure 1.6. You can now limit the amount of data loaded into the list box.

    Steps

    To get started with this How-To, right-click the form you created in How-To 1.1, which should be listed in theSolutions Explorer. Choose Copy from the pop-up menu. Next, right-click the project in the SolutionExplorer, and choose Paste from the pop-up menu. You will now have a new Class object in the SolutionsExplorer called Copy Of whatever the previous name of the form was . Rename the new form that you havecreated to the name you desire. Then, with that form highlighted, click on the Code button above theSolutions Explorer. Change the first line of code to say this:

    Public Class

  • You see, VS does not change the line of code automatically for you. It thinks you have a duplicate Classdefinition.

    Now you can see that the icon of the form is correct. You can continue with the steps of the How-To.

    Select the Data Adapter that you created. In the Properties pane, you will see the CommandText property when youclick on the SelectCommand property plus sign. Replace the CommandText property with the following command:

    1.

    SELECT CustomerID, CompanyName FROM Customers WHERE (CompanyName LIKE ? + '%')

    You will learn more about the Select statement in Chapter 3 . However, the WHERE clause used here comparesCompanyName to a parameter that will be supplied, as indicated by the ?. This will be performed using code inthe final step of this How-To. The % is a wildcard that tells the server to make it a fuzzy search.

    Resize the ListBox control, and leave room at the top of the form for the Label, TextBox, and Command button .Create these three controls, setting the properties described in Table 1.3 .

    Label

    Text

    Customer

    TextBox

    Name

    txtCustLimit

    Text

    A

    Command Button

    Name

    btnLoadList

    Text

    Load List

    Table 1.3. Label, TextBox, and Command Button Control Property Settings

    Object Property Setting

    2.

    Double-click the new command button you just created called btnLoadList . Enter the code in Listing 1.2 in the3.

  • Click event of the btnLoadList button. This code loads the data entered from txtCustLimit into the parameterof the OleDBDataAdapter1 , which was created by using the ? in the Select statement of the data adapter. ThenDataset1 is cleared of its data with the Clear method. Finally, DataSet1 is refilled with data based off the value intxtCustLimit , using the data adapter.

    Listing 1.2 frmHowTo1_2.vb : Submitting a Parameter to a DataAdapter and Filling the Dataset

    3.

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

    Me.OleDbDataAdapter1.SelectCommand.Parameters(0).Value = _ Me.txtCustLimit.Text Me.DataSet1.Clear()

    Me.OleDbDataAdapter1.Fill(Me.DataSet1)

    End Sub

    Note

    There is one big difference here between an OleDbDataAdapter and a SqlDataAdapter. Whereas the OleDbDataAdapter takes a ? to specify a parameter within the Selectstatement, the SqlDataAdapter requires a named parameter such as @parCustLimit .Therefore, instead of the select statement in step 1 being this:

    SELECT CustomerID, CompanyName FROM Customers WHERE (CompanyName LIKE ? + '%')

    It would be this:

    SELECT CustomerID, CompanyName FROM Customers WHERE (CompanyName LIKE @parCustLimit + '%')

    The naming of the actual parameter is up to you.

    Highlight and delete the Load event for the form because you don't want to just fill the event when the form loads.You want the user to click btnLoadList .

    4.

    How It Works

    When the form you created for this How-To loads, or when you're using the form called frmHowTo1_2 , youwill see a blank ListBox control with a text box on top with the letter A in it. If you click the command buttoncalled btnLoadList , the list box becomes filled with values based on the letter (or letters) intxtCustLimit and on the code described in step 3.

    Comments

  • Try entering a few other letters, and then try entering no letters. What happens? You limit the list more bythe number of letters you enter, and you get all entries when you don't enter any letters.

    The method displayed here, although simple, is powerful, and it can be used in a variety of ways.

    You can continue building on this form for the next few How-Tos. If you want to copy your form and start anew one as described at the beginning of the steps for this one, you have the instructions there. Otherwise,by the time you reach How-To 1.8, you will have a data entry form that you can use. Each step, however, isavailable in the sample solution for this chapter.

    [ Team LiB ]

  • [ Team LiB ]

    1.3 Bind and View Individual Text Boxes Based Off a Selected List Box Item

    Using a list box similar to the one in the previous How-To, in this How-To, you will learn how to createadditional OleDbDataAdapter s and DataSets and bind them to individual text boxes for viewing data.

    Although the list box is nice for displaying a couple of fields in my form and limiting the rows displayed, howdo you list the detail in individual text boxes by clicking on an item in the list box?

    Technique

    You are going to enhance the form that you created in How-To 1.2 to use additional data controls,specifically another data adapter and dataset. You will set up the select statement in the new data adapterto take the selected list box item as a parameter. The dataset will then be filled with data, and some textboxes with the dataset set as the data source will display the current record. You can see an example of thisin Figure 1.7 .

    Figure 1.7. You can bind text boxes to datasets as well as list boxes.

    Steps

    To go further with the form with which you have been working, you will want to rename the data adapter,dataset, and list box currently on the form to something more meaningful. You can see this in Table 1.4 .

    ListBox

    Name

    ListBox1

    lstCustomers

  • OleDbDataAdapter

    Name

    OleDbDataAdapter1

    odaCustomerList

    DataSet

    Name

    DataSet1

    dsCustomerList

    Table 1.4. Changes to Current Objects on the Form

    Object Property Old Setting New Setting

    Tip

    Name your objects at the time you first create them. This is true of yoursolutions, projects, and forms, as well as controls used on forms. With the .NETlanguages being so class and code driven, some items take multiple steps torename. Visual Studio doesn't seem to catch all the places in code that need tobe changed. Renaming a form is a good example. Remember that you had tochange the Public Class statement in the code to have it match the new name of

    the form.

    Drop another Data Adapter control on the form from the Data group of the toolbox. Use the existing dataconnection, specify that you will use SQL statements, and assign the following select statement that willuse a parameter supplied at runtime by using the selected list box item.

    1.

    SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers WHERE (CustomerID = ?)

    You can click the Advanced Options button on the select statement page and deselect creating theInsert, Update, and Delete commands. Finish the Data Adapter Wizard and rename the controlodaCustomerIndividual .

    Right-click odaCustomerIndividual and choose Generate Dataset from the pop-up menu. Create anew dataset called dsCustomerIndividual . Click OK. As of this writing, VS places a 1 at the end ofname of the dataset you specified. Clean up the name by removing the 1. Now you should have two dataadapters: odaCustomerList and odaCustomerIndividual , and two datasets: dsCustomerList

    2.

    3.

  • and dsCustomerIndividual .

    Now it's time to add the text boxes. Resize the form so that it allows you to add a column of text boxeswith labels beside them. You will then add the labels and text boxes, setting the Text property of the textboxes to the column names in the Customers table as supplied by dsCustomerIndividual. The Textproperty of text boxes falls under the Data Binding category in the property sheet. Table 1.5 describesthe controls and their property settings. Refer to Figure 1.8 for an example of where to place them.

    Figure 1.8. Letting users know when they can edit data is helpful.

    Label

    Text

    Customer ID

    Label

    Text

    Company Name

    Label

    Text

    Contact

    Label

    Text

    Contact Title

    Label

    Text

    3.

  • Address

    Label

    Text

    City

    Label

    Text

    Region

    Label

    Text

    Country

    Label

    Text

    Phone

    Label

    Text

    Fax

    TextBox

    Name

    txtCustomerID

    Text

    dsCustomerIndividual - Customers.CustomerID

    TextBox

    Name

    txtCompanyName

    Text

    dsCustomerIndividual - Customers.CompanyName

    TextBox

  • Name

    txtContact

    Text

    dsCustomerIndividual - Customers.Contact

    TextBox

    Name

    txtContactTitle

    Text

    dsCustomerIndividual - Customers.ContactTitle

    TextBox

    Name

    txtAddress

    Text

    dsCustomerIndividual - Customers.Address

    TextBox

    Name

    txtCity

    Text

    dsCustomerIndividual - Customers.City

    TextBox

    Name

    txtRegion

    Text

    dsCustomerIndividual - Customers.Region

  • TextBox

    Name

    txtPostalCode

    Text

    dsCustomerIndividual - Customers.PostalCode

    TextBox

    Name

    txtCountry

    Text

    dsCustomerIndividual - Customers.Country

    TextBox

    Name

    txtPhone

    Text

    dsCustomerIndividual - Customers.Phone

    TextBox

    Name

    txtFax

    Text

    dsCustomerIndividual - Customers.Fax

    Table 1.5. New Label and TextBox Control Property Settings for the FormfrmHowTo1_3

    Object Property Setting

    Now it's time for the code. To start off, you will change the Click event code for the button calledbtnLoadList. The first three lines of code are basically the same as in the last How-To, except that thename was changed as needed, and some lines were added to comment the code.

    4.

  • Listing 1.3 frmHowTo1_3.vb : Adding the Call to the RefreshIndividual Subroutine

    4.

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

    ' Store the text entered to limit the list box to the ' data adapter's parameter Me.odaCustomerList.SelectCommand.Parameters(0).Value = _ Me.txtCustLimit.Text ' Clear the current data in the dataset Me.dsCustomerList.Clear()

    ' Fill the customer list dataset Me.odaCustomerList.Fill(Me.dsCustomerList)

    ' Fill the initial entry's individual dataset RefreshIndividual()

    End Sub

    The only new line of code is the one just before the End Sub , which calls the subroutineRefreshIndividual for the first item in the newly populated list box. This subroutine firsthandles clearing the dataset called dsCustomerIndividual . It ensures that a customer ischosen in the list box and then places the selected item into the parameter value forodaCustomerIndividual . The dataset called dsCustomerIndividual is then filled, displayingthe data in the text boxes bound to the dataset.

    Listing 1.4 frmHowTo1_3.vb : Refreshing the Dataset on Which the Text Boxes Are Based

    Private Sub RefreshIndividual()

    ' Clear individual customer dataset Me.dsCustomerIndividual.Clear()

    ' Check to see if an item was selected If lstCustomers.SelectedIndex -1 Then

    ' Store the selected customer ID into the ' parameter of the SQL data adapter Me.odaCustomerIndividual.SelectCommand.Parameters(0).Value = _Me.lstCustomers.SelectedItem(0)

    ' Fill the dataset Me.odaCustomerIndividual.Fill(Me.dsCustomerIndividual)

    End If

    End Sub

    The only other code is required when a new item is selected in the list box. You want to refresh thetext boxes with the new data. This code is on the SelectedIndexChanged event for the

  • lstCustomers list box.

    Listing 1.5 frmHowTo1_3.vb : Call the RefreshIndividual Routine

    Private Sub lstCustomers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles lstCustomers.SelectedIndexChanged ' Fill the current list item's individual dataset RefreshIndividual()

    End Sub

    How It Works

    After the user types a letter into the txtCustLimit text box and clicks btnLoadList , the list box ispopulated with the items that match the text in the text box. After lstCustomers is populated, the usersees the details for the first item in the list box that is displayed in the text boxes. This occurs within theroutine called RefreshIndividual . The selected item is used for the parameter for the data adaptercalled odaCustomerIndividual , then filling the dataset called dsCustomerIndividual . As the userselects new items in the list box, the data that corresponds to the selected item is displayed.

    Tip

    Always try to break your code into specific routines such as the subroutineRefreshIndividual . That way when someone tries to read the code, the codeis easy to read, you don't make mistakes by typing the same code two or moretimes, and you only have to change the code in one place if necessary.

    Comments

    Binding text boxes to datasets saves work when switching from one record to another because you don'thave to specifically load each text box with data each time. It also gets easier every time you use a dataadapter and dataset in combination when manipulating data on your forms.

    Bound datasets are particularly useful as you edit, add, and delete data on your forms, as you will see in thefollowing How-Tos.

    [ Team LiB ]

  • [ Team LiB ]

    1.4 Edit and Update Data Using Bound Controls

    Although viewing data is fine in some situations, the real power comes in being able to edit the data in thetext box and update the data in the server. In this How-To, you learn just that, using some new methodsand properties from the various data controls, including autogenerated commands that create update,insert, and delete SQL statements for you. This How-To also introduces you to the BinderContext class ,which is used to perform updates with bound controls.

    The form as created in How-To 1.4 is great if you just want to view data for various records. But what if youwant to let users edit and update the data?

    Technique

    Continuing with the form you used in the previous How-Tos, you are going to add a few command buttonswith code that will perform the following:

    Edit. Toggle the look of the text boxes to let the user know that he can edit the data in the controls bygiving the controls a sunken look.

    Save. Save the changes made to the data back to the server. Then toggle the look of the text boxesback to flat so that the user knows he can't edit them.

    Cancel. Toggle the text boxes back to flat so that the user knows he can't edit them anymore, butdon't save the data.

    It is important to let users know when they can edit and when they can't. By toggling the style of the textboxes between flat and sunken and the color between gray and white, users have a definite clue that theycan edit the data at certain times (see Figure 1.8 ).

    Another useful item to note about this How-To is the introduction of the BindingContext class. This classhelps you work with data bound controls. Each control on a Windows form has a BindingContext object aswell as BindingContext objects for any controls that are contained within that control. Each form also hasa BindingContext object. BindingContext objects manage BindingManagerBase class object(s) foreach control. Through the BindingContext object, you can manage editing and updating data back to theserver. BindingManagerBase objects help with synchronization of datasets with controls. You are going touse the BindingContext class throughout the rest of this chapter, but only a couple of methods.

    Steps

    Open the solution for the chapter called "VB .NET How-To Chapter 1 ," and run the application. From themain form, click the command button with the caption "How-To 1.4." Click the Load List button . Along withthe list being filled with customers whose names start with A , you will see the detail How-To fill in on theright side of the form with the first customer in the list. Click Edit. You will now be able to change the data inthe text boxes. After you have changed a couple of fields, click Save. If you select another customer fromthe list box, select the one you changed. You will see that your changes have in fact been saved. If you clickCancel instead of Save, your changes will not be saved. Note that if you change the name of the customer,you must load the list again to see the changes in the list box.

    Add the three command buttons to your form as described in Table 1.6 and as displayed in Figure 1.8 .1.

  • Command Button

    Name

    btnEdit

    Caption

    &Edit

    Command Button

    Name

    btnSave

    Caption

    &Save

    Command Button

    Name

    btnCancel

    Caption

    &Cancel

    Table 1.6. Command Buttons to Edit, Save, and Cancel Changes to Data

    Object Property Setting

    1.

    Add the code shown in Listing 1.6 to the btnEdit Click event.

    Listing 1.6 frmHowTo1_4.vb : Calling the ActiveEditing Subroutine from the btnEdit Command Button

    2.

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

    ' Enable the editing of the form ActivateEditing(True)

    End Sub

  • This calls the routine called ActivateEditing , listed here. This code iterates through all the controls onthe form and uses the TypeOf condition to check whether the current control is a text box. It also ensuresthat the control is not the txtCustLimit text box. If the control is a text box and the parameter calledbEnable has been passed in as True , then the sunken look is given to the text box using theBorderStyle and the BackColor property is set to white. Otherwise, the BorderStyle is set toFixedSingle , which is flat, and the BackColor is set to the backcolor of the form. The Enabledproperty of the text box is set to whatever bEnabled is: True or False .

    Listing 1.7 frmHowTo1_4.vb : Toggling the Enabled Property and Look of Text Boxes

    Private Sub ActivateEditing(ByVal bEnable As Boolean)

    Dim oCurr As Object

    ' Loop through each of the controls on the form For Each oCurr In Me.Controls()

    ' Check to see if the control is a text box If TypeOf oCurr Is TextBox And oCurr.Name "txtCustLimit" Then

    ' If so, toggle the properties If bEnable Then

    oCurr.BorderStyle() = _ System.Windows.Forms.BorderStyle.Fixed3D

    oCurr.BackColor() = System.Drawing.Color.White

    Else

    oCurr.BorderStyle() = _ System.Windows.Forms.BorderStyle.FixedSingle

    oCurr.BackColor() = Me.BackColor

    End If

    oCurr.Enabled = bEnable

    End If Next

    End Sub

    Add the code to the Click event of the btnSave command button. This code calls a new routine calledSaveRecord , which performs the actual save. The ActivateEditing is then called, passing False to disablethe controls because you are finished editing.

    Listing 1.8 frmHowTo1_4.vb : Calling the SaveRecord Routine and Disabling the Text Boxes by CallingActivateEditing

    3.

  • Private Sub btnSave_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSave.Click

    ' Save the information SaveRecord()

    ' Disable the text boxes ActivateEditing(False)

    End Sub

    Following is the code for the subroutine called SaveRecord . This routine calls the EndCurrentEditmethod of the BindingContext class, passing in the dataset called dsCustomerIndividual , andspecifying the Customers table. Then the Update method is called off the data adapter calledodaCustomerIndividual , passing the same parameters. This updates the changes back to the dataset.Finally, the dataset changes are sent back to the server.

    Listing 1.9 frmHowTo1_4.vb : Saving the Data Back to the Server

    Private Sub SaveRecord()

    ' Use the BindingContext class to end current editing ' so that we can update the server. Me.BindingContext(Me.dsCustomerIndividual, "Customers").EndCurrentEdit()

    ' Perform the requested task at the dataset ' level using the data adapter Me.odaCustomerIndividual.Update(Me.dsCustomerIndividual, "Customers")

    ' By accepting the changes, the data gets sent back to the server Me.dsCustomerIndividual.AcceptChanges()

    End Sub

    Note

    If you haven't read about ADO.NET yet, then you might be confused about doing anupdate to the dataset, accepting changes, and sending the changes back to the server.ADO.NET works using disconnected data. When you create a dataset by using a dataadapter, the data is actually created using XML. To see proof of this, take a look atdsCustomerIndividual.xsd, found in the Solutions Explorer.

  • This is all performed under the covers, so the good news is that you don't have to know XML to work withdatasets and ADO. More information on this can be found in Chapter 3 .

    The last task is to give you the capibility to cancel the edits. You do this by placing the following code in theClick event on btnCancel . Calling the CancelCurrentEdit method of the BindingContext object for theform, the current edits are cancelled. Next, the text boxes are disabled using the routine ActivateEditing.

    Listing 1.10 frmHowTo1_4.vb : Canceling Changes to Data and Disabling the Text Boxes Again

    4.

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

    ' Use the BindingContext class to cancel the current editing. Me.BindingContext(Me.dsCustomerIndividual, _ "Customers").CancelCurrentEdit() ActivateEditing(False)

    End Sub

    How It Works

    When the user clicks the btnEdit button, the ActiveEditing routine alerts the user that he can edit thedata in the text boxes. The text boxes are enabled.

  • If the user then clicks the btnSave button, the data is updated to the dataset and then back to the server. Ifthe user clicks the btnCancel button, the edits are canceled. In both cases, the ActivateEditing routineis called to disable the text boxes and let the user know that the text boxes cannot be edited.

    Comments

    This How-To showed the bare bones for editing and updating data. It presented a basic technique to getstarted. As you continue, you will learn methods to add and delete records, as well as handle errors.

    Using ADO.NET, which you use for bound controls, takes some getting used to if you have worked with otherdata accessing methods such as ADO and DAO. The BindingContext and BindingManagerBase objectsmake working with bound objects in code much more manageable.

    [ Team LiB ]

  • [ Team LiB ]

    1.5 Add and Delete Records Using Bound Controls

    Besides editing data, adding new records and deleting records in a table are obviously important features.This How-To shows you just that, taking advantage of the BinderContext class.

    Besides being able to edit current records that already exist, users need to be able to add and delete recordsas well. How do you add and delete records using bound controls?

    Technique

    To create the Add New Record feature, you will add a button called btnAddNew that has code behind it. Youwill use the BindingContext object again to add a new record by using the AddNew method . A modulevariable will be added to the form to keep track of whether a record is being added or edited. If a new recordis being added, then when the update is performed, the application needs to reload the data in the list box incase the new record's CompanyName data falls into the chosen list limit that is specified in thetxtCustLimit text box.

    To create the Delete Record feature, you will add a button called btnDelete . This button will have codebehind it that will use the RemoveAt method of the ContextBinding object to remove the record from thedataset. The data will then be posted back to the server.

    Steps

    Open the solution for the chapter called "VB .NET How-To Chapter 1 ," and run the application. From themain form, click on the command button labeled How-To 1.5. Click the Load List button . Click the buttonlabeled New. Enter the text ALF for Customer ID and Alfred's Fried Foods in the Company Name.Then click the button labeled Save, and see the record you just entered added to the list. After the recordhas been entered, you can test the delete feature by clicking on the button named Delete. The record goesaway, and the list is rebuilt.

    Add a new command button under btnEdit , and then set the Name property to btnNew and theCaption property to &Save .

    1.

    Add a new module-level variable called mbAddNew , which is a Boolean variable to keep track of whetheryou are adding a new record. This variable will be placed outside of your routines, just under the formscode. You can see this in Figure 1.9 .

    Figure 1.9. By placing this variable just underneath Windows Form Designer Generated Codeand declaring it Private, routines inside the Class can see it, but those outside cannot.

    2.

  • Tip

    You can collapse and expand routines that you are working on within modules.This makes it handy when you are working on new routines (which can beexpanded) and don't want to mess with old routines (which can be collapsed).

    Add the following code to the Click event of the new command button btnNew . This code first sets theBoolean variable called mbAddNew to True . It then uses the AddNew method of the form'sBindingContext object to add a new record to the dsCustomerIndividual dataset. Finally, the codecalls the ActiveEditing routine to enable the text boxes.

    Listing 1.11 frmHowTo1_5.vb : Adding a New Record to the dsCustomerIndividual Datasetand Toggling Text Boxes

    3.

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

    mbAddNew = True

    ' Using the BindingContext class add a new record Me.BindingContext(Me.dsCustomerIndividual, "Customers").AddNew()

    ActivateEditing(True)

  • End Sub

    Modify the Click event of the btnSave to test whether the mbAddNew flag has been set to True ,meaning that a new record is being added. If True , then after saving the record by calling theSaveRecord and ActivateEditing routines, the LoadList and RefreshIndividual are called toload the new record's data. Note that the SaveRecord, ActiveEditing , and RefreshIndividualroutines have not changed from How-To 1.4. The mbAddNew variable is then set to False .

    Listing 1.12 frmHowTo1_5.vb : Saving the Changed Data, Toggling Text Boxes, and Reloadingthe List Box and First Record in the List

    4.

    Private Sub btnSave_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnSave.Click

    ' Save the information SaveRecord()

    ' Disable the text boxes ActivateEditing(False)

    If mbAddNew Then LoadList() RefreshIndividual() mbAddNew = False End If

    End Sub

    Modify the Click event for the btnCancel button to reset the mbAddNew variable to False , as seen inListing 1.13 .

    Listing 1.13 frmHowTo1_5.vb : Canceling the Edit and Resetting the mbAddNew Variable

    5.

    Private Sub btnCancel_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnCancel.Click

    ' Use the BindingContext class to cancel the current editing. Me.BindingContext(Me.dsCustomerIndividual, "Customers").CancelCurrentEdit()

    ActivateEditing(False) mbAddNew = False

    End Sub

    Now it is time to add the delete functionality. To do this, add the following code to the Click event ofthe new button called btnDelete . The first line of the code you added begins by introducing a newmethod called RemoveAt and a new property called Position, both used with the BindingContext

    6.

  • object. You will work from the inside out. The Position property tracks the current position in thedataset, in this case dsCustomerIndividual. The RemoveAt method marks the record that is at theposition passed to it for deletion.

    Next, the Update method of the odaCustomerIndividual adapter is used to call the DELETE SQLstatement command against the dataset, deleting the actual rows in the data set. The AcceptChangesmethod is called to send the changes to the dataset, a delete in this case, back to the server. Finally, theLoadList , RefreshIndividual , and ActivateEditing subroutines are called to refresh the list,refresh the first record in the list for the text boxes, and toggle the text boxes so that the user knows hecan't edit them.

    Listing 1.14 frmHowTo1_5.vb : Deleting the Selected Record and Reloading the List Box

    6.

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

    ' Mark the row for deletion using the RemoveAt method of the BindingContext Me.BindingContext(Me.dsCustomerIndividual, _ "Customers").RemoveAt(Me.BindingContext(Me.dsCustomerIndividual, "Customers").Position)

    ' Perform the requested task at the dataset ' level using the data adapter odaCustomerIndividual.Update(dsCustomerIndividual, "Customers")

    ' By accepting the changes, the data gets sent back to the server dsCustomerIndividual.AcceptChanges()

    ' Reload the list LoadList()

    ' Display the first record RefreshIndividual()

    ' Disable the text boxes ActivateEditing(False)

    End Sub

    How It Works

    When the user clicks the btnNew button, a flag (mbAddNew ) is set to True , the dataset is set for adding arecord with the AddNew method of the BindingContext , and the text boxes are enabled for editing.

    If the user then clicks the btnSave button, the data is updated to the dataset and then back to the server.If the user clicks the btnCancel button, the edits are canceled. In both cases, the mbAddNew variable isset to False and the ActivateEditing routine is called to disable the text boxes and let the user knowthat the text boxes are not available for editing. Finally, if the btnSave button was clicked and the mbAddNewwas set to True , the LoadList and RefreshIndividual routines are called.

    When the user clicks the btnDelete button, the record is deleted from the recordset and then from theserver. The list box is reloaded and the first record in the list is displayed in the text boxes. The text boxesare then disabled.

  • Comments

    Here you have the basic commands needed to create a full-fledged data entry form. You can add, edit, anddelete information from the form. This actually takes less code than if you use Visual Basic 6.0.

    The BindingContext object really goes a long way to helping you work with bound data.

    [ Team LiB ]

  • [ Team LiB ]

    1.6 Take Care of Error Handling with Bound Controls

    When dealing with database tasks, you are going to get runtime errors. In .NET, we call the various types oferrors you can get exceptions. This How-To shows examples of what exceptions could occur and how tohandle them using the Try, Catch, and Finally statements.

    Adding and deleting records is fine, but what happens if an error occurs? You tried to delete an existingcompany, and got the screen that appears in Figure 1.10.

    Figure 1.10. This is an unhandled error, called an exception in .NET.

    How do you make it so errors are handled gracefully within the application using bound controls?

    Technique

    Error handling is one of the most important aspects of working with data, between when a user is enteringdata and updating the server. If you don't have proper error handling, your system will, in the best situation,give an ugly error message, and in the worst, blow up and put bad data in your system. In Visual Studio.NET, errors are classes called exceptions. Many different (inherited) types of exceptions exist.

    Run-time exceptions can occur in just about any part of your application. They can be handled by usingTry...Catch...Finally or they can be unhandled, where you will see the error in Figure 1.11.

    Figure 1.11. This error was thrown up from one subroutine to the one that called it.

    Take a look at a common way to trap exceptions shown in Listing 1.15.

    Listing 1.15 Standard Code for Handling Exceptions

  • Private Sub MySub()

    Try

    'Code to be handled here

    Catch dataException as Exception

    MessageBox.Show(dataException.Message)

    Finally

    'Code that will occur regardless of if an error occurs.

    End Try

    End Sub

    Following are some basic points to help you when working with exceptions and Try...Catch...Finallyblocks:

    The name of the exception object can be whatever you want it to be. dataException was just used asan example.

    Specific types of exceptions inherit from the base class of System.Exception. OleDbException isone of those classes, and you will see an example of using this class in the following steps.

    You can use the Throw statement within a Catch statement to throw the exception back up to acalling subroutine.

    You can use the When clause on the Catch statement to trap for specific exceptions.

    When multiple Catch statements are used, each one is executed unless an End Try or End Sub isplaced within a Catch block, as in this How-To.

    You can use multiple Catch statements to handle various possible exceptions that can occur.

    You will see an example of these bullets in the following steps.

    Steps

    Taking the form with which you have been working, you are going to modify it to trap exceptions when therecord is being saved (either for additions or editing) and when the record is deleted. You will also add somecode in the event when closing the form.

    Modify the code in the Click event of the command button called btnSave. You will surround theSaveRecord routine call with a Try...Catch...End Try block. If an exception occurs, the Showmethod of the MessageBox class is called, passing the Message property of the Exception objectcalled saveException. Next, the subroutine is exited. If no errors occur, then life goes on, and sodoes the subroutine.

    1.

  • Listing 1.16 frmHowTo1_6.vb: Code Added to btnSave Click Event to Trap Save Exceptions

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

    Try

    ' Save the information SaveRecord()

    Catch saveException As Exception

    MessageBox.Show("The following error has occurred: " & _saveException.Message, "Error Saving Record") Exit Sub

    End Try

    ' Disable the text boxes ActivateEditing(False)

    If mbAddNew Then LoadList() RefreshIndividual() mbAddNew = False End If

    End Sub

    Modify the SaveRecord routine to "throw" the exception up to the btnSave_Click subroutine, orwhatever happens to have called the SaveRecord routine. Following is the SaveRecord subroutinewith the new Try...Catch...End Try block added, along with the Throw statement.

    Listing 1.17 frmHowTo1_6.vb: Pass the Exception Back Up to the Calling Routine

    2.

    Private Sub SaveRecord()

    Try

    ' Use the BindingContext class to end the current editing so ' that we can update the server. Me.BindingContext(Me.dsCustomerIndividual, _ "Customers").EndCurrentEdit()

    ' Perform the requested task at the dataset ' level using the data adapter odaCustomerIndividual.Update(dsCustomerIndividual, "Customers")

    ' By accepting the changes, the data gets sent back to the server dsCustomerIndividual.AcceptChanges()

  • Catch saveException As Exception

    Throw saveException

    End Try

    End Sub

    Now it's time to deal with adding exception handling to the btnDelete Click event, as seen next.The Try statement is used to wrap the code that performs deletion of the data. The code then uses aCatch statement to check whether the exception that occurs is a specific OleDbException, 3621,which is an error having to do with trying to delete a record when related records exist in anothertable. Note that you couldand in fact shouldassign this to a constant value. BecausedelException has been caught as an OleDbException, you can look at the NativeError propertyof the first error in the Errors collection to get the actual OleDb error number. If the error is not 3621,then the exception is trapped with the next Catch statement, and a messagebox is displayed. Iferrors occur, then the subroutine is exited before the final lines of code are executed.

    Listing 1.18 frmHowTo1_6.vb: Catching Exceptions When You're Deleting a Record

    3.

    Private Sub btnDelete_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnDelete.Click

    Try ' Mark the row for deletion using the RemoveAt ' method of the BindingContext Me.BindingContext(Me.dsCustomerIndividual,"Customers").RemoveAt(Me.BindingContext(Me.dsCustomerIndividual,"Customers").Position)

    ' Perform the requested task at the dataset ' level using the data adapter odaCustomerIndividual.Update(dsCustomerIndividual, "Customers")

    ' By accepting the changes, the data gets sent back to the server dsCustomerIndividual.AcceptChanges()

    Catch delException As System.Data.OleDb.OleDbException _ When delException.Errors(0).NativeError = 3621

    MessageBox.Show("An error occurred because of related order records.","Error Deleting Customer", _ MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub

    Catch delException As Exception

    MessageBox.Show(delException.Message, "Error Deleting Customer", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    Exit Sub

    End Try

  • ' Reload the list LoadList()

    ' Display the first record RefreshIndividual()

    ' Disable the text boxes ActivateEditing(False)

    End Sub

    How It Works

    When an exception occurs within the Try...Catch...End Try block, the Catch statements are comparedwhen a When clause is used or when the code is simply executed. If a Throw statement is used, then anexecution is thrown back up a level to the Try...Catch...End Try block containing the call to the routinewhere the Throw statement occurred. You can see an example of this in Figure 1.11.

    Comments

    Microsoft has gone to great length to let you control how you handle exceptions in .NET with the variouslanguages. You can be as creative as you need to by using the Try...Catch...End Try block with all theclauses available.

    Exceptions bring back plenty of information so that you can create pretty slick error handling. You can useexceptions to create a centralized routine that logs errors, or even one that e-mails exception information toyou from your applications.

    [ Team LiB ]

  • [ Team LiB ]

    1.7 Put the Finishing Touches on a Data Bound Form

    Besides handling the basics, you need to add some finishing touches to a data entry form, such asenabling/disabling controls based on whether you're on a record. This How-To shows you how to use theEnabled properties on controls to give the user more direction when using a Windows form (see Figure 1.12).

    Figure 1.12. You will create this complete form by How-To 1.7, with all the bells and whistles thatusers expect from a good data entry form.

    Although the majority of the major issues are taken care of for the form you created so far in the chapter,your users become confused about when to push some of the buttons. How do you get the buttons to reflectwhen the users can click them, and what other finishing touches might help the form?

    Technique

    An important part of user interfaces is letting the user know when he has access to certain features on theform. In this case, you will see how to do the following:

    Toggle the enabled property of the btnSave , btnCancel , btnNew , and btnDelete at theappropriate moments, such as when a record is highlighted in the list box.

    Add a command button to close the form.

    Add code to the Closing event of the form that tests whether you have made changes to the currentrecord, and if so, whether you want to save the changes.

    You can see an example of particular command buttons being enabled based on the current action beingperformed in the form in Figure 1.13 .

    Figure 1.13. This form allows users to access command buttons only when the functionality is

  • available.

    Steps

    Continuing on with the form that you have been using, you are going to make the changes just mentioned inthe previous bulleted list.

    Start by modifying two routines already created: RefreshIndividual and ActivateEditingsubroutines. Then check whether a customer has been selected in lstCustomers . If not, then the twobuttons, btnEdit and btnDelete, are disabled. If a customer hasn't been selected, the two buttons areenabled, and the dsCustomerIndividual dataset control is refreshed.

    Listing 1.19 frmHowTo1_7.vb : Toggling the Enabled Property of the btnEdit and btnDeleteButtons

    1.

    Private Sub RefreshIndividual()

    ' Clear individual customer dataset Me.dsCustomerIndividual.Clear()

    If lstCustomers.SelectedIndex = -1 Then btnEdit.Enabled = False btnDelete.Enabled = False Else btnEdit.Enabled = True btnDelete.Enabled = True

    Me.odaCustomerIndividual.SelectCommand.Parameters(0).Value =lstCustomers.SelectedItem(0)

    ' Fill the dataset Me.odaCustomerIndividual.Fill(Me.dsCustomerIndividual, "Customers")

    End If

  • End Sub

    Similarly, you will add code to the ActivateEditing subroutine to toggle the Enable property ofthe various command buttons, depending on their purpose. Listing 1.20 shows the entire routine.

    Listing 1.20 frmHowTo1_7.vb : Toggling the Enabled Property of btnEdit and btnDeleteButtons

    Private Sub ActivateEditing(ByVal bEnable As Boolean)

    Dim oCurr As Object

    ' Loop through each of the controls on the form For Each oCurr In Me.Controls()

    ' Check to see if the control is a text box If TypeOf oCurr Is TextBox And oCurr.Name "txtCustLimit" Then

    ' If so, toggle the properties If bEnable Then

    oCurr.BorderStyle() = _ System.Windows.Forms.BorderStyle.Fixed3D

    oCurr.BackColor() = System.Drawing.Color.White

    Else

    oCurr.BorderStyle() = _ System.Windows.Forms.BorderStyle.FixedSingle

    oCurr.BackColor() = Me.BackColor

    End If

    oCurr.Enabled = bEnable

    End If Next

    ' Enable/Disable the appropriate buttons btnEdit.Enabled = Not bEnable btnNew.Enabled = Not bEnable btnDelete.Enabled = Not bEnable

    btnCancel.Enabled = bEnable btnSave.Enabled = bEnable

    ' Set the focus to the CustomerID text box If bEnable Then Me.txtCustomerID.Focus() End If End Sub

  • The specific lines of code added are shown here:

    ' Enable/Disable the appropriate buttons btnEdit.Enabled = Not bEnable btnNew.Enabled = Not bEnable btnDelete.Enabled = Not bEnable

    btnCancel.Enabled = bEnable btnSave.Enabled = bEnable

    These buttons are handled as the other buttons areby taking the opposite value to which bEnableis currently set, and using it to toggle the Enabled property.

    Finally, if the bEnable flag is True , then focus is moved to the txtCustomerID text box using thefollowing lines of code:

    ' Set the focus to the CustomerID text box If bEnable Then Me.txtCustomerID.Focus() End If End Sub

    Add a new command button, with the properties Name and Text set to btnClose and &Close ,respectively. Place the code in Listing 1.21 for the Click event.

    Listing 1.21 frmHowTo1_7.vb : Close the Form

    2.

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

    Me.Close()

    End Sub

    Add some code to the Closing event of the form. Listing 1.22 tests whether the btnSave button isenabled. If it is, the MessageBox method is evoked, asking the user if he wants to save changes thatwere made. If so, then the SaveRecord is called within a Try...Catch...End Try block.

    Listing 1.22 frmHowTo1_7.vb : Checking Whether the User Wants to Save a Record BeforeClosing

    3.

    Private Sub frmHowTo1_7_Closing(ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing

    ' If an edit or add has been requested, enabling the Save button, ' then prompt to save the record

  • If btnSave.Enabled Then

    If MessageBox.Show("Would you like to save the current record?", _ "Save Record?", MessageBoxButtons.YesNo) = _ DialogResult.Yes Then Try

    ' Save the information SaveRecord()

    Catch saveException As Exception

    If MessageBox.Show("The following error has occurred: " & saveException.Message & vbCrLf & vbCrLf & _ "Continue with closing the form?", "Error Saving Record", MessageBoxButtons.YesNo) = DialogResult.No Then e.Cancel = True End If

    End Try End If End If

    End Sub

    How It Works

    In the modifications made to the form in this How-To, many things happen depending on what is occurring.When the user clicks the btnEdi t button, btnEdit , btnNew , and btnDelete are disabled, andbtnCancel and btnSave are enabled. The opposite is true when btnCancel and btnSave are pressed. IfbEnable is True , then the focus is moved to the txtCustomerID text box.

    When the txtClosed button is clicked, the application then checks whether the btnSave command buttonhas been enabled, meaning data is being edited. If so, then the user is asked whether he wants to save thecurrent record. If the user does, the system then saves the current information back to the server.

    Comments

    The tasks displayed in this How-To are just a few of the tasks you can do to make your forms look and feelmore professional. They are also what users come to expect from database applications.

    Play with the form a bit more. You're sure to come up with a few more ideas.

    [ Team LiB ]

  • [ Team LiB ]

    1.8 Bind Data to ComboBox and DataGrid Controls

    Sometimes you might want to use a ComboBox control instead of a ListBox control to display a list ofchoices. You also might want to display information in a grid style based on the item chosen in that combobox. This How-To describes how to bind data to both ComboBox and DataGrid controls.

    Instead of using a ListBox control to display customers, you would like to use a ComboBox control todisplay them. After you choose a customer, you would like to display information about the orders thatbelong to that customer. How do you bind data to the ComboBox and then bind the DataGrid control aswell?

    Technique