Why there is need of ADO.Net? Explain how to use ADO.Net in any web application.

2 years ago
Cloud Computing

ADO.NET provides a comprehensive caching data model for marshalling data between applications and services with facilities to optimistically update the original data sources. This enables developer to begin with XML while leveraging existing skills with SQL and the relational model.

Although the ADO.NET model is different from the existing ADO model, the same basic concepts include provider, connection and command objects. By combining the continued use of SQL with similar basic concepts, current ADO developers should be able to migrate to ADO.NET over a reasonable period of time.

Create a simple data application by using ADO.NET

When you create an application that manipulates data in a database, stored procedures. By following this topic, you can discover how to interact with a database from within a simple Windows Forms "forms over data" application by using Visual C# or Visual Basic and ADO.NET. All .NET data technologies—including datasets, LINQ to SQL, and Entity Framework—ultimately perform steps that are very similar to those shown in this article.

This article demonstrates a simple way to get data out of a database in a fast manner. If your application needs to modify data in non-trivial ways and update the database, you should consider using Entity Framework and using data binding to automatically sync user interface controls to changes in the underlying data.

Important

you perform basic tasks such as defining connection strings, inserting data, and running To keep the code simple, it doesn't include production-ready exception handling.

Prerequisites

To create the application, you'll need:

  • Visual Studio.
  • SQL Server Express If you don't have SQL Server Express LocalDB, 

Create the sample database by following these steps:

1. In Visual Studio, open the Server Explorer window.

2. Right-click on Data Connections and choose Create New SQL Server Database.

3. In the Server name text box, enter (localdb)\mssqllocaldb.

4. In the New database name text box, enter Sales, then choose OK.

The empty Sales database is created and added to the Data Connections node in Server Explorer.

5. Right-click on the Sales data connection and select New Query.

A query editor window opens.

6. Copy the Sales Transact-SQL script to your clipboard.

7. Paste the T-SQL script into the query editor, and then choose the Execute After a short time, the query finishes running and the database objects are created. The database contains two tables: Customer and Orders. These tables contain no data initially, but you can add data when you run the application that you'll create. The database also contains four simple stored procedures.

Create the forms and add controls

  1. Create a project for a Windows Forms application, and then name it SimpleDataApp. 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:

I)  Navigation

ii) NewCustomer

iii) FillOrCancel

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

                                   

Controls for the Navigation form

Properties

 

Button

 

Name = btnGoToAdd

 

Button

 

Name = btnGoToFillOrCancel

 

Button

 

Name = btnExit

NewCustomer form

                       

 

Controls for the NewCustomer form

Properties

TextBox

Name = txtCustomerName

TextBox

Name = txtCustomerID

 

Readonly = True

Button

Name = btnCreateAccount

NumericUpdown

DecimalPlaces = 0

 

Maximum = 5000

 

Name = numOrderAmount

DateTimePicker

Format = Short

 

Name = dtpOrderDate

Button

Name = btnPlaceOrder

Button

Name = btnAddAnotherAccount

Button

Name = btnAddFinish

FillOrCancel form

                         

Controls for the FillOrCancel form

Properties

TextBox

Name = txtOrderID

Button

Name = btnFindByOrderID

DateTimePicker

Format = Short Name = dtpFillDate

DataGridView

Name = dgvCustomerOrders Readonly = True RowHeadersVisible = False

Button

Name = btnCancelOrder

Button

Name = btnFillOrder

 

Controls for the FillOrCancel form

Properties

Button

Name = btnFinishUpdates

Store the connection string

When your application tries to open a connection to the database, your application must have access to the connection string. To avoid entering the string manually on each form, store the string in the App.config file in your project, and create a method that returns the string when the method is called from any form in your application.

You can find the connection string by right-clicking on the Sales data connection in Server Explorer and     choosing Properties.  Locate the ConnectionString property,     then use Ctrl+A, Ctrl+C to select and copy the string to the clipboard.

  1. If you're using C#, in Solution Explorer, expand the Properties node under the project, and   then open the settings file.   If you're   using   Visual Basic, in Solution Explorer, click Show All Files, expand the My Project node, and then open the Settings.settings file.
  2. In the Name column, enter connString.
  3. In the Type list, select (Connection String).
  4. In the Scope list, select Application.
  5. In the Value column, enter your connection string (without any outside quotes), and then save your changes.

Note

In a real application, you   should   store the connection   string   securely,   as described in Connection strings and configuration files.

Write the code for the forms

This section contains brief overviews of what each form does. It also provides the code that defines the underlying logic when a button on the form is clicked.

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.

Make the Navigation form the startup form

If   you're   using   C#,    in Solution    Explorer,    open Program.cs,    and   then   change the Application.Run line to this: Application.Run(new Navigation());

If you're using Visual Basic, in Solution Explorer, open the Properties window, select the Application tab, and then select SimpleDataApp.Navigation in the Startup form list.

Create auto-generated event handlers

Double-click the three buttons on the Navigation form to create empty event handler methods. Double-clicking the buttons also adds auto-generated code in the Designer code file that enables a button click to raise an event.

Add code for the Navigation form logic

In the code page for the Navigation form, complete the method bodies for the three-button click event handlers as shown in the following code.

C#Copy

/// <summary>

/// Opens the NewCustomer form as a dialog box,

/// which returns focus to the calling form when it is closed.

/// </summary>

private void btnGoToAdd_Click(object sender, EventArgs e)

{

Form frm = new NewCustomer(); frm.Show();

}

/// <summary>

/// Opens the FillorCancel form as a dialog box.

/// </summary>

private void btnGoToFillOrCancel_Click(object sender, EventArgs e)

{

Form frm = new FillOrCancel(); frm.ShowDialog();

}

/// <summary>

/// Closes the application (not just the Navigation form).

/// </summary>

private void btnExit_Click(object sender, EventArgs e)

{

this.Close();

}

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 customer ID. You can then place an order for the new account by specifying an amount and an order date and selecting the Place Order button.

Create auto-generated event handlers

Create an empty Click event handler for each button on the NewCustomer form by double- clicking on each of the four buttons. Double-clicking the buttons also adds auto-generated code in the Designer code file that enables a button click to raise an event.

Add code for the NewCustomer form logic

 

To complete the NewCustomer form logic, follow these steps.

 

  1. Bring the Data.SqlClient namespace into scope so that you don't have to fully qualify the names of its members.

C#Copy

using System.Data.SqlClient;

  1. Add some variables and helper methods to the class as shown in the following

C#Copy

// Storage for IDENTITY values returned from database. private int parsedCustomerID;

private int orderID;

/// <summary>

/// Verifies that the customer name text box is not empty.

/// </summary>

private bool IsCustomerNameValid()

{

if (txtCustomerName.Text == "")

{

MessageBox.Show("Please enter a name."); return false;

}

else

{

return true;

}

}

/// <summary>

/// Verifies that a customer ID and order amount have been provided.

/// </summary>

private bool IsOrderDataValid()

{

// Verify that CustomerID is present. if (txtCustomerID.Text == "")

{

MessageBox.Show("Please create customer account before placing order."); return false;

}

// Verify that Amount isn't 0.

else if ((numOrderAmount.Value < 1))

{

MessageBox.Show("Please specify an order amount."); return false;

}

else

{

// Order can be submitted. return true;

}

}

 

/// <summary>

/// Clears the form data.

/// </summary>

private void ClearForm()

{

txtCustomerName.Clear(); txtCustomerID.Clear(); dtpOrderDate.Value = DateTime.Now; numOrderAmount.Value = 0;

this.parsedCustomerID = 0;

}

  1. Complete the method bodies for the four button click event handlers as shown in the following

C#Copy

/// <summary>

/// Creates a new customer by calling the Sales.uspNewCustomer stored procedure.

/// </summary>

private void btnCreateAccount_Click(object sender, EventArgs e)

{

if (IsCustomerNameValid())

{

// Create the connection.

using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString))

{

// Create a SqlCommand, and identify it as a stored procedure. using (SqlCommand sqlCommand = new

SqlCommand("Sales.uspNewCustomer", connection))

{

sqlCommand.CommandType = CommandType.StoredProcedure;

// Add input parameter for the stored procedure and specify what to use as its

value.

sqlCommand.Parameters.Add(new SqlParameter("@CustomerName", SqlDbType.NVarChar, 40));

sqlCommand.Parameters["@CustomerName"].Value = txtCustomerName.Text;

// Add the output parameter.

sqlCommand.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.Int));

sqlCommand.Parameters["@CustomerID"].Direction = ParameterDirection.Output;

try

{

connection.Open();

// Run the stored procedure. sqlCommand.ExecuteNonQuery();

// Customer ID is an IDENTITY value from the database. this.parsedCustomerID =

(int)sqlCommand.Parameters["@CustomerID"].Value;

// Put the Customer ID value into the read-only text box. this.txtCustomerID.Text = Convert.ToString(parsedCustomerID);

}

catch

{

MessageBox.Show("Customer ID was not returned. Account could not be

created.");

}

finally

{

connection.Close();

}

}

}

}

}

 

/// <summary>

/// Calls the Sales.uspPlaceNewOrder stored procedure to place an order.

/// </summary>

private void btnPlaceOrder_Click(object sender, EventArgs e)

{

// Ensure the required input is present. if (IsOrderDataValid())

{

// Create the connection.

using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString))

{

// Create SqlCommand and identify it as a stored procedure. using (SqlCommand sqlCommand = new

SqlCommand("Sales.uspPlaceNewOrder", connection))

{

sqlCommand.CommandType = CommandType.StoredProcedure;

// Add the @CustomerID input parameter, which was obtained from uspNewCustomer.

sqlCommand.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.Int));

sqlCommand.Parameters["@CustomerID"].Value = this.parsedCustomerID;

// Add the @OrderDate input parameter. sqlCommand.Parameters.Add(new SqlParameter("@OrderDate",

SqlDbType.DateTime, 8));

sqlCommand.Parameters["@OrderDate"].Value = dtpOrderDate.Value;

// Add the @Amount order amount input parameter. sqlCommand.Parameters.Add(new SqlParameter("@Amount",

SqlDbType.Int));

sqlCommand.Parameters["@Amount"].Value = numOrderAmount.Value;

// Add the @Status order status input parameter.

// For a new order, the status is always O (open). sqlCommand.Parameters.Add(new SqlParameter("@Status",

SqlDbType.Char, 1));

sqlCommand.Parameters["@Status"].Value = "O";

// Add the return value for the stored procedure, which is the order ID. sqlCommand.Parameters.Add(new SqlParameter("@RC", SqlDbType.Int)); sqlCommand.Parameters["@RC"].Direction =

ParameterDirection.ReturnValue;

try

{

//Open connection. connection.Open();

// Run the stored procedure. sqlCommand.ExecuteNonQuery();

// Display the order number.

this.orderID = (int)sqlCommand.Parameters["@RC"].Value;

MessageBox.Show("Order number " + this.orderID + " has been submitted.");

}

catch

{

MessageBox.Show("Order could not be placed.");

}

finally

{

connection.Close();

}

}

}

}

}

 

/// <summary>

/// Clears the form data so another new account can be created.

/// </summary>

private void btnAddAnotherAccount_Click(object sender, EventArgs e)

{

this.ClearForm();

}

 

/// <summary>

/// Closes the form/dialog box.

/// </summary>

private void btnAddFinish_Click(object sender, EventArgs e)

{

this.Close();

}

FillOrCancel form

The FillOrCancel form runs a query to return an order when you enter an order ID and then click 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 auto-generated event handlers

Create empty Click event handlers for the four buttons on the FillOrCancel form by double-clicking the buttons. Double-clicking the buttons also adds auto-generated code in the Designer code file that enables a button click to raise an event.

Add code for the FillOrCancel form logic

To complete the FillOrCancel form logic, follow these steps.

  1. Bring the following two namespaces into scope so that you don't have to fully qualify the names of their members.

C#Copy

using System.Data.SqlClient;

using System.Text.RegularExpressions;

  1. Add a variable and helper method to the class as shown in the following

C#Copy

// Storage for the order ID value. private int parsedOrderID;

/// <summary>

/// Verifies that an order ID is present and contains valid characters.

/// </summary>

private bool IsOrderIDValid()

{

// Check for input in the Order ID text box. if (txtOrderID.Text == "")

{

MessageBox.Show("Please specify the Order ID."); return false;

}

// Check for characters other than integers.

else if (Regex.IsMatch(txtOrderID.Text, @"^\D*$"))

{

// Show message and clear input.

MessageBox.Show("Customer ID must contain only numbers."); txtOrderID.Clear();

return false;

}

else

{

// Convert the text in the text box to an integer to send to the database. parsedOrderID = Int32.Parse(txtOrderID.Text);

return true;

}

}

 

  1. Complete the method bodies for the four button click event handlers as shown in the following

 

C#Copy

 

 

/// <summary>

/// Executes a t-SQL SELECT statement to obtain order data for a specified

/// order ID, then displays it in the DataGridView on the form.

/// </summary>

private void btnFindByOrderID_Click(object sender, EventArgs e)

{

if (IsOrderIDValid())

{

using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString))

{

// Define a t-SQL query string that has a parameter for orderID.

const string sql = "SELECT * FROM Sales.Orders WHERE orderID = @orderID";

 

// Create a SqlCommand object.

using (SqlCommand sqlCommand = new SqlCommand(sql, connection))

{

// Define the @orderID parameter and set its value. sqlCommand.Parameters.Add(new SqlParameter("@orderID",

SqlDbType.Int));

sqlCommand.Parameters["@orderID"].Value = parsedOrderID;

 

try

{

connection.Open();

 

// Run the query by calling ExecuteReader().

using (SqlDataReader dataReader = sqlCommand.ExecuteReader())

{

// Create a data table to hold the retrieved data. DataTable dataTable = new DataTable();

 

// Load the data from SqlDataReader into the data table. dataTable.Load(dataReader);

 

// Display the data from the data table in the data grid view. this.dgvCustomerOrders.DataSource = dataTable;

 

// Close the SqlDataReader. dataReader.Close();

}

}

catch

{

MessageBox.Show("The requested order could not be loaded into the

form.");

 

 

}

finally

{

// Close the connection. connection.Close();

}

}

}

}

}

 

/// <summary>

/// Cancels an order by calling the Sales.uspCancelOrder

/// stored procedure on the database.

/// </summary>

private void btnCancelOrder_Click(object sender, EventArgs e)

{

if (IsOrderIDValid())

{

// Create the connection.

using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString))

{

// Create the SqlCommand object and identify it as a stored procedure. using (SqlCommand sqlCommand = new

SqlCommand("Sales.uspCancelOrder", connection))

{

sqlCommand.CommandType = CommandType.StoredProcedure;

 

// Add the order ID input parameter for the stored procedure. sqlCommand.Parameters.Add(new SqlParameter("@orderID",

SqlDbType.Int));

sqlCommand.Parameters["@orderID"].Value = parsedOrderID;

 

try

{

// Open the connection. connection.Open();

 

// Run the command to execute the stored procedure. sqlCommand.ExecuteNonQuery();

}

catch

{

MessageBox.Show("The cancel operation was not completed.");

}

finally

 

 

{

// Close connection. connection.Close();

}

}

}

}

}

 

/// <summary>

/// Fills an order by calling the Sales.uspFillOrder stored

/// procedure on the database.

/// </summary>

private void btnFillOrder_Click(object sender, EventArgs e)

{

if (IsOrderIDValid())

{

// Create the connection.

using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connString))

{

// Create command and identify it as a stored procedure.

using (SqlCommand sqlCommand = new SqlCommand("Sales.uspFillOrder", connection))

{

sqlCommand.CommandType = CommandType.StoredProcedure;

 

// Add the order ID input parameter for the stored procedure. sqlCommand.Parameters.Add(new SqlParameter("@orderID",

SqlDbType.Int));

sqlCommand.Parameters["@orderID"].Value = parsedOrderID;

 

// Add the filled date input parameter for the stored procedure. sqlCommand.Parameters.Add(new SqlParameter("@FilledDate",

SqlDbType.DateTime, 8));

sqlCommand.Parameters["@FilledDate"].Value = dtpFillDate.Value;

 

try

{

connection.Open();

 

// Execute the stored procedure. sqlCommand.ExecuteNonQuery();

}

catch

{

MessageBox.Show("The fill operation was not completed.");

 

 

}

finally

{

// Close the connection. connection.Close();

}

}

}

}

}

 

/// <summary>

/// Closes the form.

/// </summary>

private void btnFinishUpdates_Click(object sender, EventArgs e)

{

this.Close();

}

 

 

0
Dipti KC
Dec 20, 2022
More related questions

Questions Bank

View all Questions