- 21.1 Introduction
- 21.2 Relational Databases
- 21.3 Relational Database Overview: Books Database
- 21.4 SQL
- 21.5 LINQ to SQL
- 21.6 LINQ to SQL: Extracting Information from a Database
- 21.7 More Complex LINQ Queries and Data Binding
- 21.8 Retrieving Data from Multiple Tables with LINQ
- 21.9 Creating a Master/Detail View Application
- 21.10 Programming with LINQ to SQL: Address-Book Case Study
- 21.11 Wrap-Up
- 21.12 Tools and Web Resources
21.10 Programming with LINQ to SQL: Address-Book Case Study
Our next example implements a simple address-book application that enables users to insert rows into, locate rows from and update the database AddressBook.mdf, which is included in the directory with this chapter’s examples.
The AddressBook application (Fig. 21.30) provides a GUI through which users can query the database with LINQ. However, rather than displaying a database table in a DataGridView, this example presents data from a table one row at a time, using several TextBoxes that display the values of each of the row’s columns. A BindingNavigator allows you to control which row of the table is in view at any given time. The BindingNavigator also allows you to add rows, delete rows, and save changes to the data. We discuss the application’s functionality and the code that implements it momentarily. First we show the steps to create this application.
Fig. 21.30 Manipulating an address book.
1 // Fig. 21.30: AddressBookForm.cs 2 // Manipulating an address book. 3 using System; 4 using System.Linq; 5 using System.Windows.Forms; 6 7 namespace AddressBook 8 { 9 public partial class AddressBookForm : Form 10 { 11 public AddressBookForm() 12 { 13 InitializeComponent(); 14 } // end constructor 15 16 // LINQ to SQL data context 17 private AddressBookDataContext database = 18 new AddressBookDataContext(); 19 20 // fill our addressBindingSource with all rows, ordered by name 21 private void BindDefault() 22 { 23 // use LINQ to create a data source from the database 24 addressBindingSource.DataSource = 25 from address in database.Addresses 26 orderby address.LastName, address.FirstName 27 select address; 28 29 addressBindingSource.MoveFirst(); // go to the first result 30 findTextBox.Clear(); // clear the Find TextBox 31 } // end method BindDefault 32 33 private void AddressBookForm_Load( object sender, EventArgs e ) 34 { 35 BindDefault(); // fill binding with data from database 36 } // end method AddressBookForm_Load 37 38 // Click event handler for the Save Button in the 39 // BindingNavigator saves the changes made to the data 40 private void addressBindingNavigatorSaveItem_Click( 41 object sender, EventArgs e ) 42 { 43 Validate(); // validate input fields 44 addressBindingSource.EndEdit(); // indicate edits are complete 45 database.SubmitChanges(); // write changes to database file 46 47 BindDefault(); // change back to initial unfiltered data on save 48 } // end method addressBindingNavigatorSaveItem_Click 49 50 // load LINQ to create a data source that contains 51 // only people with the specified last name 52 private void findButton_Click( object sender, EventArgs e ) 53 { 54 // use LINQ to create a data source that contains 55 // only people with the specified last name 56 addressBindingSource.DataSource = 57 from address in database.Addresses 58 where address.LastName == findTextBox.Text 59 orderby address.LastName, address.FirstName 60 select address; 61 62 addressBindingSource.MoveFirst(); // go to first result 63 } // end method findButton_Click 64 65 private void browseButton_Click( object sender, EventArgs e ) 66 { 67 BindDefault(); // change back to initial unfiltered data 68 } // end method browseButton_Click 69 } // end class AddressBookForm 70 } // end namespace AddressBook
Step 1: Creating the Project
Create a new Windows Forms Application named AddressBook. Rename the Form AddressBookForm and its source file AddressBookForm.cs, then set the Form’s Text property to AddressBook.
Step 2: Creating LINQ to SQL Classes and Data Source
Follow the instructions in Section 21.6.1 to add a database to the project and generate the LINQ to SQL classes. For this example, add the AddressBook.mdf database from the Databases folder included with this chapter’s examples and name the file AddressBook.dbml instead of Books.dbml. You must also add the Addresses table as a data source, as was done with the Authors table in Step 1 of Section 21.6.2.
Step 3: Indicating that the IDE Should Create a Set of Labels and TextBoxes to Display Each Row of Data
In the earlier sections, you dragged a node from the Data Sources window to the Form to create a DataGridView bound to the data-source member represented by that node. The IDE allows you to specify the type of control(s) that it creates when you drag and drop a data-source member onto a Form. In Design view, click the Address node in the Data Sources window. Note that this becomes a drop-down list when you select it. Click the down arrow to view the items in the list. The item to the left of DataGridView is initially highlighted in blue, because the default control to be bound to a table is a DataGridView (as you saw in the earlier examples). Select the Details option in the drop-down list to indicate that the IDE should create a set of Label/TextBox pairs for each column-name/column-value pair when you drag and drop the Address node onto the Form. The drop-down list contains suggestions for controls to display the table’s data, but you can also choose the Customize... option to select other controls that can be bound to a table’s data.
Step 4: Dragging the Address Data-Source Node to the Form
Drag the Address node from the Data Sources window to the Form. This automatically creates a BindingNavigator and the Labels and TextBoxes corresponding to the columns of the database table. The fields are ordered alphabetically by default, with Email appearing directly after AddressID. Reorder the components, using Design view, so they are in the proper order shown in Fig. 21.30.
Step 5: Making the AddressID TextBox ReadOnly
The AddressID column of the Addresses table is an autoincremented identity column, so users should not be allowed to edit the values in this column. Select the TextBox for the AddressID and set its ReadOnly property to True using the Properties window. Note that you may need to click in an empty part of the Form to deselect the other Labels and TextBoxes before selecting the AddressID TextBox.
Step 6: Connecting the BindingSource to the DataContext
As in previous examples, we must connect the AddressBindingSource that controls the GUI with the AddressBookDataContext that controls the connection to the database. This is done using the BindDefault method (lines 21–31), which sets the AddressBindingSource’s DataSource property to the result of a LINQ query on the Addresses table. The need for a separate function becomes apparent later, when we have two places that need to set the DataSource to the result of that query. Line 30 uses a GUI element that will be created in subsequent steps—do not add this line until you create findTextBox in Step 8 or the program will not compile.
The BindDefault method must be called from the Form’s Load event handler for the data to be displayed when the application starts (line 35). As before, you create the Load event handler by double clicking the Form’s title bar.
We must also create an event handler to save the changes to the database when the BindingNavigator’s save Button is clicked (lines 40–48). Note that, besides the names of the variables, the three-statement save logic remains the same. We also call BindDefault after saving to re-sort the data and move back to the first element. Recall from Section 21.6 that to allow changes to the database to save between runs of the application, you must select the database in the Solution Explorer, then change its Copy to Output Directory property to Copy if newer in the Properties window.
The AddressBook database is configured to require values for the first name, last name, phone number or e-mail. In order to simplify the code, we have not checked for errors, but an exception (of type System.Data.SqlClient.SqlException) will be thrown if you attempt to save when any of the fields are empty.
Step 7: Running the Application
Run the application and experiment with the controls in the BindingNavigator at the top of the window. Like the previous examples, this example fills a BindingSource object (called addressBindingSource, specifically) with all the rows of a database table (i.e., Addresses). However, only a single row of the database appears at any given time. The CD- or DVD-like buttons of the BindingNavigator allow you to change the currently displayed row (i.e., change the values in each of the TextBoxes). The Buttons to add a row, delete a row and save changes also perform their designated tasks. Adding a row clears the TextBoxes and sets the TextBox to the right of Address ID to zero. Note that if starting with an empty database, the TextBoxes will be empty and editable even though there is no current entry—be sure to create a new entry with the add Button before you enter data or saving will have no effect. After entering several address-book entries, click the Save Button to record the new rows to the database—the Address ID field is automatically changed from zero to a unique number by the database. When you close and restart the application, you should be able to use the BindingNavigator controls to browse your entries.
Step 8: Adding Controls to Allow Users to Specify a Last Name to Locate
While the BindingNavigator allows you to browse the address book, it would be more convenient to be able to find a specific entry by last name. To add this functionality to the application, we must create controls to allow the user to enter a last name, then event handlers to actually perform the search.
Go to Design view and add to the Form a Label named findLabel, a TextBox named findTextBox, and a Button named findButton. Place these controls in a GroupBox named findGroupBox. Set the Text properties of these controls as shown in Fig. 21.30.
Step 9: Programming an Event Handler that Locates the User-Specified Last Name
Double click findButton to create a Click event handler for this Button. In the event handler, use LINQ to select only people with the last name entered in findTextBox and sort them by last name, then first name (lines 57–60). Start the application to test the new functionality. When you enter a last name and click Find, the BindingNavigator allows the user to browse only the rows containing the specified last name. This is because the data source bound to the Form’s controls (the result of the LINQ query) has changed and now contains only a limited number of rows. The database in this example is initially empty, so you’ll need to add several records before testing the find capability.
Step 10: Allowing the User to Return to Browsing All Rows of the Database
To allow users to return to browsing all the rows after searching for specific rows, add a Button named browseAllButton below the findGroupBox. Set the Text property of browseAllButton to Browse All Entries. Double click browseAllButton to create a Click event handler. Have the event handler call BindDefault (line 67) to restore the data source to the full list of people. Also modify BindDefault so that it clears findTextBox (line 30).
Data Binding in the AddressBook Application
Dragging and dropping the Address node from the Data Sources window onto the AddressBookForm caused the IDE to generate several components in the component tray. These serve the same purposes as those generated for the earlier examples that use the Books database. In this example, addressBindingSource uses LINQ to SQL to manipulate the AddressBookDataContext’s Addresses table. The BindingNavigator (named addressBindingNavigator) is bound to addressBindingSource, enabling the user to manipulate the Addresses table through the GUI. This binding is created by assigning addressBindingSource to addressBindingNavigator’s BindingSource property. This is done automatically when the IDE creates them after you drag the Address data source onto the Form.
In each of the earlier examples using a DataGridView to display all the rows of a database table, the DataGridView’s DataSource property was set to the corresponding BindingSource object. In this example, you selected Details from the drop-down list for the Addresses table in the Data Sources window, so the values from a single row of the table appear on the Form in a set of TextBoxes. In this example, the IDE binds each TextBox to a specific column of the Addresses table in the AddressBookDataContext. To do this, the IDE sets the TextBox’s DataBindings.Text property. You can view this property by clicking the plus sign next to (DataBindings) in the Properties window. Clicking the drop-down list for this property (as in Fig. 21.31) allows you to choose a BindingSource object and a property (i.e., column) within the associated data source to bind to the TextBox. Using a BindingSource keeps the data displayed in the TextBoxes synchronized, and allows the BindingNavigator to update them by changing the current row in the BindingSource.
Fig. 21.31 Data bindings for firstNameTextBox in the AddressBook application.
Consider the TextBox that displays the FirstName value—named firstNameTextBox by the IDE. This control’s DataBindings.Text property is set to the FirstName property of addressBindingSource (which refers to the Addresses table in the database). Thus, firstNameTextBox always displays the FirstName column’s value in the currently selected row of the Addresses table. Each IDE-created TextBox on the Form is configured in a similar manner. Browsing the address book with addressBindingNavigator changes the current position in addressBindingSource, and thus changes the values displayed in each TextBox. Regardless of changes to the contents of the Addresses table in the database, the TextBoxes remain bound to the same properties of the table and always display the appropriate data. The TextBoxes do not display any values if addressBindingSource is empty.