Walkthrough: Display Data from a SQL Server Database in a DataGrid Control
In this walkthrough, you retrieve data from a SQL Server database and display that data in a DataGrid control. You use the ADO.NET Entity Framework to create the entity classes that represent the data, and use LINQ to write a query that retrieves the specified data from an entity class.
You need the following components to complete this walkthrough:
Visual Studio 2012.
Access to a running instance of SQL Server or SQL Server Express that has the AdventureWorksLT2008 sample database attached to it. You can download the AdventureWorksLT2008 database from the CodePlex Web site.
To create entity classes
Create a new WPF Application project in Visual Basic or C#, and name it DataGridSQLExample.
In Solution Explorer, right-click your project, point to Add, and then select New Item.
The Add New Item dialog box appears.
In the Installed Templates pane, select Data and in the list of templates, select ADO.NET Entity Data Model.
Name the file AdventureWorksModel.edmx and then click Add.
The Entity Data Model Wizard appears.
In the Choose Model Contents screen, select Generate from database and then click Next.
In the Choose Your Data Connection screen, provide the connection to your AdventureWorksLT2008 database. For more information, see Choose Your Data Connection Dialog Box.
Make sure that the name is AdventureWorksLT2008Entities and that the Save entity connection settings in App.Config as check box is selected, and then click Next.
In the Choose Your Database Objects screen, expand the Tables node, and select the Product and ProductCategory tables.
You can generate entity classes for all of the tables; however, in this example you only retrieve data from those two tables.
The Product and ProductCategory entities are displayed in the Entity Designer.
To retrieve and present the data
Open the MainWindow.xaml file.
Select the Window.
The following shows the XAML for MainWindow.xaml.
If you are using Visual Basic, in the first line of MainWindow.xaml, replace x:Class="DataGridSQLExample.MainWindow" with x:Class="MainWindow".
Open the code-behind file (MainWindow.xaml.vb or MainWindow.xaml.cs) for the Window.
Run the example.
You should see a DataGrid that displays data.