246Microsoft Visual Studio 2010: A Beginner’s Guide

Dim OrderViewSource As CollectionViewSource = CType(FindResource("OrderViewSource"), CollectionViewSource)

OrderViewSource.Source =

From ord In m_ctx.Orders

Select ord

End Sub

This code loads orders into the Grid. Notice that the MyShopDataContext, m_ctx, is a field outside of the Window_Loaded method handler. It is raised to field level so that the same instance can be used in multiple methods. As you may notice from Figure 8-16, there is also an Update button on the form. Double-clicking the Update button produced the following Click event handler that saves changes, such as updates and deletes, to the Grid:

C#:

private void UpdateButton_Click(object sender, RoutedEventArgs e)

{

m_ctx.SubmitChanges();

MessageBox.Show("Updates and Deletes Saved!");

}

VB:

Private Sub UpdateButton_Click(

ByVal sender As System.Object,

ByVal e As System.Windows.RoutedEventArgs)

Handles UpdateButton.Click

m_ctx.SubmitChanges()

MessageBox.Show("Updates and Deletes Saved!")

End Sub

When you run the program, you can add new rows, modify the cells of existing rows, or delete a row by selecting the row and pressing DELETE on the keyboard. After making changes to the Grid, click Update, which will call the previous UpdateButton_Click event handler.

To understand how this works, remember that the Window_Loaded event handler assigned a collection of Order objects to the CollectionViewSource, orderViewSource, which is data bound to the Grid. Each row of the Grid is bound to an instance of an Order object. Each Order object is part of the LINQ to SQL MyShopDataContext. Since we are

Page 269
Image 269
Microsoft 9GD00001 manual Microsoft Visual Studio 2010 a Beginner’s Guide