Pass data between forms
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. They 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.
This tutorial provides step-by-step instructions for passing data from one form to another. Using the customers and orders tables from Northwind, one form allows users to select a customer, and a second form displays the selected customer's orders. This tutorial shows how to create a method on the second form that receives data from the first form.
Note
This tutorial demonstrates only one way to pass data between forms. There are other options for passing data to a form, including creating a second constructor to receive data, or creating a public property that can be set with data from the first form.
Tasks illustrated in this tutorial include:
Creating a new Windows Forms App (.NET Framework) project.
Creating and configuring a dataset with the Data Source Configuration Wizard.
Selecting the control to be created on the form when dragging items from the Data Sources window. For more information, see Set the control to be created when dragging from the Data Sources window.
Creating a data-bound control by dragging items from the Data Sources window onto a form.
Creating a second form with a grid to display data.
Creating a TableAdapter query to fetch orders for a specific customer.
Passing data between forms.
Prerequisites
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.
This tutorial uses SQL Server Express LocalDB and the Northwind sample database.
If you don't have SQL Server Express LocalDB, install it either from the SQL Server Express download page, or through the Visual Studio Installer. In the Visual Studio Installer, SQL Server Express LocalDB can be installed as part of the Data storage and processing workload, or as an individual component.
Install the Northwind sample database by following these steps:
In Visual Studio, open the SQL Server Object Explorer window. (SQL Server Object Explorer is installed as part of the Data storage and processing workload in the Visual Studio Installer.) Expand the SQL Server node. Right-click on your LocalDB instance and select New Query.
A query editor window opens.
Copy the Northwind Transact-SQL script to your clipboard. This T-SQL script creates the Northwind database from scratch and populates it with data.
Paste the T-SQL script into the query editor, and then choose the Execute button.
After a short time, the query finishes running and the Northwind database is created.
Create the Windows Forms app project
In Visual Studio, on the File menu, select New > Project.
Expand either Visual C# or Visual Basic in the left-hand pane, then select Windows Desktop.
In the middle pane, select the Windows Forms App project type.
Name the project PassingDataBetweenForms, and then choose OK.
The PassingDataBetweenForms project is created, and added to Solution Explorer.
Create the data source
To open the Data Sources window, on the Data menu, click Show Data Sources.
In the Data Sources window, select Add New Data Source to start the Data Source Configuration wizard.
Select Database on the Choose a Data Source Type page, and then click Next.
On the Choose a database model page, verify that Dataset is specified, and then click Next.
On the Choose your Data Connection page, do one of the following:
If a data connection to the Northwind sample database is available in the dropdown list, select it.
Select New Connection to launch the Add/Modify Connection dialog box.
If your database requires a password and if the option to include sensitive data is enabled, select the option and then click Next.
On the Save connection string to the Application Configuration file page, click Next.
On the Choose your Database Objects page, expand the Tables node.
Select the Customers and Orders tables, and then click Finish.
The NorthwindDataSet is added to your project, and the Customers and Orders tables appear in the Data Sources window.
Create the first form (Form1)
You can create a data-bound grid (a DataGridView control), by dragging the Customers node from the Data Sources window onto the form.
To create a data-bound grid on the form
Drag the main Customers node from the Data Sources window onto Form1.
A DataGridView and a tool strip (BindingNavigator) for navigating records appear on Form1. A NorthwindDataSet, CustomersTableAdapter, BindingSource, and BindingNavigator appear in the component tray.
Create the second form
Create a second form to pass data to.
From the Project menu, choose Add Windows Form.
Leave the default name of Form2, and click Add.
Drag the main Orders node from the Data Sources window onto Form2.
A DataGridView and a tool strip (BindingNavigator) for navigating records appear on Form2. A NorthwindDataSet, CustomersTableAdapter, BindingSource, and BindingNavigator appear in the component tray.
Delete the OrdersBindingNavigator from the component tray.
The OrdersBindingNavigator disappears from Form2.
Add a TableAdapter query
Add a TableAdapter query to Form2 to load orders for the selected customer on Form1.
Double-click the NorthwindDataSet.xsd file in Solution Explorer.
Right-click the OrdersTableAdapter, and select Add Query.
Leave the default option of Use SQL statements, and then click Next.
Leave the default option of SELECT which returns rows, and then click Next.
Add a
WHEREclause to the query, to returnOrdersbased on theCustomerID. The query should be similar to the following:SELECT OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders WHERE CustomerID = @CustomerIDNote
Verify the correct parameter syntax for your database. For example, in Microsoft Access, the
WHEREclause would look like:WHERE CustomerID = ?.Click Next.
For the Fill a DataTableMethod Name, type
FillByCustomerID.Clear the Return a DataTable option, and then click Next.
Click Finish.
Create a method on Form2 to pass data to
Right-click Form2, and select View Code to open Form2 in the Code Editor.
Add the following code to Form2 after the
Form2_Loadmethod:
internal void LoadOrders(String CustomerID)
{
ordersTableAdapter.FillByCustomerID(northwindDataSet.Orders, CustomerID);
}
Create a method on Form1 to pass data and display Form2
In Form1, right-click the Customer data grid, and then click Properties.
In the Properties window, click Events.
Double-click the CellDoubleClick event.
The code editor appears.
Update the method definition to match the following sample:
private void customersDataGridView_DoubleClick(object sender, EventArgs e)
{
System.Data.DataRowView SelectedRowView;
NorthwindDataSet.CustomersRow SelectedRow;
SelectedRowView = (System.Data.DataRowView)customersBindingSource.Current;
SelectedRow = (NorthwindDataSet.CustomersRow)SelectedRowView.Row;
Form2 OrdersForm = new Form2();
OrdersForm.LoadOrders(SelectedRow.CustomerID);
OrdersForm.Show();
}
Run the app
Press F5 to run the application.
Double-click a customer record in Form1 to open Form2 with that customer's orders.
Next steps
Depending on your application requirements, there are several steps you might want to perform after passing data between forms. Some enhancements you could make to this tutorial include:
Editing the dataset to add or remove database objects. For more information, see Create and configure datasets.
Adding functionality to save data back to the database. For more information, see Save data back to the database.
Related content
Feedback
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback.
Submit and view feedback for