Bind WPF controls to a dataset in .NET Framework applications
Note
Datasets and related classes are legacy .NET Framework technologies from the early 2000s that enable applications to work with data in memory while the applications are disconnected from the database. The technologies are especially useful for applications that enable users to modify data and persist the changes back to the database. Although datasets have proven to be a very successful technology, we recommend that new .NET applications use Entity Framework Core. Entity Framework provides a more natural way to work with tabular data as object models, and it has a simpler programming interface.
In this walkthrough, you create a WPF application that contains data-bound controls. The controls are bound to product records that are encapsulated in a dataset. You also add buttons to browse through products and save changes to product records.
This walkthrough illustrates the following tasks:
Creating a WPF application and a dataset that is generated from data in the AdventureWorksLT sample database.
Creating a set of data-bound controls by dragging a data table from the Data Sources window to a window in the WPF Designer.
Creating buttons that navigate forward and backward through product records.
Creating a button that saves changes that users make to the product records to the data table and the underlying data source.
Note
Your computer might show different names or locations for some of the Visual Studio user interface elements in this article. You might be using a different edition of Visual Studio or different environment settings. For more information, see Personalize the IDE.
Prerequisites
You need the following components to complete this walkthrough:
To complete this tutorial, you need the .NET desktop development and Data storage and processing workloads installed in Visual Studio. To install them, open Visual Studio Installer and choose Modify (or More > Modify) next to the version of Visual Studio you want to modify. See Modify Visual Studio.
Access to a running instance of SQL Server or SQL Server Express that has the AdventureWorks Light (AdventureWorksLT) sample database attached to it. To download the database, see AdventureWorks sample databases.
Prior knowledge of the following concepts is also helpful, but not required to complete the walkthrough:
Datasets and TableAdapters. For more information, see Dataset tools in Visual Studio and TableAdapters.
WPF data binding. For more information, see Data Binding Overview.
Create the project
Create a new WPF project to display product records.
Open Visual Studio.
On the start window, choose Create a new project.
Search for the C# WPF App project template and follow the steps to create the project, naming the project AdventureWorksProductsEditor.
Visual Studio creates the AdventureWorksProductsEditor project.
Create a dataset for the application
Before you can create data-bound controls, you must define a data model for your application and add it to the Data Sources window. In this walkthrough, you create a dataset to use as the data model.
On the Data menu, click Show Data Sources.
The Data Sources window opens.
In the Data Sources window, click Add New Data Source.
The Data Source Configuration wizard opens.
On the Choose a Data Source Type page, select Database, and then select Next.
On the Choose a Database Model page, select Dataset, and then select Next.
On the Choose Your Data Connection page, select one of the following options:
If a data connection to the AdventureWorksLT sample database is available in the dropdown list, select it, and then select Next.
Click New Connection, and create a connection to the AdventureWorksLT database.
On the Save the Connection String to the Application Configure File page, select the Yes, save the connection as checkbox, and then select Next.
On the Choose Your Database Objects page, expand Tables, and then select the Product (SalesLT) table.
Click Finish.
Visual Studio adds a new
AdventureWorksLTDataSet.xsd
file to the project, and it adds a corresponding AdventureWorksLTDataSet item to the Data Sources window. TheAdventureWorksLTDataSet.xsd
file defines a typed dataset namedAdventureWorksLTDataSet
and a TableAdapter namedProductTableAdapter
. Later in this walkthrough, you will use theProductTableAdapter
to fill the dataset with data and save changes back to the database.Build the project.
Edit the default fill method of the TableAdapter
To fill the dataset with data, use the Fill
method of the ProductTableAdapter
. By default, the Fill
method fills the ProductDataTable
in the AdventureWorksLTDataSet
with all rows of data from the Product table. You can modify this method to return only a subset of the rows. For this walkthrough, modify the Fill
method to return only rows for products that have photos.
In Solution Explorer, double-click the AdventureWorksLTDataSet.xsd file.
The Dataset designer opens.
In the designer, right-click the Fill, GetData() query and select Configure.
The TableAdapter Configuration wizard opens.
In the Enter a SQL Statement page, add the following
WHERE
clause after theSELECT
statement in the text box.WHERE ThumbnailPhotoFileName <> 'no_image_available_small.gif'
Click Finish.
Define the user interface
Add several buttons to the window by modifying the XAML in the WPF Designer. Later in this walkthrough, you will add code that enables users to scroll through and save changes to products records by using these buttons.
In Solution Explorer, double-click MainWindow.xaml.
The window opens in the WPF Designer.
In the XAML view of the designer, add the following code between the
<Grid>
tags:<Grid.RowDefinitions> <RowDefinition Height="75" /> <RowDefinition Height="625" /> </Grid.RowDefinitions> <Button HorizontalAlignment="Left" Margin="22,20,0,24" Name="backButton" Width="75"><</Button> <Button HorizontalAlignment="Left" Margin="116,20,0,24" Name="nextButton" Width="75">></Button> <Button HorizontalAlignment="Right" Margin="0,21,46,24" Name="saveButton" Width="110">Save changes</Button>
Build the project.
Create data-bound controls
Create controls that display customer records by dragging the Product
table from the Data Sources window to the WPF Designer.
In the Data Sources window, click the dropdown list menu for the Product node and select Details.
Expand the Product node.
For this example, some fields will not be displayed, so click the dropdown list menu next to the following nodes and select None:
ProductCategoryID
ProductModelID
ThumbnailPhotoFileName
rowguid
ModifiedDate
Click the dropdown list menu next to the ThumbNailPhoto node and select Image.
Note
By default, items in the Data Sources window that represent pictures have their default control set to None. This is because pictures are stored as byte arrays in databases, and byte arrays can contain anything from a simple array of bytes to the executable file of a large application.
From the Data Sources window, drag the Product node to the grid row under the row that contains the buttons.
Visual Studio generates XAML that defines a set of controls that are bound to data in the Products table. It also generates code that loads the data. For more information about the generated XAML and code, see Bind WPF controls to data in Visual Studio.
In the designer, click the text box next to the Product ID label.
In the Properties window, select the checkbox next to the IsReadOnly property.
Navigate product records
Add code that enables users to scroll through product records by using the < and > buttons.
In the designer, double-click the < button on the window surface.
Visual Studio opens the code-behind file, and creates a new
backButton_Click
event handler for the Click event.Modify the
Window_Loaded
event handler, so theProductViewSource
,AdventureWorksLTDataSet
, andAdventureWorksLTDataSetProductTableAdapter
are outside of the method and accessible to the entire form. Declare only these to be global to the form, and assign them within theWindow_Loaded
event handler similar to the following:private AdventureWorksProductsEditor.AdventureWorksLTDataSet AdventureWorksLTDataSet; private AdventureWorksProductsEditor.AdventureWorksLTDataSetTableAdapters.ProductTableAdapter adventureWorksLTDataSetProductTableAdapter; private System.Windows.Data.CollectionViewSource productViewSource; private void Window_Loaded(object sender, RoutedEventArgs e) { AdventureWorksLTDataSet = ((AdventureWorksProductsEditor.AdventureWorksLTDataSet)(this.FindResource("adventureWorksLTDataSet"))); // Load data into the table Product. You can modify this code as needed. adventureWorksLTDataSetProductTableAdapter = new AdventureWorksProductsEditor.AdventureWorksLTDataSetTableAdapters.ProductTableAdapter(); adventureWorksLTDataSetProductTableAdapter.Fill(AdventureWorksLTDataSet.Product); productViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("productViewSource"))); productViewSource.View.MoveCurrentToFirst(); }
Add the following code to the
backButton_Click
event handler:Return to the designer and double-click the > button.
Add the following code to the
nextButton_Click
event handler:
Save changes to product records
Add code that enables users to save changes to product records by using the Save changes button.
In the designer, double-click the Save changes button.
Visual Studio opens the code-behind file, and creates a new
saveButton_Click
event handler for the Click event.Add the following code to the
saveButton_Click
event handler:Note
This example uses the
Save
method of theTableAdapter
to save the changes. This is appropriate in this walkthrough, because only one data table is being changed. If you need to save changes to multiple data tables, you can alternatively use theUpdateAll
method of theTableAdapterManager
that Visual Studio generates with your dataset. For more information, see TableAdapters.
Test the application
Build and run the application. Verify that you can view and update product records.
Press F5.
The application builds and runs. Verify the following:
The text boxes display data from the first product record that has a photo. This product has the product ID 713, and the name Long-Sleeve Logo Jersey, S.
You can click the > or < buttons to navigate through other product records.
In one of the product records, change the Size value, and then select Save changes.
Close the application, and then restart the application by pressing F5 in Visual Studio.
Navigate to the product record you changed, and verify that the change persisted.
Close the application.
Next steps
After completing this walkthrough, you might try the following related tasks:
Learn how to use the Data Sources window in Visual Studio to bind WPF controls to other types of data sources. For more information, see Bind WPF controls to a WCF data service.
Learn how to use the Data Sources window in Visual Studio to display related data (that is, data in a parent-child relationship) in WPF controls. For more information, see Walkthrough: Display related data in a WPF app.