- •Contents at a Glance
- •Table of Contents
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •Finding Your Best Starting Point in This Book
- •Conventions and Features in This Book
- •Conventions
- •Other Features
- •System Requirements
- •Code Samples
- •Installing the Code Samples
- •Using the Code Samples
- •Support for This Book
- •Questions and Comments
- •Beginning Programming with the Visual Studio 2008 Environment
- •Writing Your First Program
- •Using Namespaces
- •Creating a Graphical Application
- •Chapter 1 Quick Reference
- •Understanding Statements
- •Identifying Keywords
- •Using Variables
- •Naming Variables
- •Declaring Variables
- •Working with Primitive Data Types
- •Displaying Primitive Data Type Values
- •Using Arithmetic Operators
- •Operators and Types
- •Examining Arithmetic Operators
- •Controlling Precedence
- •Using Associativity to Evaluate Expressions
- •Associativity and the Assignment Operator
- •Incrementing and Decrementing Variables
- •Declaring Implicitly Typed Local Variables
- •Chapter 2 Quick Reference
- •Declaring Methods
- •Specifying the Method Declaration Syntax
- •Writing return Statements
- •Calling Methods
- •Specifying the Method Call Syntax
- •Applying Scope
- •Overloading Methods
- •Writing Methods
- •Chapter 3 Quick Reference
- •Declaring Boolean Variables
- •Using Boolean Operators
- •Understanding Equality and Relational Operators
- •Understanding Conditional Logical Operators
- •Summarizing Operator Precedence and Associativity
- •Using if Statements to Make Decisions
- •Understanding if Statement Syntax
- •Using Blocks to Group Statements
- •Cascading if Statements
- •Using switch Statements
- •Understanding switch Statement Syntax
- •Following the switch Statement Rules
- •Chapter 4 Quick Reference
- •Using Compound Assignment Operators
- •Writing while Statements
- •Writing for Statements
- •Understanding for Statement Scope
- •Writing do Statements
- •Chapter 5 Quick Reference
- •Coping with Errors
- •Trying Code and Catching Exceptions
- •Handling an Exception
- •Using Multiple catch Handlers
- •Catching Multiple Exceptions
- •Using Checked and Unchecked Integer Arithmetic
- •Writing Checked Statements
- •Writing Checked Expressions
- •Throwing Exceptions
- •Chapter 6 Quick Reference
- •The Purpose of Encapsulation
- •Controlling Accessibility
- •Working with Constructors
- •Overloading Constructors
- •Understanding static Methods and Data
- •Creating a Shared Field
- •Creating a static Field by Using the const Keyword
- •Chapter 7 Quick Reference
- •Copying Value Type Variables and Classes
- •Understanding Null Values and Nullable Types
- •Using Nullable Types
- •Understanding the Properties of Nullable Types
- •Using ref and out Parameters
- •Creating ref Parameters
- •Creating out Parameters
- •How Computer Memory Is Organized
- •Using the Stack and the Heap
- •The System.Object Class
- •Boxing
- •Unboxing
- •Casting Data Safely
- •The is Operator
- •The as Operator
- •Chapter 8 Quick Reference
- •Working with Enumerations
- •Declaring an Enumeration
- •Using an Enumeration
- •Choosing Enumeration Literal Values
- •Choosing an Enumeration’s Underlying Type
- •Working with Structures
- •Declaring a Structure
- •Understanding Structure and Class Differences
- •Declaring Structure Variables
- •Understanding Structure Initialization
- •Copying Structure Variables
- •Chapter 9 Quick Reference
- •What Is an Array?
- •Declaring Array Variables
- •Creating an Array Instance
- •Initializing Array Variables
- •Creating an Implicitly Typed Array
- •Accessing an Individual Array Element
- •Iterating Through an Array
- •Copying Arrays
- •What Are Collection Classes?
- •The ArrayList Collection Class
- •The Queue Collection Class
- •The Stack Collection Class
- •The Hashtable Collection Class
- •The SortedList Collection Class
- •Using Collection Initializers
- •Comparing Arrays and Collections
- •Using Collection Classes to Play Cards
- •Chapter 10 Quick Reference
- •Using Array Arguments
- •Declaring a params Array
- •Using params object[ ]
- •Using a params Array
- •Chapter 11 Quick Reference
- •What Is Inheritance?
- •Using Inheritance
- •Base Classes and Derived Classes
- •Calling Base Class Constructors
- •Assigning Classes
- •Declaring new Methods
- •Declaring Virtual Methods
- •Declaring override Methods
- •Understanding protected Access
- •Understanding Extension Methods
- •Chapter 12 Quick Reference
- •Understanding Interfaces
- •Interface Syntax
- •Interface Restrictions
- •Implementing an Interface
- •Referencing a Class Through Its Interface
- •Working with Multiple Interfaces
- •Abstract Classes
- •Abstract Methods
- •Sealed Classes
- •Sealed Methods
- •Implementing an Extensible Framework
- •Summarizing Keyword Combinations
- •Chapter 13 Quick Reference
- •The Life and Times of an Object
- •Writing Destructors
- •Why Use the Garbage Collector?
- •How Does the Garbage Collector Work?
- •Recommendations
- •Resource Management
- •Disposal Methods
- •Exception-Safe Disposal
- •The using Statement
- •Calling the Dispose Method from a Destructor
- •Making Code Exception-Safe
- •Chapter 14 Quick Reference
- •Implementing Encapsulation by Using Methods
- •What Are Properties?
- •Using Properties
- •Read-Only Properties
- •Write-Only Properties
- •Property Accessibility
- •Understanding the Property Restrictions
- •Declaring Interface Properties
- •Using Properties in a Windows Application
- •Generating Automatic Properties
- •Initializing Objects by Using Properties
- •Chapter 15 Quick Reference
- •What Is an Indexer?
- •An Example That Doesn’t Use Indexers
- •The Same Example Using Indexers
- •Understanding Indexer Accessors
- •Comparing Indexers and Arrays
- •Indexers in Interfaces
- •Using Indexers in a Windows Application
- •Chapter 16 Quick Reference
- •Declaring and Using Delegates
- •The Automated Factory Scenario
- •Implementing the Factory Without Using Delegates
- •Implementing the Factory by Using a Delegate
- •Using Delegates
- •Lambda Expressions and Delegates
- •Creating a Method Adapter
- •Using a Lambda Expression as an Adapter
- •The Form of Lambda Expressions
- •Declaring an Event
- •Subscribing to an Event
- •Unsubscribing from an Event
- •Raising an Event
- •Understanding WPF User Interface Events
- •Using Events
- •Chapter 17 Quick Reference
- •The Problem with objects
- •The Generics Solution
- •Generics vs. Generalized Classes
- •Generics and Constraints
- •Creating a Generic Class
- •The Theory of Binary Trees
- •Building a Binary Tree Class by Using Generics
- •Creating a Generic Method
- •Chapter 18 Quick Reference
- •Enumerating the Elements in a Collection
- •Manually Implementing an Enumerator
- •Implementing the IEnumerable Interface
- •Implementing an Enumerator by Using an Iterator
- •A Simple Iterator
- •Chapter 19 Quick Reference
- •What Is Language Integrated Query (LINQ)?
- •Using LINQ in a C# Application
- •Selecting Data
- •Filtering Data
- •Ordering, Grouping, and Aggregating Data
- •Joining Data
- •Using Query Operators
- •Querying Data in Tree<TItem> Objects
- •LINQ and Deferred Evaluation
- •Chapter 20 Quick Reference
- •Understanding Operators
- •Operator Constraints
- •Overloaded Operators
- •Creating Symmetric Operators
- •Understanding Compound Assignment
- •Declaring Increment and Decrement Operators
- •Implementing an Operator
- •Understanding Conversion Operators
- •Providing Built-In Conversions
- •Creating Symmetric Operators, Revisited
- •Adding an Implicit Conversion Operator
- •Chapter 21 Quick Reference
- •Creating a WPF Application
- •Creating a Windows Presentation Foundation Application
- •Adding Controls to the Form
- •Using WPF Controls
- •Changing Properties Dynamically
- •Handling Events in a WPF Form
- •Processing Events in Windows Forms
- •Chapter 22 Quick Reference
- •Menu Guidelines and Style
- •Menus and Menu Events
- •Creating a Menu
- •Handling Menu Events
- •Shortcut Menus
- •Creating Shortcut Menus
- •Windows Common Dialog Boxes
- •Using the SaveFileDialog Class
- •Chapter 23 Quick Reference
- •Validating Data
- •Strategies for Validating User Input
- •An Example—Customer Information Maintenance
- •Performing Validation by Using Data Binding
- •Changing the Point at Which Validation Occurs
- •Chapter 24 Quick Reference
- •Querying a Database by Using ADO.NET
- •The Northwind Database
- •Creating the Database
- •Using ADO.NET to Query Order Information
- •Querying a Database by Using DLINQ
- •Creating and Running a DLINQ Query
- •Deferred and Immediate Fetching
- •Joining Tables and Creating Relationships
- •Deferred and Immediate Fetching Revisited
- •Using DLINQ to Query Order Information
- •Chapter 25 Quick Reference
- •Using Data Binding with DLINQ
- •Using DLINQ to Modify Data
- •Updating Existing Data
- •Adding and Deleting Data
- •Chapter 26 Quick Reference
- •Understanding the Internet as an Infrastructure
- •Understanding Web Server Requests and Responses
- •Managing State
- •Understanding ASP.NET
- •Creating Web Applications with ASP.NET
- •Building an ASP.NET Application
- •Understanding Server Controls
- •Creating and Using a Theme
- •Chapter 27 Quick Reference
- •Comparing Server and Client Validations
- •Validating Data at the Web Server
- •Validating Data in the Web Browser
- •Implementing Client Validation
- •Chapter 28 Quick Reference
- •Managing Security
- •Understanding Forms-Based Security
- •Implementing Forms-Based Security
- •Querying and Displaying Data
- •Understanding the Web Forms GridView Control
- •Displaying Customer and Order History Information
- •Paging Data
- •Editing Data
- •Updating Rows Through a GridView Control
- •Navigating Between Forms
- •Chapter 29 Quick Reference
- •What Is a Web Service?
- •The Role of SOAP
- •What Is the Web Services Description Language?
- •Nonfunctional Requirements of Web Services
- •The Role of Windows Communication Foundation
- •Building a Web Service
- •Creating the ProductsService Web Service
- •Web Services, Clients, and Proxies
- •Talking SOAP: The Easy Way
- •Consuming the ProductsService Web Service
- •Chapter 30 Quick Reference
548 |
Part V Managing Data |
|
The code in your ChangeConflictException handler can then iterate through all the items |
|
in the ObjectChangeConflict property of the DataContext object and resolve them all (the |
|
example shown earlier already does this) before calling SubmitChanges again. |
|
When you call SubmitChanges, you can also specify the parameter value of ConflictMode. |
|
FailOnFirstConflict. This is the default behavior and raises a ChangeConflictException as soon |
|
as the first conflict is detected. |
Adding and Deleting Data
As well as modifying existing data, with DLINQ you can add new items to a Table collection and remove items from a Table collection. To add a new item, call the Add method and pro-
vide an entity object with the new information, like this:
NorthwindDataContext ndc = new NorthwindDataContext(...); Table<Product> products = ndc.Products;
Product newProduct = new Product() {ProductName = “New Product”, ... }; products.Add(newProduct);
When you call SubmitChanges, the DataContext object will generate a SQL INSERT statement for each new item in the Table collection.
Note When you add a new entity object to the Table collection, you must provide values for every column that does not allow a null value in the database. The exception to this rule is for primary key columns that are designated as IDENTITY columns in the database—SQL Server will generate values for these columns and will raise an error if you try to specify a value of your own.
Deleting an entity object from a Table collection is equally straightforward. You call the
Remove method and specify the entity to be deleted. The following code deletes product 14 from the products collection.
Product product = products.Single(p => p.ProductID == 14); products.Remove(product);
When you call SubmitChanges, the DataContext object will generate a SQL DELETE statement for each row that has been removed from the Table collection.
Note Be careful when deleting rows in tables that have relationships to other tables because such deletions can cause referential integrity errors when you update the database. For example,
in the Northwind database, if you attempt to delete a supplier that currently supplies products, the update will fail. You must first change the SupplierID column in the Products table for all
products available from that supplier to null or to a different supplier.
You now have enough knowledge to complete the Suppliers application.
Chapter 26 Displaying and Editing Data by Using Data Binding |
549 |
Write code to modify, delete, and create products
1.Return to the Visual Studio 2008 window in which you were editing the Suppliers application.
2.In the Design View window, in the XAML pane, modify the definition of the productsList control to trap the KeyDown event and invoke an event method called productsList_KeyDown. (This is the default name of the event method.) If IntelliSense does not recognize the KeyDown keyword, try closing and reopening the SupplierInfo. xaml file.
3.In the Code and Text Editor window, add the following code shown in bold type to the productsList_KeyDown method.
private void productsList_KeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter: editProduct(this.productsList.SelectedItem as Product); break;
case Key.Insert: addNewProduct(); break;
case Key.Delete: deleteProduct(this.productsList.SelectedItem as Product); break;
}
}
This method examines the key pressed by the user. If the user presses the Enter key, the code calls the editProduct method, passing in the details of the product as a parameter. If the user presses the Insert key, the code calls the addNewProduct method to cre-
ate and add a new product to the list for the current supplier, and if the user presses the Delete key, the code calls the deleteProduct method to delete the product. You will write the editProduct, addNewProduct, and deleteProduct methods in the next few
steps.
4. Add the deleteProduct method to the SupplierInfo class, as follows:
private void deleteProduct(Product prod)
{
MessageBoxResult response = MessageBox.Show(“Delete “ + prod.ProductName, “Confirm”, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
if (response == MessageBoxResult.Yes)
{
supplier.Products.Remove(prod);
productsInfo.Remove(prod); this.saveChanges.IsEnabled = true;
}
}
550 |
Part V Managing Data |
This method prompts the user to confirm that the user really does want to delete the currently selected product. The if statement calls the Remove method of the Products EntitySet<TEntity> property to delete the product from this collection and also removes it from the productsInfo binding list. (This step is necessary to ensure that the display
is kept synchronized with the changes.) Finally, the method activates the saveChanges
button. You will add functionality to this button to send the changes made to the Products EntitySet<TEntity> back to the database in a later step.
There are several approaches you can use for adding and editing products; the columns in the ListView control are read-only text items, but you can create a customized
list view that contains text boxes or other controls that enable user input. However, the simplest strategy is to create another form that enables the user to edit or add the details of a product.
5.On the Project menu, click Add Class. In the Add New Items – Suppliers dialog box, select the Window (WPF) template, type ProductForm.xaml in the Name box, and then click Add.
6.In the Design View window, click the ProductForm form, and in the Properties window, set the ResizeMode property to NoResize, set the Height property to 225, and set the Width property to 515.
7.Add three Label controls, three TextBox controls, and two Button controls to the form. Using the Properties window, set the properties of these controls to the values shown in the following table.
Control |
Property |
Value |
label1 |
Content |
Product Name |
|
Height |
23 |
|
Width |
120 |
|
Margin |
17,20,0,0 |
|
VerticalAlignment |
Top |
|
HorizontalAlignment |
Left |
|
|
|
label2 |
Content |
Quantity Per Unit |
|
Height |
23 |
|
Width |
120 |
|
Margin |
17,60,0,0 |
|
VerticalAlignment |
Top |
|
HorizontalAlignment |
Left |
|
|
|
|
Chapter 26 Displaying and Editing Data by Using Data Binding |
551 |
||
Control |
Property |
Value |
|
|
label3 |
Content |
Unit Price |
|
|
|
Height |
23 |
|
|
|
Width |
120 |
|
|
|
Margin |
17,100,0,0 |
|
|
|
VerticalAlignment |
Top |
|
|
|
HorizontalAlignment |
Left |
|
|
|
|
|
|
|
textBox1 |
Name |
productName |
|
|
|
Height |
21 |
|
|
|
Width |
340 |
|
|
|
Margin |
130,24,0,0 |
|
|
|
VerticalAlignment |
Top |
|
|
|
HorizontalAlignment |
Left |
|
|
|
|
|
|
|
textBox2 |
Name |
quantityPerUnit |
|
|
|
Height |
21 |
|
|
|
Width |
340 |
|
|
|
Margin |
130,64,0,0 |
|
|
|
VerticalAlignment |
Top |
|
|
|
HorizontalAlignment |
Left |
|
|
|
|
|
|
|
textBox3 |
Name |
unitPrice |
|
|
|
Height |
21 |
|
|
|
Width |
120 |
|
|
|
Margin |
130,104,0,0 |
|
|
|
VerticalAlignment |
Top |
|
|
|
HorizontalAlignment |
Left |
|
|
|
|
|
|
|
button1 |
Name |
ok |
|
|
|
Content |
OK |
|
|
|
Height |
23 |
|
|
|
Width |
75 |
|
|
|
Margin |
130,150,0,0 |
|
|
|
VerticalAlignment |
Top |
|
|
|
HorizontalAlignment |
Left |
|
|
|
|
|
|
|
552 |
Part V Managing Data |
|
|
|
|
|
Control |
Property |
Value |
|
|
button2 |
Name |
cancel |
|
|
|
Content |
Cancel |
|
|
|
Height |
23 |
|
|
|
Width |
75 |
|
|
|
Margin |
300,150,0,0 |
|
|
|
VerticalAlignment |
Top |
|
|
|
HorizontalAlignment |
Left |
|
|
|
|
|
The Supplier Information form should look like this in the Design View window:
8.Double-click the OK button to create an event handler for the click event. In the Code and Text Editor window displaying the ProductForm.xaml.cs file, add the following code shown in bold type.
private void ok_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(this.productName.Text))
{
MessageBox.Show(“The product must have a name”, “Error”, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
decimal result;
if (!Decimal.TryParse(this.unitPrice.Text, out result))
{
MessageBox.Show(“The price must be a valid number”, “Error”, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (result < 0)
{
Chapter 26 Displaying and Editing Data by Using Data Binding |
553 |
MessageBox.Show(“The price must not be less than zero”, “Error”, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
this.DialogResult = true;
}
The application will display this form by calling the ShowDialog method. This method
displays the form as a modal dialog box. When the user clicks a button on the form, it will close automatically if the code for the click event sets the DialogResult property.
If the user clicks OK, this method performs some simple validation of the information entered by the user. The Quantity Per Unit column in the database accepts null values,
so the user can leave this field on the form empty. If the user enters a valid product name and price, the method sets the DialogResult property of the form to true. This value is passed back to the ShowDialog method call.
9.Return to the Design View window displaying the ProductForm.xaml file. Select the Cancel button, and in the Properties window, set the IsCancel property to true (select the check box).
If the user clicks the Cancel button, it will automatically close the form and return a
DialogResult value of false to the ShowDialog method.
10.Switch to the Code and Text Editor window displaying the SupplierInfo.xaml.cs file. Add the addNewProduct method shown here to the SupplierInfo class.
private void addNewProduct()
{
ProductForm pf = new ProductForm();
pf.Title = “New Product for “ + supplier.CompanyName; if (pf.ShowDialog().Value)
{
Product newProd = new Product(); newProd.SupplierID = supplier.SupplierID; newProd.ProductName = pf.productName.Text; newProd.QuantityPerUnit = pf.quantityPerUnit.Text;
newProd.UnitPrice = Decimal.Parse(pf.unitPrice.Text); supplier.Products.Add(newProd); productsInfo.Add(newProd);
this.saveChanges.IsEnabled = true;
}
}
The addNewProduct method creates a new instance of the ProductForm form, sets the Title property of this form to contain the name of the supplier, and then calls the ShowDialog method to display the form as a modal dialog box. If the user enters some
valid data and clicks the OK button on the form, the code in the if block creates a new Product object and populates it with the information from the ProductForm instance.
554 Part V Managing Data
The method then adds it to the Products EntitySet<TEntity> for the current supplier and
also adds it to the list displayed in the list view control on the form. Finally, the code activates the Save Changes button. In a later step, you will add code to the click event
handler for this button so that the user can save changes back to the database. 11. Add the editProduct method shown here to the SupplierInfo class.
private void editProduct(Product prod)
{
ProductForm pf = new ProductForm(); pf.Title = “Edit Product Details”; pf.productName.Text = prod.ProductName;
pf.quantityPerUnit.Text = prod.QuantityPerUnit; pf.unitPrice.Text = prod.UnitPrice.ToString();
if (pf.ShowDialog().Value)
{
prod.ProductName = pf.productName.Text; prod.QuantityPerUnit = pf.quantityPerUnit.Text; prod.UnitPrice = Decimal.Parse(pf.unitPrice.Text); this.saveChanges.IsEnabled = true;
}
}
The editProduct method also creates an instance of the ProductForm form. This time, as well as setting the Title property, the code also populates the fields on the form with
the information from the currently selected product. When the form is displayed, the user can edit these values. If the user clicks the OK button to close the form, the code
in the if block copies the new values back to the currently selected product before activating the Save Changes button. Notice that this time you do not need to update the current item manually in the productsInfo list because the Product class notifies the list
view control of changes to its data automatically.
12.Return to the Design View window displaying the SupplierInfo.xaml file. Double-click the Save Changes button to create the click event handler method.
13.In the Code and Text Editor window, add the following code shown in bold to the saveChanges_Click method:
private void saveChanges_Click(object sender, RoutedEventArgs e)
{
try
{
ndc.SubmitChanges(); saveChanges.IsEnabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error saving changes”);
}
}
Chapter 26 Displaying and Editing Data by Using Data Binding |
555 |
This method calls the SubmitChanges method of the DataContext object to send all the changes back to the database. For simplicity, this method performs only very rudimentary exception handling and does not attempt to resolve errors caused by conflicting updates made by other users.
Test the Suppliers application
1.On the Debug menu, click Start Without Debugging to build and run the applica-
tion. When the form appears displaying the products supplied by Exotic Liquids, click product 3 (Aniseed Syrup), and then press Enter. The Edit Product Details form should appear. Change the value in the Unit Price field to 12.5, and then click OK. Verify that the new price is copied back to the list view.
2.Press the Insert key. The New Product for Exotic Liquids form should appear. Enter a product name, quantity per unit, and price, and then click OK. Verify that the new product is added to the list view.
The value in the Product ID column should be 0. This value is an identity column in the database, so SQL Server will generate its own unique value for this column when you save the changes.
3.Click Save Changes. After the data is saved, the ID for the new product is displayed in the list view.
4.Click the new product, and then press the Delete key. In the Confirm dialog box, click Yes. Verify that the product disappears from the form. Click Save Changes again, and verify that the operation completes without any errors.
Feel free to experiment by adding, removing, and editing products for other suppliers. You can make several modifications before clicking Save Changes—the SubmitChanges method saves all changes made since the data was retrieved or last saved.
Tip If you accidentally delete or overwrite the data for a product that you want to keep, close the application without clicking Save Changes. Note that the application as written
does not warn the user if the user tries to exit without first saving changes.
Alternatively, you can add a Discard Changes button to the application that calls the Refresh method of the ndc DataContext object to repopulate its tables from the database. You would also then need to rebuild the productsInfo binding list for the currently selected
product.
However, if you are handling a relatively small number of rows, as is the case in the Suppliers application, a simpler technique is to discard the current DataContext object and create a new one, and then reapply the binding for the suppliersList combo box, like this:
ndc = new NorthwindDataContext(); this.suppliersList.DataContext = ndc.Suppliers;
