Windows Database Updates

Similar documents
Chapter 3. Windows Database Applications The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Chapter 4. Windows Database Using Related Tables The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Windows Database Applications

Programming with ADO.NET

C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies. Objectives (1 of 2)

CSC 330 Object-Oriented

How to use data sources with databases (part 1)

Chapter 10. Database Applications The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

ADO.NET 2.0. database programming with

VS2010 C# Programming - DB intro 1

CIS 209 Final Exam. 1. A Public Property procedure creates a property that is visible to any application that contains an instance of the class.

How to work with data sources and datasets

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Data Binding. Data Binding

1. A Web Form created in Visual Basic can only be displayed in Internet Explorer. True False

Introduction to using Visual Studio 2010 to build data-aware applications

DataGridView FAQ.doc. DataGridView FAQ.doc

Kendo UI. Builder by Progress : What's New

Building Multitier Programs with Classes

Microsoft Visual C# 2005: Developing Applications Table of Contents

Report Designer Report Types Table Report Multi-Column Report Label Report Parameterized Report Cross-Tab Report Drill-Down Report Chart with Static

Release Notes ClearSQL (build 181)

ADO.NET Using Visual Basic 2005 Table of Contents

DbSchema Forms and Reports Tutorial

Programming Logic -Intermediate

Index. AutoNumber data types, 154 6, 168 and Number data type, 181 AutoPostBack Property, 505, 511, 513 5, 527 8, AVG, 242, 247 8

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

DbSchema Forms and Reports Tutorial

Chapter 14. Additional Topics in C# 2010 The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

You can also check the videos at the bottom of this page:

Imagine. Create. Discover. User Manual. TopLine Results Corporation

Database Tutorials

SQL Server. Management Studio. Chapter 3. In This Chapter. Management Studio. c Introduction to SQL Server

Contents. Chapter 1 Introducing ADO.NET...1. Acknowledgments...xiii. About the Authors...xv. Introduction...xix

About the Authors Introduction p. 1 Exploring Application Architectures p. 9 Introduction p. 9 Choosing the "Right" Architecture p.

DTS. The SQL Server 2000 client installation adds the necessary components for creating DTS packages. You can save your DTS packages to:

10Tec igrid for.net 6.0 What's New in the Release

Building Datacentric Applications

Copy Datatable Schema To Another Datatable Vb.net

COMM 391. Objectives. Introduction to Microsoft Access. What is in an Access database file? Introduction to Microsoft Access 2010

DOT NET Syllabus (6 Months)

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.)

Chapter 13. Additional Topics in Visual Basic The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Introduction to using Microsoft Expression Web to build data-aware web applications

Roxen Content Provider

Ocean Wizards and Developers Tools in Visual Studio

If this is the first time you have run SSMS, I recommend setting up the startup options so that the environment is set up the way you want it.

Dataflow Editor User Guide

Application Aspect. Hierarchical DataGridView v1.7 BOOKLET

Data Gr id Vie w C ont ro l

CIS Intro to Programming in C#

Microsoft Access 2010

Chapter 10 Databases

Chapter 4: Single Table Form Lab

Chapter 02 Building Multitier Programs with Classes

KB_SQL Release Notes Version 4.3.Q2. Knowledge Based Systems, Inc.

FirePower 4.1. Woll2Woll Software Nov 3rd, Version 4.1 Supporting RAD Studio versions: XE7. FirePower 4.

Administration. Training Guide. Infinite Visions Enterprise Edition phone toll free fax

A. Local B. Module C. Regional D. Global. 2. What is the standard size of the 4GL screen?

Saikat Banerjee Page 1

DEVELOPING DATABASE APPLICATIONS (INTERMEDIATE MICROSOFT ACCESS, X405.5)

IBM i Version 7.2. Database Database overview IBM

CO Environmental Web Application Users Help. March 2012 Updated June 2012 Updated March 2014

overview of, ASPNET User, Auto mode, 348 AutoIncrement property, 202 AutoNumber fields, 100 AVG function, 71

Access Made Easy. Forms.

Exploring Microsoft Office Access Chapter 2: Relational Databases and Multi-Table Queries

Table Basics. The structure of an table

Contents. Properties: Field Area Fields Add a Table to a Form... 23

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Jet Data Manager 2014 SR2 Product Enhancements

Working with Data in ASP.NET 2.0 :: Using Existing Stored Procedures for the Typed DataSet s TableAdapters Introduction

Editing ITP MLR Address Table Files

Acknowledgments Introduction. Chapter 1: Introduction to Access 2007 VBA 1. The Visual Basic Editor 18. Testing Phase 24

.NET FRAMEWORK. Visual C#.Net

IBM. Database Database overview. IBM i 7.1

POS Designer Utility

The Scheduler & Hotkeys plugin PRINTED MANUAL

Chapter 1 Getting Started

About the Author... xiii Introduction... xiv Acknowledgments and Thanks... xv Terminology... xvii Sample Code... xvii

Cross-loading of Legacy Data Using the Designer/2000 Repository Data Model OBJECTIVES ABSTRACT

Release Notes. PREEvision. Version 6.5 SP11 English

EasyCatalog For Adobe InDesign

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Find and Filter Records on a Form

User Guide Product Design Version 1.7

ArcGIS Extension User's Guide

Introduction to Acumatica Framework

Logi Ad Hoc Reporting System Administration Guide

Direct Connect and Dial-Up on Windows 98

Perceptive Intelligent Capture Project Migration Tool. User Guide. Version: 2.0.x

Assembling a Three-Tier Web Form Application

Contents. Add a Form Element to a Group Box Add a Field to a Form... 22

Connect Databases to AutoCAD with dbconnect Nate Bartley Test Development Engineer autodesk, inc.

Chapter 2. DB2 concepts

Quick & Simple Imaging. User Guide

Logi Ad Hoc Reporting System Administration Guide

Component Templates. The Component Template Item Type. Modified by Jason Howie on 31-May-2017

Lab 5: ASP.NET 2.0 Profiles and Localization

Management Reports Centre. User Guide. Emmanuel Amekuedi

Kendo UI. Builder by Progress : Using Kendo UI Designer

Transcription:

5-1 Chapter 5 Windows Database Updates This chapter provides instructions on how to update the data, which includes adding records, deleting records, and making changes to existing records. TableAdapters, datasets, and binding sources are used. Objectives Update a database table in a grid and in individual controls Use the BindingSource properties for navigation and for determining the current record number Update the original data source by saving the values from a dataset Validate user input in an update program Sequence the update statements to accurately update related tables 5-3 1

Updating a DataSet Using a DataGridView The DataGridView object includes features that allow the user to update the underlying dataset The user can modify data in any row in the grid All changes are made in the underlying dataset (the in-memory copy of the data) When the user clicks the Save button, the BindingNavigator s SaveItem event is fired and an attempt is made to save the data back to the original data source The update code is automatically generated by the designer when a BindingNavigator is added to a form See See code p. p. 190-191 5-4 DataGridView 5-5 The TableAdapter A dataset is a temporary source of data A dataset is disconnected from the original data source The TableAdapter s Update method is used to send changes back to the data source 5-6 2

Database Handling in the VS IDE First time a program is run in the debugger, the database file is copied into the bin\debug folder and is the one used in the program By default, the file s Copy to Output Directory property is set to Copy always If database updates to show up from one run to the next, select the filename in the Solution Explorer and change the setting for Copy to Output Directory to Copy if newer This checks the file version when the debugger runs and copies the file when appropriate 5-7 Copy Behavior of a Database File (1 of 2) Select the filename in the Solution Explorer and set the Copy to Output Directory property to Copy if newer 5-8 Copy Behavior of a Database File (2 of 2) The database file appears in the project folder and in the bin\debug folder Delete the copy in bin\debug to work with a fresh copy of the original file when the file is set to Copy if newer 5-9 3

Data Objects, Methods, and Properties You must use methods and properties of the data objects to write more sophisticated update programs See See Table 5.1 5.1 p. p. 193 193 Overview of of Useful Data Data Methods and and Properties 5-10 DataSet Object Each row of data belongs to a DataRows collection of a table 5-11 The DataRowState Enumeration DataRowState Enumeration Added Purpose Indicates that this is a new row Deleted Detached Modified Unchanged The row is marked for deletion The row is not part of a collection. A row has the detached value before it is added or after it has been removed Changes have been made to the row No changes have been made to the row 5-12 4

The HasChanges Method Determines if changes have been made to a dataset Returns a boolean value If If PubsDataSet.HasChanges() Then ' Ask Ask the the user to to save the the changes. End End If If An overloaded version of the method allows you to check for specific types of changes If If PubsData.SetHasChanges(DataRowState.Deleted) Then ' ' Code to to handle the the deletion(s). End End If If 5-13 The GetChanges Method Use to retrieve the rows that have changes Use an empty argument to retrieve all changed rows OR specify type of changes using enumeration values Dim Dim employeechangesdataset As As DataSet employeechangesdataset = PubsDataSet.GetChanges() Dim Dim employeedeletesdataset As As DataSet employeedeletesdataset = PubsDataSet.GetChanges _ (DataRowState.Deleted) 5-14 The Edit Methods To modify a row of data, the row must be in edit mode Edit methods are called automatically for bound controls The BeginEdit is called when an edit begins The EndEdit executes when the method terminates Use the CancelEdit method to return field values to their original values 5-15 5

DataRow Versions The DataRow object maintains several versions of its column data Current, Original, Default, and Proposed If no changes have been made, the Current and Original versions are the same When EndEdit executes, the Current version is replaced by the Proposed version The EndEdit method confirms the changes Changes are made when the AcceptChanges method executes 5-16 The AcceptChanges Method (1 of 2) Removes all rows marked for deletion Makes the adds and edits indicated for the table Sets the Original version of each changed row to the Current version Sets the RowState of each row to Unchanged Clears any RowError information and sets the HasErrors property to False 5-17 The AcceptChanges Method (2 of 2) The AcceptChanges method commits all changes to the dataset The RejectChanges method rolls back all changes that have been made by replacing Current versions with the Original versions After AcceptChanges or RejectChanges executes, all RowState properties are reset to Unchanged The dataset is disconnected so changes are made to the dataset and not to the original data source execute the TableAdapter s Update method before calling the AcceptChanges method 5-18 6

The TableAdapter Update Method Execute the Update method after every change OR when the program terminates General form if the dataset has only one table there is no need to specify the table name TableAdapter.Update(DataSet.Table) 5-19 When to Update? Every time an add, edit, or delete occurs? When the program terminates? Provide a Save option on a menu and prompt for unsaved changes when the program terminates? Update Considerations 1. 1. Where does the the application and and data reside? 2. 2. How many users can can make changes? 3. 3. Does the the data source need to to be be up-to-date at at all all times? 5-20 Binding Source Update Methods Method AddNew Insert CancelNew Cancel Edit EndEdit RemoveAt RemoveCurrent Purpose Clears bound fields to allow new data to be entered. Adds a new row to the table Adds a record at the specified index Cancels the record being added Cancels the edit currently being processed Completes the current edit Deletes the row at the specified index from the table Deletes the current record 5-21 7

Binding Source Events Two useful events for the BindingSource class CurrentChanged event A bound value is changed PositionChanged event The user navigates to another record The PostionChanged event handler is a good place to display the current record number in a label or the status bar See See code p. p. 200 200 5-22 Using Binding Source Events in a Multitier Application The BindingSource object must be declared in code and there is no automatic access to its events Declare an object WithEvents to make its events available in code '' Module-level variable. Private WithEvents apublishersbindingsource _ As As BindingSource After an object is declared WithEvents, the events appear in the drop-down lists in the editor 5-23 SQL Statements for Updates ADO.NET handles the complicated process of updating the original data source The Update method makes all of the indicated changes to the original data source for all rows that have a RowState other than Unchanged When a data source is added, several SQL statements are generated. SELECT INSERT DELETE UPDATE 5-24 8

Concurrency Occurs when more than one user can update a file at the same time Concurrency control is the process of handling conflicts in updates by multiple users Three types of concurrency controls in ADO.NET Pessimistic row is unavailable from the time the record is retrieved until the update is complete Optimistic row is unavailable only while an update is in progress (the default) Last in wins row is unavailable only when the update is being made 5-25 Testing Update Programs Many types of errors may be encountered when testing an Add or Update in an update program Must have proper rights to the database to allow writing to the data source Be aware of constraints which fields contain nulls, required fields, specific values in fields Include exception handling statements for all statements that access the database Display the exception message to help determine the cause of any problems 5-26 Updating a DataSet in Bound Controls Using bound individual controls is more common than using a grid Change the dataset field in bound text boxes so users can type in changes keep as Read Only unless an Add or Edit is in progress All of the techniques for updating a dataset apply equally to an Access database and a SQL Server database 5-27 9

Details View Update Program Form using buttons for navigation in an Update program Form using a combo box for selection 5-28 Update Logic Update program needs procedures to modify existing records (editing), deleting, and adding new records Call the Update method so that the data source is upto-date for every change Enclose all statements that access the database in Try/Catch blocks Limit the options available to users during an update While Add or Edit is in progress, the only options should be Save or Cancel While navigating from one record to another, don t allow changes to data 5-29 Add or Edit During an Add or Edit, the Add button becomes the Save button and the Delete button become the Cancel button; Edit button is disabled 5-30 10

Add Operation Pseudocode Call the BindingSource s AddNew method, which begins the Add and clears the text boxes Set addingboolean to True Set the focus to the first text box Disable navigation Set the text boxes ReadOnly Property to False Set up the buttons for an Add: Set up the Save and Cancel buttons Disable the Edit button Display Adding in the status bar 5-31 Edit Logic Display fields in bound text boxes Set the ReadOnly property of each text box to True, locking the text box For bound check boxes, lists, and grids set the Enabled property to False (no ReadOnly property) Disable navigation so users can t move off records and automatically save the changes The only choices a user should have during an Edit are Save or Cancel 5-32 Psuedocode to Begin an Edit Set editingboolean to True Disable navigation Set the text boxes ReadOnly property to False Set up the buttons for an Edit: Set up the Save and Cancel buttons Disable the Edit button Display Editing in the status bar. 5-33 11

Validating User Input Data As users enter data, some fields need to be validated such as constraints, such as required fields, or data type There may be business rules for validating data Validating data before sending it back to the database can reduce the number of round trips between the application and the database Perform field-level or record-level validation in an event handler 5-34 Using a Combo Box for Selection (1 of 2) During navigation, the user can make a selection from the list but not make changes to the text NameComboBox.DropDownStyle _ = ComboBoxStyle.DropDownList During an Add or Edit, the user can change the text but not make a new selection from the list NameComboBox.DropDownStyle _ = ComboBoxStyle.Simple 5-35 Using a Combo Box for Selection (2 of 2) During navigation, making a new selection from the combo box should not update the dataset NameComboBox.DataBindings!text. _ DataSourceUpdateMode _ = DataSourceUpdateMode.Never During an Add or Edit, making a new selection from the combo box should update the dataset NameComboBox.DataBindings!text. _ DataSourceUpdateMode _ = DataSourceUpdateMode.OnValidation 5-36 12

Checking for Nulls Common problem for programming database updates relates to null fields If users do not enter data in a field that does not permit nulls and the record is sent to the database, an exception occurs Check to see which field allow nulls by: In the DataSet Designer click on each individual field and view the AllowDBNull property View settings for an entire table by using the Server Explorer Select View/Server Explorer to see the window, expand the nodes, right-click on table name and select Open Table Definition 5-37 Open Table Definition View and modify the table definition 5-38 ErrorProvider Component Displays an icon and a message for invalid data 5-39 13

Displaying a Message Using an ErrorProvider Add an ErrorProvider to the form Make sure that the CausesValidation property of most controls is set to True Set CausesValidation = False for the Cancel button In the Validating event handler for the control to validate, set e.cancel = True for bad data Makes the control sticky Also set the error message for the ErrorProvider Make sure to clear the error message when the control passes validation 5-40 Adding Validation to a DataGridView Program Validation concepts for data in a grid are similar to the detail view Must perform validation for the grid s CellValidating and RowValidating events CellValidating event occurs when the user moves across the row from one field to another RowValidating event occurs when the user attempts to move off the current row DataGridView control has the equivalent of a built-in error provider To display an error icon/message, set the cell s ErrorText property 5-41 Displaying Error Messages in a Grid Error icon and message 5-42 14

Updating Related Tables The Update method issues the proper INSERT, DELETE and UPDATE SQL commands for a single table If updating multiple tables, the program must take charge and issue the commands in the correct sequence 5-43 Parent and Child Relationships To maintain referential integrity, update in the following order: 1. Delete any child records 2. Insert, update, and delete the parent records 3. Insert and update the child records A parent or master can t be deleted if there are any associated child records 5-44 Cascading Deletes and Updates Help to maintain referential integrity Set up the relationship for cascading updates and cascading deletes in the Relation dialog box 5-45 15

The Related-Table Update Program A. B. C. 5-46 The Update Logic for Related Tables (1 of 2) First, save the deletes for child records create a new table that holds only the rows marked for deletion Use the GetChanges method of a table or dataset to request all rows with a specific row state Test for IsNot Nothing to determine whether the GetChanges method returned any rows If changes exist, assign the retrieved rows to the new table and specify the table name as the argument of the Update method 5-47 The Update Logic for Related Tables (2 of 2) Second, Save all updates for the parent table Check to determine that changes have been made Execute the Update method again for child record Adds and Edits '' Update child child Adds Adds and and Edits. If If PubsDataSet.sales.GetChanges(DataRowState.Added + _ DataRowState.Modified) IsNot IsNot Nothing Then Then '' Get Get changes for for the the added added and and edited child child rows rows only. only. 5-48 16

Setting DataGridView Properties for the Update Program Hide a column in a DataGridView using the grid s Edit Columns dialog box Set the Visible property to False (will hide at run time) Don t hide columns that the user must be able to enter for an Add or Edit 5-49 Creating a Table Lookup Column (1 of 2) Use a combo box to hold the value the user selects a title from a list but cannot type a new entry 5-50 Creating a Table Lookup Column (2 of 2) In the Data Source Configuration Wizard select the fields from the table for lookup Drag the table to the form For the new DataGridView control, use the smart tag to select Edit Columns Click the Add button to add a new column Select Unbound column, enter a name and header text and select DataGridViewComboBoxColumn for Type Set the properties of the added column BindingSource, DisplayMember, DataPropertyName, ValueMember, DisplayStyle, MinimumWidth, and MaximumWidth 5-51 17

Considerations for Multitier Applications The form should contain only the code for formatting and displaying input and output for the user and perhaps input validation. (Update logic belongs in the data tier.) To create a combo box column for a table lookup, instantiate the object of type DataGridViewComboBox Column, set the properties and add it to the DataGridView s Columns collection A good way to guard against a user adding child records is to set the grid s Enabled property to False until the new parent has been saved 5-52 Navigation Code in a Related Table Update Perform navigation in the SelectedIndexChanged event handler (rather than SelectionChangeCommitted) SelectIndexChanged event occurs any time the combo box index changes Advantage: You can filter the table to always display the correct data for the combo box selection Disadvantage: The event occurs several times as the form and data are initialized. You must set up a Boolean variable and check for completed initialization 5-53 Security Considerations Do not provide a user with information that could be used to violate database security Don t use actual field names in error messages use descriptive names for the data items The practice of displaying ex.message in a Catch clause is useful for testing and debugging a program but should not appear in a production program because it may contain actual field names 5-54 18