Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

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;

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]