Home > Articles > Programming > Windows Programming

This chapter is from the book

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.

Figure 21.31

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020