1create A Simple Data Application by Using ADO
1create A Simple Data Application by Using ADO
In this topic
Set up the sample database
Create the forms and add controls
Store the connection string
Retrieve the connection string
Write the code for the forms
Test your application
Prerequisites
To create the application, you'll need:
Visual Studio Community Edition.
SQL Server Express LocalDB.
The small sample database that you create by following the steps in Create a SQL database by
using a script.
The connection string for the database after you set it up. You can find this value by opening SQL
Server Object Explorer, opening the shortcut menu for the database, selecting Properties, and
then scrolling to the ConnectionString property.
Return returnValue
End Function
End Class
End Namespace
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 select 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 selecting
the Place Order button.
Create event handlers
Create an empty Click event handler for each button on the form.
Create code for NewCustomer
Add the following code to the NewCustomer form. Step through each code block by using the numbered
comments and the table after the code.
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
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"
Page | 9
' NC-24 Add return value for stored procedure, which is orderID.
cmdNewOrder.Parameters.Add(New SqlParameter("@RC", SqlDbType.Int))
cmdNewOrder.Parameters("@RC").Direction = ParameterDirection.ReturnValue
' try-catch-finally
Try
' Open connection.
conn.Open()
Catch
' A simple catch.
MessageBox.Show("Order could 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.
NC-3 Call the GetConnectionString method to get the connection string from the App
config file, and store the value in the connstr string variable.
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.
Comment Description
Page | 11
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.
Page | 12
NC-12 Use the ExecuteNonQuery method for cmdNewCustomer to run
the Sales.uspNewCustomer stored procedure. This stored procedure runs
an INSERT statement, not a query.
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.
Comment Description
Page | 13
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.
NC-19 These sections of code resemble the code that you added for
through the btnCreateAccount_Click event handler.
NC-25
- NC-19. Create the SqlCommand object, cmdNewOrder, and
specify Sales.uspPlaceOrder as the stored procedure.
- NC-20 through NC-23 are the input parameters for the stored procedure.
- NC-24. @RC will contain a return value that's the generated order ID from the
database. This parameter's direction is specified as ReturnValue.
- NC-25. Store the value of order ID in the orderID variable that you declared at NC-2,
and display the value in a message box.
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 select the Find
Order button. The returned row appears in a read-only data grid. You can mark the order as canceled (X)
if you select the Cancel Order button, or you can mark the order as filled (F) if you select the Fill
Order button. If you select the Find Order button again, the updated row appears.
Create event handlers
Create empty Click event handlers for the four buttons on the form.
Create code for FillOrCancel
Page | 14
Add the following code to the FillOrCancel form. Step through the code blocks by using the numbered
comments and the table that follows the code.
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
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() Page | 15
' Run the command by using SqlDataReader.
Dim rdr As SqlDataReader = cmdOrderID.ExecuteReader()
' Load the data from SqlDataReader into the data table.
dataTable.Load(rdr)
' Display the data from the data table in the data grid view.
Me.dgvCustomerOrders.DataSource = dataTable
' try-catch-finally
Try
' Open the connection.
conn.Open()
' try-catch-finally
Try
' Open the connection.
conn.Open()
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 These tasks are required before you try to run an SQL statement or a stored procedure.
Comment Description
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.