Introduction
In this article, we will learn how to perform CRUD (Create, Read, Update and Delete) operations using ADO.NET in ASP.NET Web Forms with .NET Framework 4.8 and SQL Server.
We will create a simple Employee Management System where users can add, view, update and delete employee records without using Entity Framework.
ADO.NET allows us to communicate directly with the database using classes such as SqlConnection, SqlCommand, SqlDataAdapter and SqlDataReader.
Prerequisites
Visual Studio
.NET Framework 4.8
SQL Server
SQL Server Management Studio (SSMS)
Basic knowledge of C#, SQL and ASP.NET Web Forms
Application architecture
We will separate the database operations from the presentation layer to make our application easier to maintain.
Presentation Layer
Employee.aspx
Code Behind
Employee.aspx.cs
Data Access Layer
EmployeeDAL.cs
SQL Server Database
EmployeeDB
Step 1: Create a database and table
Open SQL Server Management Studio and execute the following SQL script.
CREATE DATABASE EmployeeDB;
GO
USE EmployeeDB;
GO
CREATE TABLE Employee
(
Id INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(100) NOT NULL,
Email NVARCHAR(100) NOT NULL,
Department NVARCHAR(100) NOT NULL,
Salary DECIMAL(18,2) NOT NULL
);Insert some sample records into the Employee table.
INSERT INTO Employee
(Name, Email, Department, Salary)
VALUES
('Rahul', '[email protected]', 'IT', 35000),
('Amit', '[email protected]', 'HR', 30000),
('Priya', '[email protected]', 'Finance', 40000);Step 2: Create an ASP.NET Web Forms project
Open Visual Studio and follow these steps:
Click on Create a new project.
Select ASP.NET Web Application (.NET Framework).
Enter the project name
CrudUsingADONET.Select .NET Framework 4.8.
Select the Web Forms template.
Click on Create.
After creating the project, add two folders named Models and DAL.
The project structure will look like this:
CrudUsingADONET
Models
Employee.cs
DAL
EmployeeDAL.cs
Employee.aspx
Employee.aspx.cs
Employee.aspx.designer.cs
Web.config
Step 3: Configure the connection string
Open the Web.config file and add the connection string inside the configuration section.
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=.;
Initial Catalog=EmployeeDB;
Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>Replace Data Source with your SQL Server instance name.
We will use this connection string in our Data Access Layer to establish a connection with SQL Server.
Step 4: Create the Employee model
Create a class named Employee.cs inside the Models folder.
Employee.cs
namespace CrudUsingADONET.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Department { get; set; }
public decimal Salary { get; set; }
}
}This model represents the Employee table and is used to transfer employee data between the presentation layer and the data access layer.
Step 5: Create the Data Access Layer
Create a class named EmployeeDAL.cs inside the DAL folder.
We will write all database operations inside this class using ADO.NET.
EmployeeDAL.cs
using CrudUsingADONET.Models;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace CrudUsingADONET.DAL
{
public class EmployeeDAL
{
private readonly string _conStr =
ConfigurationManager.ConnectionStrings[
"DefaultConnection"].ConnectionString;
// Get All Employees
public DataTable GetAllEmployees()
{
using (SqlConnection con =
new SqlConnection(_conStr))
{
string query = "SELECT * FROM Employee";
using (SqlCommand cmd =
new SqlCommand(query, con))
{
using (SqlDataAdapter da =
new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
}
// Get Employee By Id
public Employee GetEmployeeById(int id)
{
using (SqlConnection con =
new SqlConnection(_conStr))
{
string query =
"SELECT * FROM Employee WHERE Id = @Id";
using (SqlCommand cmd =
new SqlCommand(query, con))
{
cmd.Parameters.Add("@Id",
SqlDbType.Int).Value = id;
con.Open();
using (SqlDataReader dr =
cmd.ExecuteReader())
{
if (dr.Read())
{
return new Employee
{
Id = (int)dr["Id"],
Name = dr["Name"].ToString(),
Email = dr["Email"].ToString(),
Department =
dr["Department"].ToString(),
Salary = (decimal)dr["Salary"]
};
}
}
}
}
return null;
}
// Insert Employee
public int InsertEmployee(Employee emp)
{
using (SqlConnection con =
new SqlConnection(_conStr))
{
string query = @"INSERT INTO Employee
(Name, Email, Department, Salary)
VALUES
(@Name, @Email, @Department, @Salary)";
using (SqlCommand cmd =
new SqlCommand(query, con))
{
AddEmployeeParameters(cmd, emp);
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
// Update Employee
public int UpdateEmployee(Employee emp)
{
using (SqlConnection con =
new SqlConnection(_conStr))
{
string query = @"UPDATE Employee SET
Name = @Name,
Email = @Email,
Department = @Department,
Salary = @Salary
WHERE Id = @Id";
using (SqlCommand cmd =
new SqlCommand(query, con))
{
cmd.Parameters.Add("@Id",
SqlDbType.Int).Value = emp.Id;
AddEmployeeParameters(cmd, emp);
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
// Delete Employee
public int DeleteEmployee(int id)
{
using (SqlConnection con =
new SqlConnection(_conStr))
{
string query =
"DELETE FROM Employee WHERE Id = @Id";
using (SqlCommand cmd =
new SqlCommand(query, con))
{
cmd.Parameters.Add("@Id",
SqlDbType.Int).Value = id;
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
// Common Parameters
private void AddEmployeeParameters(
SqlCommand cmd, Employee emp)
{
cmd.Parameters.Add("@Name",
SqlDbType.NVarChar, 100).Value = emp.Name;
cmd.Parameters.Add("@Email",
SqlDbType.NVarChar, 100).Value = emp.Email;
cmd.Parameters.Add("@Department",
SqlDbType.NVarChar, 100).Value = emp.Department;
SqlParameter salary = cmd.Parameters.Add(
"@Salary", SqlDbType.Decimal);
salary.Precision = 18;
salary.Scale = 2;
salary.Value = emp.Salary;
}
}
}In the above code, we have created five methods to perform database operations.
Method | Purpose |
|---|---|
GetAllEmployees() | Retrieve all employees |
GetEmployeeById() | Retrieve a particular employee |
InsertEmployee() | Insert a new employee |
UpdateEmployee() | Update an existing employee |
DeleteEmployee() | Delete an employee |
We are using parameterized queries to prevent SQL injection and using blocks to ensure that database resources are properly disposed of.
Step 6: Design the Web Form
Add a new Web Form named Employee.aspx to the project.
We will use TextBox controls to enter employee details, Button controls to perform operations and a GridView control to display employee records.
Employee.aspx
Join the conversation! Your thoughts help the community grow.