Bagikan melalui


Using LINQ to Bind Data to Controls

In the previous lesson, Creating LINQ to SQL Classes: Using the O/R Designer, you learned how to use the O/R Designer to map LINQ to SQL classes to tables in a database. In this lesson, you will learn how to use a LINQ query to bind data to a control.

Prerequisites

To complete this lesson, you must have access to the SQL Server version of the Northwind sample database. For more information, see How to: Install Sample Databases.

You must complete the lesson Creating LINQ to SQL Classes: Using the O/R Designer before you start this lesson.

To use LINQ to bind data to a control

  1. Open the solution you created in Creating LINQ to SQL Classes: Using the O/R Designer.

  2. Drag a TextBox control from the Toolbox to Form1.

  3. Drag a Button from the Toolbox to Form1, and change its Text property to Run Query.

  4. Double-click the button and add the following code to the Button1_Click event handler:

    Dim CustomersQuery = From customers in NorthwindSampleDataContext1.Customers _
        Where customers.Country = TextBox1.Text _
        Select customers
    
    CustomerBindingSource.DataSource = CustomersQuery
    
  5. Press F5.

  6. Type Germany in the text box.

  7. Click the Run Query button.

  8. Verify that only customers who have a value of Germany in their Country property are displayed. Then try different countries, such as USA or Canada.

Next Steps

In this lesson, you learned how to use LINQ queries to bind data to controls in an application. In the next lesson, you will learn how to use XML Literals in your code.

Next Lesson: Including XML Directly in Your Code: Using XML Literals

See Also

Tasks

Storing and Accessing Data

Creating LINQ to SQL Classes: Using the O/R Designer

Walkthrough: Creating LINQ to SQL Classes (O/R Designer)

Concepts

Using LINQ in Visual Basic Express

O/R Designer Overview

Other Resources

Managing Your Records: Using Data in Your Program