Walkthrough: Creating A Simple Data: Prerequisites
Walkthrough: Creating A Simple Data: Prerequisites
When you create an application that manipulates data in a database, you perform basic tasks such defining connection
strings, inserting data, and running stored procedures. By following this topic, you can discover how to interact with a
database from within a simple Windows Forms application by using Visual C# or Visual Basic and ADO.NET.
Important
In this topic
Prerequisites
To create the application, you'll need:
The small sample database that you create by following the steps in Walkthrough: Creating a Small Sample
Database.
The connection string for the database after you set it up. You can find this value by opening SQL Server Object
Explorer or Server Explorer, choosing the database, opening its Properties window for the database, and then
choosing the Debug tab.
This topic assumes that you're familiar with the basic functionality of the Visual Studio IDE and can create a Windows
Forms application, add forms to that project, put buttons and other controls on those forms, set properties of those
controls, and code simple events. If you aren't comfortable with these tasks, we suggest that you complete the Getting
Started Tutorials before you start this topic.
1 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
Visual Studio creates the project and several files, including an empty Windows form that's named Form1.
2. Add two Windows forms to your project so that it has three forms, and then give them the following names.
Navigation
NewCustomer
FillOrCancel
3. For each form, add the text boxes, buttons, and other controls that appear in the following illustrations. For each
control, set the properties that the tables describe.
Note
The group box and the label controls add clarity but aren't used in the code.
Navigation form
NewCustomer form
2 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
Readonly = True
NumericUpdown DecimalPlaces = 0
Maximum = 5000
Name = numOrderAmount
Name = dtpOrderDate
FillOrCancel form
3 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
Name = dtpFillDate
Readonly = True
RowHeaderVisible = False
1. Open the shortcut menu for the project, and then choose Properties.
2. In the left panel of the Properties window, choose the Project Settings tab.
6. In the Value column, enter your connection string, and then save your changes.
4 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
3. Open the Utility file, and then enter the following code. Notice the numbered comments (prefixed with Util-) that
identify sections of the code. The table that follows the code calls out key points.
VB
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
' Util-1 More namespaces.
Imports System.Configuration
Namespace SimpleDataApp
Friend Class Utility
Return returnValue
End Function
End Class
End Namespace
Comment Description
Util-2 Define a variable, returnValue, and initialize it to null (C#) or Nothing (Visual Basic).
Util-3 Even though you entered connString as the name of the connection string in the Properties
window, you must specify "SimpleDataApp.Properties.Settings.connString" (C#) or
"SimpleDataApp.My.MySettings.connString" (Visual Basic) in the code.
Navigation form
The Navigation form opens when you run the application. The Add an account button opens the NewCustomer form.
The Fill or cancel orders button opens the FillOrCancel form. The Exit button closes the application.
5 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
VB
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
Namespace SimpleDataApp
Partial Public Class Navigation
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
' Open the NewCustomer form as a dialog box, which will return focus to the
calling form when it closes.
Private Sub btnGoToAdd_Click() Handles btnGoToAdd.Click
Dim frm As Form = New NewCustomer()
frm.Show()
End Sub
NewCustomer form
When you enter a customer name and then choose the Create Account button, the NewCustomer form creates a
customer account, and SQL Server returns an IDENTITY value as the new account number. You then place an order for
the new account by specifying an amount and an order date and choosing the Place Order button.
6 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
VB
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
' NC-1 More namespaces.
Imports System.Data.SqlClient
Imports System.Configuration
Namespace SimpleDataApp
Partial Public Class NewCustomer
Inherits Form
' NC-5 Set up and run stored procedure only if Customer Name is present.
If isCustomerName() Then
' NC-8 Add input parameter from the stored procedure and specify what
to use as its value.
cmdNewCustomer.Parameters.Add(New SqlParameter("@CustomerName",
SqlDbType.NVarChar, 40))
cmdNewCustomer.Parameters("@CustomerName").Value =
txtCustomerName.Text
7 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
Catch
' NC-14 A simple catch.
MessageBox.Show("Customer ID was not returned. Account could not
be created.")
Finally
' NC-15 Close the connection.
conn.Close()
End Try
End If
End Sub
' NC-18 Set up and run stored procedure only if necessary input is
present.
If isPlaceOrderReady() Then
' NC-23 @Status. For a new order, the status is always O (open).
cmdNewOrder.Parameters.Add(New SqlParameter("@Status", SqlDbType.
[Char], 1))
cmdNewOrder.Parameters("@Status").Value = "O"
' NC-24 add return value for stored procedure, which is the orderID
cmdNewOrder.Parameters.Add(New SqlParameter("@RC", SqlDbType.Int))
cmdNewOrder.Parameters("@RC").Direction =
ParameterDirection.ReturnValue
8 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
Catch
' A simple catch.
MessageBox.Show("Order could not not be placed.")
Finally
' Close connection.
conn.Close()
End Try
End If
End Sub
End Class
End Namespace
Comment Description
NC-2 Declare the parsedCustomerID and orderID variables, which you'll use later.
9 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
NC-4 Add code to the Click event handler for the btnCreateAccount button.
NC-5 Wrap the call to isCustomerName around the Click event code so that uspNewCustomer runs
only if a customer name is present.
NC-6 Create a SqlConnection object (conn), and pass in the connection string in connstr.
NC-8 Add the @CustomerName input parameter from the stored procedure.
NC-10 Add a Try – Catch – Finally block to open the connection, run the stored procedure, handle
exceptions, and then close the connection.
NC-13 The @CustomerID value is returned as an IDENTITY value from the database. Because it's an
integer, you'll have to convert it to a string to display it in the Customer ID text box.
NC-14 For this sample, add a simple, not production-quality catch clause.
NC-15 Always close a connection after you finish using it, so that it can be released to the connection
pool. See SQL Server Connection Pooling (ADO.NET).
If the text box is empty, display a message, and return false, because a name is
required to create the account.
If the text box isn't empty, return true.
NC-17 Add code to the Click event handler for the btnPlaceOrder button.
NC-18 Wrap the call to isPlaceOrderReady around the btnPlaceOrder_Click event code so that
uspPlaceNewOrder doesn't run if required input isn't present.
10 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
NC-26 Define a method to verify that a customer ID exists and that an amount has been specified in
numOrderAmount.
NC-27 Call the ClearForm method in the btnAddAnotherAccount Click event handler.
NC-28 Create the ClearForm method to clear values from the form if you want to add another
customer.
NC29 Close the NewCustomer form, and return focus to the Navigation form.
FillOrCancel form
The FillorCancel form runs a query to return an order when you enter an order ID and choose the Find Order button.
The returned row appears in a read-only data grid. You can mark the order as cancelled (X) if you choose the Cancel
Order button, or you can mark the order as filled (F) if you choose the Fill Order button. If you choose the Find Order
button again, the updated row appears.
VB
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
' FC-1 More namespaces.
Imports System.Text.RegularExpressions
Imports System.Data.SqlClient
Imports System.Configuration
Namespace SimpleDataApp
Partial Public Class FillOrCancel
Inherits Form
' FC-2 Storage for OrderID
Private parsedOrderID As Integer
11 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
If isOrderID() Then
' Create the connection.
Dim conn As New SqlConnection(connstr)
' Define the query string that has a parameter for orderID.
Dim sql As String = "select * from Sales.Orders where orderID =
@orderID"
' try-catch-finally
Try
' FC-6 Run the command and display the results.
' Open connection.
conn.Open()
' Load the data from the SqlDataReader into the data table.
dataTable.Load(rdr)
' Display the data from the data table in the datagridview.
Me.dgvCustomerOrders.DataSource = dataTable
12 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
' try-catch-finally
Try
' Open the connection.
conn.Open()
' try-catch-finally
Try
' Open the connection.
conn.Open()
13 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
Else
' Convert the text in the text box to an integer to send to the
database.
parsedOrderID = Int32.Parse(txtOrderID.Text)
Return True
End If
End Function
Comment Description
FC-3 Call the GetConnectionString method to get the connection string from the App config file,
and store the value in the connstr string variable.
FC-5 Look familiar? These tasks are required before you try to run an SQL statement or a stored
procedure.
FC-6 This code uses SqlDataReader and DataTable to retrieve and display the query result.
FC-7 Add code to the Click event handler for btnCancelOrder. This code runs the
Sales.uspCancelOrder stored procedure.
FC-8 Add code to the Click event handler for btnFillOrder. This code runs the Sales.uspFillOrder
stored procedure.
14 of 15 20/10/2017, 3:55 PM
Walkthrough: Creating a Simple Data Application by Using ADO.NET https://msdn.microsoft.com/en-us/library/jj943772(v=vs.110).aspx?cs-sa...
© 2017 Microsoft
15 of 15 20/10/2017, 3:55 PM