Home > Articles > Programming > Windows Programming

This chapter is from the book

21.6 LINQ to SQL: Extracting Information from a Database

In this section, we demonstrate how to connect to a database, query it and display the result of the query. There is little code in this section—the IDE provides visual programming tools and wizards that simplify accessing data in your projects. These tools establish database connections and create the data-binding objects necessary to view and manipulate the data through Windows Forms GUI controls.

The next example performs a simple query on the Books database from Section 21.3. The program retrieves the entire Authors table and uses data binding to display its data in a DataGridView—a control from namespace System.Windows.Forms that can display a data source in a GUI. First, we connect to the Books database and create the LINQ to SQL classes required to use it. Then, we add the Authors table as a data source. Finally, we drag the Authors table data source onto the Design view to create a GUI for displaying the table’s data.

21.6.1 Creating LINQ to SQL Classes

This section presents the steps required to create LINQ to SQL classes for a database. Though we create a Windows Forms Application here, Steps 2–3 apply to any type of application that manipulates a database via LINQ to SQL.

Step 1: Creating the Project

Create a new Windows Forms Application named DisplayTable. Change the name of the source file to DisplayTableForm.cs. When the IDE asks if you wish to update the Form’s class name to match the source file, select Yes. Set the Form’s Text property to DisplayTable.

Step 2: Adding a Database to the Project

To interact with a database, you must first add it to the project. Select Tools > Connect to Database.... If the Choose Data Source dialog appears, select Microsoft SQL Server Database File from the Data source: ListBox. If you check the Always use this selection CheckBox, Visual C# will use this type of database file by default when you add databases to your projects in the future. Click Continue to open the Add Connection dialog. Notice that the Data source: TextBox reflects your selection in the Choose Data Source dialog. You can click the Change... Button to select a different type of database. Next, click Browse... and locate the Books.mdf file in the Databases directory included with this chapter’s examples. You can click Test Connection to verify that the IDE can connect to the database through SQL Server Express. Click OK to create the connection.

Step 3: Generating the LINQ to SQL classes

After the database has been added, you must create the classes based on the database schema. To do this, right click the project name in the Solution Explorer and select Add > New Item... to display the Add New Item dialog. Select LINQ to SQL classes, name the new item Books.dbml and click the Add button. After a few moments, the Object Relational Designer window appears. You can also double click the Books.dbml file in the Solution Explorer to open the Object Relational Designer.

The Database Explorer window, which lets you navigate the structure of databases, should have appeared on the left side of the IDE when you added the database to the project. If not, open it by selecting View > Other Windows > Database Explorer. Expand the Books.mdf database node, then expand the Tables node. Drag the Authors, Titles and AuthorISBN tables onto the Object Relational Designer. The IDE prompts whether you want to copy the database to the project directory. Select Yes. Then save the Books.dbml file. At this point, the IDE generates the LINQ to SQL classes—the next steps will not work if you do not save the .dbml file.

21.6.2 Creating Data Bindings

While they are not a part of LINQ to SQL, the automatic data bindings that the IDE provides greatly simplify the creation of applications to view and modify the data stored in the database’s tables. You must write a small amount of code to bridge the gap between the autogenerated data-binding classes and the autogenerated LINQ to SQL classes.

Step 1: Adding a Data Source

To use the LINQ to SQL classes in our bindings, we must first add them as a data source. Select Data > Add New Data Source... to display the Data Source Configuration Wizard. Since the LINQ to SQL classes can be used to create objects representing the tables in the database, we’ll use an object data source. In the dialog, select Object and click Next >. Expand the tree view in the next screen and select DisplayTable > DisplayTable > Author. The first DisplayTable is the project’s name, the second is the DisplayTable namespace where the automatically generated classes are located, and the last is the Author class—an object of this class will be used as the data source. Click Next > then Finish. The Authors table in the database is now a data source that can be used by the bindings.

Step 2: Create GUI Elements

Open the Data Sources window by selecting Data > Show Data Sources. The Author class that you added in the previous step should appear. The columns of the Authors table should appear below it, as well as an AuthorISBNs entry showing the relationship between the two tables.

Open the DisplayTableForm in Design view. Click the Author node in the Data Sources window—it should change to a drop-down list. Open the drop-down and ensure that the DataGridView option is selected—this is the GUI control that will be used to display and interact with the data.

Drag the Author node from the Data Sources window to the DisplayTableForm. The IDE creates a DataGridView with the correct column names and a BindingNavigator. The BindingNavigator contains Buttons for moving between entries, adding entries, deleting entries and saving changes to the database. The IDE also generates a BindingSource, which transfers data between the data source and the data-bound controls on the Form. Nonvisual components such as the BindingSource and the nonvisual aspects of the BindingNavigator appear in the component tray—the gray region below the Form in Design view (Fig. 21.23). We use the default names for automatically generated components throughout this chapter to show exactly what the IDE creates, but we have made small modifications to the layout such as setting the DataGridView’s Dock property to Fill so it fills the Form. These modifications have no effect on the behavior of the program, and are simply cosmetic—you may also want to tweak the GUI to suit your tastes.

Figure 21.23

Fig. 21.23 Component tray holds nonvisual components in Design view.

Step 3: Connect the BooksDataContext to the AuthorBindingSource

Now that we’ve created the back-end LINQ to SQL classes and the front-end DataGridView and BindingNavigator, we must connect them with a small amount of code. The DataGridView is already connected to the BindingSource by the IDE, so we simply need to connect the BooksDataContext you declared in the previous section and the authorBindingSource you created above. Figure 21.24 shows the small amount of code needed to move data back and forth between the database and GUI.

Fig. 21.24 Displaying data from a database table in a DataGridView.

 1  // Fig. 21.24: DisplayTableForm.cs
 2  // Displaying data from a database table in a DataGridView.
 3  using System;
 4  using System.Linq;
 5  using System.Windows.Forms;
 6
 7  namespace DisplayTable
 8  {
 9     public partial class DisplayTableForm : Form
10     {
11        // constructor
12       public DisplayTableForm()
13        {
14           InitializeComponent();
15        } // end constructor
16
17        // LINQ to SQL data context
18        private BooksDataContext database = new BooksDataContext();
19
20        // load data from database into DataGridView
21        private void DisplayTableForm_Load( object sender, EventArgs e )
22        {
23           // use LINQ to order the data for display
24           authorBindingSource.DataSource =   
25             from author in database.Authors
26             orderby author.AuthorID         
27             select author;                  
28        } // end method DisplayTableForm_Load
29
30        // click event handler for the Save Button in the
31        // BindingNavigator saves the changes made to the data
32        private void authorBindingNavigatorSaveItem_Click(
33           object sender, EventArgs e )
34        {
35           Validate(); // validate input fields
36           authorBindingSource.EndEdit(); // indicate edits are complete
37           database.SubmitChanges(); // write changes to database file
38        } // end method authorBindingNavigatorSaveItem_Click
39     } // end class DisplayTableForm
40  } // end namespace DisplayTable

As mentioned in the previous section, we must use a DataContext object to interact with the database. The BooksDataContext class is automatically generated by the IDE to allow access to the Books database. Line 18 defines an object of this class named database.

Create the Form’s Load handler by double clicking the title bar in Design view. We allow data to move between the DataContext and the BindingSource by creating a LINQ query that extracts data from the DataContext’s Authors property (lines 25–27), which corresponds to the Authors table in the database. The BindingSource’s DataSource property is set to the results of this query (line 24). The BindingSource uses its DataSource to extract data from the database and to populate the DataGridView.

Step 4: Saving Modifications Back to the Database

We’d like to save data back to the database if the user modifies it. By default, the Binding-Navigator’s save Button (saveicon.jpg) is disabled. Enable it via the save Button’s right-click menu or by using the Properties window to set its Enabled property to True. Then, double click the Button to create its event handler.

Saving the data entered into the DataGridView back to the database is a three-step process (lines 35–37). First, all controls on the form are validated (line 35)—if any of the controls have validation event handlers, those execute to determine whether the controls’ contents are valid. Second, line 36 calls EndEdit on the BindingSource, which forces it to save any pending changes to its DataSource. Finally, with the data saved back to the LINQ to SQL classes, we call SubmitChanges on the BooksDataContext to store the changes in the database. For efficiency reasons, LINQ to SQL sends only data that has changed.

Step 5: Configuring the Database File to Persist Changes

By default, the original database file is copied to the project’s bin directory—the location of the program’s executable—each time you execute the program. To persist changes between program executions, select the database in the Solution Explorer and set the Copy to Output Directory property in the Properties window to Copy if newer.

Testing the Application

Run the application to verify that it works. The DataGridView should be filled with the author data, as shown in the screenshot. You can add and remove rows, and save your changes back to the database. Note that NULL values are not allowed in the database, and the data bindings consider an empty cell in the DataGridView to be NULL, not an empty string. Therefore, attempting to save the data with some of the fields empty will cause an exception to be thrown.

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