Create a database and add tables in Visual Studio
You can use Visual Studio to create and update a local database file in SQL Server Express LocalDB.
You can also create a database by executing Transact-SQL statements in the SQL Server Object
Explorer tool window in Visual Studio. In this topic, we'll create an .mdf file and add tables and keys by
using the Table Designer.
Create a project and a local database file
1. Create a new Windows Forms App project and name it SampleDatabaseWalkthrough.
2. On the menu bar, select Project > Add New Item.
3. In the list of item templates, scroll down and select Service-based Database.
4. Name the database SampleDatabase, and then click Add.
Add a data source
1. If the Data Sources window isn't open, open it by pressing Shift+Alt+D or
selecting View > Other Windows > Data Sources on the menu bar.
2. In the Data Sources window, select Add New Data Source.
The Data Source Configuration Wizard opens.
3. On the Choose a Data Source Type page, choose Database and then choose Next.
4. On the Choose a Database Model page, choose Next to accept the default (Dataset).
5. On the Choose Your Data Connection page, select the [Link] file in the drop-
down list, and then choose Next.
6. On the Save the Connection String to the Application Configuration File page, choose Next.
7. On the Choose your Database Objects page, you'll see a message that says the database doesn't
contain any objects. Choose Finish.
View properties of the data connection
You can view the connection string for the [Link] file by opening the Properties window
of the data connection:
Select View > SQL Server Object Explorer to open the SQL Server Object Explorer window.
Expand (localdb)\MSSQLLocalDB > Databases, and then right-click
on [Link] and select Properties.
Alternatively, you can select View > Server Explorer, if that window isn't already open. Open the
Properties window by expanding the Data Connections node, right-clicking
on [Link], and then selecting Properties.
If you can't expand the Data Connections node, or the [Link] connection is not
listed, select the Connect to Database button in the Server Explorer toolbar. In the Add
Connection dialog box, make sure that Microsoft SQL Server Database File is selected
under Data source, and then browse to and select the [Link] file. Finish adding the
connection by selecting OK.
Create tables and keys by using Table Designer
Create two tables, a primary key in each table, and a few rows of sample data. Create a foreign key to
specify how records in one table correspond to records in the other table.
Create the Customers table
1. In Server Explorer, expand the Data Connections node, and then expand
the [Link] node.
If you can't expand the Data Connections node, or the [Link] connection is not
listed, select the Connect to Database button in the Server Explorer toolbar. In the Add
Connection dialog box, make sure that Microsoft SQL Server Database File is selected
under Data source, and then browse to and select the [Link] file. Finish adding the
connection by selecting OK.
2. Right-click on Tables and select Add New Table.
The Table Designer opens and shows a grid with one default row, which represents a single
column in the table that you're creating. By adding rows to the grid, you'll add columns in the table.
3. In the grid, add a row for each of the following entries:
Column name Data type Allow nulls
CustomerID nchar(5) False (cleared)
CompanyName nvarchar(50) False (cleared)
ContactName nvarchar (50) True (selected)
Phone nvarchar (24) True (selected)
4. Right-click on the CustomerID row, and then select Set Primary Key.
5. Right-click on the default row (Id), and then select Delete.
6. Name the Customers table by updating the first line in the script pane to match the following
sample:
CREATE TABLE [dbo].[Customers]
You should see something like this:
7. In the upper-left corner of Table Designer, select Update.
8. In the Preview Database Updates dialog box, select Update Database.
The Customers table is created in the local database file.
Create the Orders table
1. Add another table, and then add a row for each entry in the following table:
Column name Data type Allow nulls
OrderID int False (cleared)
CustomerID nchar(5) False (cleared)
OrderDate datetime True (selected)
OrderQuantity int True (selected)
2. Set OrderID as the primary key, and then delete the default row.
3. Name the Orders table by updating the first line in the script pane to match the following sample:
CREATE TABLE [dbo].[Orders]
4. In the upper-left corner of the Table Designer, select Update.
5. In the Preview Database Updates dialog box, select Update Database.
The Orders table is created in the local database file. If you expand the Tables node in Server
Explorer, you see the two tables:
Create a foreign key
1. In the context pane on the right side of the Table Designer grid for the Orders table, right-click
on Foreign Keys and select Add New Foreign Key.
2. In the text box that appears, replace the text ToTable with Customers.
3. In the T-SQL pane, update the last line to match the following sample:
CONSTRAINT [FK_Orders_Customers] FOREIGN KEY ([CustomerID]) REFERENCES
[Customers]([CustomerID])
4. In the upper-left corner of the Table Designer, select Update.
5. In the Preview Database Updates dialog box, select Update Database.
The foreign key is created.
Populate the tables with data
1. In Server Explorer or SQL Server Object Explorer, expand the node for the sample database.
2. Open the shortcut menu for the Tables node, select Refresh, and then expand the Tables node.
3. Open the shortcut menu for the Customers table, and then select Show Table Data.
4. Add whatever data you want for some customers.
You can specify any five characters you want as the customer IDs, but choose at least one that you
can remember for use later in this procedure.
5. Open the shortcut menu for the Orders table, and then select Show Table Data.
6. Add data for some orders.
Make sure that all order IDs and order quantities are integers and that each customer ID matches a
value that you specified in the CustomerID column of the Customers table.
7. On the menu bar, select File > Save All.
Create a Windows Form to search data
A common application scenario is to display selected data on a form. For example, you might want to
display the orders for a specific customer or the details of a specific order. In this scenario, a user enters
information into a form, and then a query is executed with the user's input as a parameter; that is, the data
is selected based on a parameterized query. The query returns only the data that satisfies the criteria
entered by the user. This walkthrough shows how to create a query that returns customers in a specific
city, and modify the user interface so that users can enter a city's name and press a button to execute the
query.
Using parameterized queries helps make your application efficient by letting the database do the work it
is best at — quickly filtering records. In contrast, if you request an entire database table, transfer it over
the network, and then use application logic to find the records you want, your application can become
slow and inefficient.
You can add parameterized queries to any TableAdapter (and controls to accept parameter values and
execute the query), using the Search Criteria Builder dialog box. Open the dialog box by selecting
the Add Query command on the Data menu (or on any TableAdapter smart tag).
Tasks illustrated in this walkthrough include:
Creating and configuring the data source in your application with the Data Source
Configuration wizard.
Setting the drop type of the items in the Data Sources window.
Creating controls that display data by dragging items from the Data Sources window onto a form.
Adding controls to display the data on the form.
Completing the Search Criteria Builder dialog box.
Entering parameters into the form and executing the parameterized query.
Prerequisites
This walkthrough uses SQL Server Express LocalDB and the Northwind sample database.
1. 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, you can
install SQL Server Express LocalDB as part of the Data storage and processing workload, or as
an individual component.
2. Install the Northwind sample database by following these steps:
1. 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.
2. Copy the Northwind Transact-SQL script to your clipboard. This T-SQL script creates the
Northwind database from scratch and populates it with data.
3. 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 application
Create a new Windows Forms App project for Visual Basic. Name the project WindowsSearchForm.
Create the data source
This step creates a data source from a database using the Data Source Configuration wizard:
1. To open the Data Sources window, on the Data menu, click Show Data Sources.
2. In the Data Sources window, select Add New Data Source to start the Data Source
Configuration wizard.
3. Select Database on the Choose a Data Source Type page, and then click Next.
4. On the Choose your Data Connection page do one of the following:
o If a data connection to the Northwind sample database is available in the drop-down list,
select it.
o Select New Connection to launch the Add/Modify Connection dialog box.
5. If your database requires a password, select the option to include sensitive data, and then
click Next.
6. On the Save connection string to the Application Configuration file page, click Next.
7. On the Choose your Database Objects page, expand the Tables node.
8. Select the Customers table, and then click Finish.
The NorthwindDataSet is added to your project, and the Customers table appears in the Data
Sources window.
Create the form
You can create the data-bound controls by dragging items from the Data Sources window onto your
form:
1. Expand the Customers node in the Data Sources window.
2. Drag the Customers node from the Data Sources window to your form.
A DataGridView and a tool strip (BindingNavigator) for navigating records appear on the form.
A NorthwindDataSet, CustomersTableAdapter, BindingSource, and BindingNavigator appear in the
component tray.
Add parameterization (search functionality) to the query
You can add a WHERE clause to the original query using the Search Criteria Builder dialog box:
1. Select the DataGridView control, and then choose Add Query on the Data menu.
2. Type FillByCity in the New query name area on the Search Criteria Builder dialog box.
3. Add WHERE City = @City to the query in the Query Text area.
The query should be similar to the following:
SELECT CustomerID, CompanyName, ContactName, ContactTitle,
Address, City, Region, PostalCode, Country, Phone, Fax
FROM Customers
WHERE City = @City
Note
Access and OLE DB data sources use the question mark ('?') to denote parameters, so the WHERE
clause would look like this: WHERE City = ?.
4. Click OK to close the Search Criteria Builder dialog box.
A FillByCityToolStrip is added to the form.
Test the application
Running the application opens your form and makes it ready to take the parameter as input:
1. Press F5 to run the application.
2. Type London into the City text box, and then click FillByCity.
The data grid is populated with customers that meet the criteria. In this example, the data grid only
displays customers that have a value of London in their City column.