crud operation in asp.net || crud in asp.net webforms || crud in c#

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;


namespace EmployeeCRUDoperations.Model

{

    public class Employee

    {

        public int Id { get; set; }

        public string EmpName { get; set; }

        public string Position { get; set; }

        public decimal Salary { get; set; }

    }

}

Above File is EmployeeCRUDoperations\Model\Employee.cs









using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.SqlClient;

using System.Data;

using System.Configuration;


namespace EmployeeCRUDoperations.Model

{

    public class EmployeeDAL

    {

        private readonly string _connectionString = ConfigurationManager.ConnectionStrings["EmpConnection"].ConnectionString;


        public List<Employee> GetEmployees()

        {

            List<Employee> employees = new List<Employee>();


            try

            {

                using (SqlConnection con = new SqlConnection(_connectionString))

                {

                    SqlCommand cmd = new SqlCommand("select * from employee", con);

                    con.Open();

                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())

                    {

                        Employee emp = new Employee

                        {

                            Id = Convert.ToInt32(reader["Id"]),

                            EmpName = reader["EmpName"].ToString(),

                            Position = reader["Position"].ToString(),

                            Salary = Convert.ToDecimal(reader["Salary"])

                        };

                        employees.Add(emp);

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Exception: " + ex.ToString());

            }

            return employees;

        }


        // Create Method

        public int AddEmp(Employee emp)

        {

            try

            {

                using (SqlConnection con = new SqlConnection(_connectionString))

                {

                    SqlCommand cmd = new SqlCommand("Insert into employee(EmpName,Position,Salary) values(@EmpName,@Position,@Salary)",con);

                    con.Open();

                    cmd.Parameters.AddWithValue("@EmpName",emp.EmpName);

                    cmd.Parameters.AddWithValue("@Position",emp.Position);

                    cmd.Parameters.AddWithValue("@Salary", emp.Salary);

                    return Convert.ToInt32(cmd.ExecuteScalar());

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Exception: " + ex.ToString());

            }

            return 0;

        }


        // Update Method

        public void UpdateEmp(Employee emp)

        {

            try

            {

                using(SqlConnection con = new SqlConnection(_connectionString))

                {

                    SqlCommand cmd = new SqlCommand("Update employee set EmpName=@EmpName,Position=@Position,Salary=@Salary where Id=@Id",con);

                    con.Open();

                    cmd.Parameters.AddWithValue("@EmpName",emp.EmpName);

                    cmd.Parameters.AddWithValue("@Position",emp.Position);

                    cmd.Parameters.AddWithValue("@Salary",emp.Salary);

                    cmd.Parameters.AddWithValue("@Id",emp.Id);


                    cmd.ExecuteNonQuery();

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Exception: " + ex.ToString());

            }

        }


        // Delete Method

        public void DeleteEmp(int empId)

        {

            try

            {

                using(SqlConnection con = new SqlConnection(_connectionString))

                {

                    SqlCommand cmd = new SqlCommand("delete from employee where Id=@Id",con);

                    con.Open();

                    cmd.Parameters.AddWithValue("@Id",empId);

                    cmd.ExecuteNonQuery();

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Exception: " + ex.ToString());

            }

        }


        // Get data by Id

        public Employee GetEmpById(int empId)

        {

            Employee emp = null;

            try

            {

                using(SqlConnection con = new SqlConnection(_connectionString))

                {

                    con.Open();

                    SqlCommand cmd = new SqlCommand("select * from employee where Id=@Id",con);

                    cmd.Parameters.AddWithValue("@Id",empId);

                    SqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())

                    {

                        emp = new Employee();

                        emp.Id = Convert.ToInt32(reader["Id"]);

                        emp.EmpName = reader["EmpName"].ToString();

                        emp.Position = reader["Position"].ToString();

                        emp.Salary = Convert.ToDecimal(reader["Salary"]);

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine("Exception: " + ex.ToString());

            }

            return emp;

        }

    }

}

Above File is EmployeeCRUDoperations\Model\EmployeeDAL.cs










<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="EmpPage.aspx.cs" Inherits="EmployeeCRUDoperations.EmpPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">


    <div class="container">

        <div class="row">

            <div class="col-md-6">

                <asp:GridView ID="GridViewEmployees" runat="server" AutoGenerateColumns="False" BackColor="#CCCCCC" BorderColor="#333333" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black">

                    <Columns>

                        <asp:BoundField DataField="Id" HeaderText="ID"/>

                        <asp:BoundField DataField="EmpName" HeaderText="EmployeeName"/>

                        <asp:BoundField DataField="Position" HeaderText="Position"/>

                        <asp:BoundField DataField="Salary" HeaderText="Salary"/>

                    </Columns>

                    <FooterStyle BackColor="#CCCCCC" />

                    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />

                    <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />

                    <RowStyle BackColor="White" />

                    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

                    <SortedAscendingCellStyle BackColor="#F1F1F1" />

                    <SortedAscendingHeaderStyle BackColor="Gray" />

                    <SortedDescendingCellStyle BackColor="#CAC9C9" />

                    <SortedDescendingHeaderStyle BackColor="#383838" />

                </asp:GridView>

            </div>

            <div class="col-md-6">

                EmployeeId:<asp:TextBox ID="txtId" runat="server" AutoPostBack="True" OnTextChanged="txtId_TextChanged" CssClass="form-control"></asp:TextBox><br/>

                EmployeeName:<asp:TextBox ID="txtEmpName" runat="server" CssClass="form-control"></asp:TextBox><br/>

                Position:<asp:TextBox ID="txtPosition" runat="server" CssClass="form-control"></asp:TextBox><br/>

                Salary:<asp:TextBox ID="txtSalary" runat="server" CssClass="form-control"></asp:TextBox><br/>

                <asp:Button ID="btnAdd" runat="server" Text="Add Employee" OnClick="btnAdd_Click" CssClass="btn btn-primary"/>

                <asp:Button ID="btnUpdate" runat="server" Text="Update Employee" OnClick="btnUpdate_Click" CssClass="btn btn-warning"/>

                <asp:Button ID="btnDelete" runat="server" Text="Delete Employee" OnClick="btnDelete_Click" CssClass="btn btn-danger"/>

            </div>

        </div>

    </div>

</asp:Content>

Above File is EmployeeCRUDoperations\EmpPage.aspx















using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EmployeeCRUDoperations.Model;

namespace EmployeeCRUDoperations
{
    public partial class EmpPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                BindView();
            }
        }

        private void BindView()
        {
            EmployeeDAL empDAL = new EmployeeDAL();

            List<Employee> employees = empDAL.GetEmployees();

            GridViewEmployees.DataSource = employees;
            GridViewEmployees.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Employee emp = new Employee
            {
                EmpName = txtEmpName.Text,
                Position = txtPosition.Text,
                Salary = Convert.ToDecimal(txtSalary.Text)
            };
            EmployeeDAL empDAL = new EmployeeDAL();
            empDAL.AddEmp(emp);
            BindView();
            Clear();
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int empId = Convert.ToInt32(txtId.Text);
            Employee emp = new Employee
            {
                Id = empId,
                EmpName = txtEmpName.Text,
                Position = txtPosition.Text,
                Salary = Convert.ToDecimal(txtSalary.Text)
            };
            EmployeeDAL empDAL = new EmployeeDAL();
            empDAL.UpdateEmp(emp);
            BindView();
            Clear();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int empId = Convert.ToInt32(txtId.Text);
            EmployeeDAL empDAL = new EmployeeDAL();
            empDAL.DeleteEmp(empId);
            BindView();
            Clear();
        }

        protected void txtId_TextChanged(object sender, EventArgs e)
        {
            int empId = Convert.ToInt32(txtId.Text);
            EmployeeDAL empDAL = new EmployeeDAL();
            Employee employee = empDAL.GetEmpById(empId);
            if (employee != null)
            {
                txtEmpName.Text = employee.EmpName;
                txtPosition.Text = employee.Position;
                txtSalary.Text = Convert.ToDecimal(employee.Salary).ToString();
                txtId.Text = Convert.ToInt32(employee.Id).ToString();
            }
            else
            {
                txtEmpName.Text = "";
                txtPosition.Text = "";
                txtSalary.Text = "";
            }
        }

        public void Clear()
        {
            txtId.Text = "";
            txtEmpName.Text = "";
            txtPosition.Text = "";
            txtSalary.Text = "";
        }
    }
}
Above File is EmployeeCRUDoperations\EmpPage.aspx.cs
















<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="EmployeeCRUDoperations.SiteMaster" %>

<!DOCTYPE html>

<html lang="en">
<head runat="server">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%: Page.Title %> - My ASP.NET Application</title>

    <asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/bundles/modernizr") %>
    </asp:PlaceHolder>

    <webopt:bundlereference runat="server" path="~/Content/css" />
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

</head>
<body>
    <form runat="server">
        <asp:ScriptManager runat="server">
            <Scripts>
                <%--To learn more about bundling scripts in ScriptManager see https://go.microsoft.com/fwlink/?LinkID=301884 --%>
                <%--Framework Scripts--%>
                <asp:ScriptReference Name="MsAjaxBundle" />
                <asp:ScriptReference Name="jquery" />
                <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
                <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
                <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
                <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
                <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
                <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
                <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
                <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
                <asp:ScriptReference Name="WebFormsBundle" />
                <%--Site Scripts--%>
            </Scripts>
        </asp:ScriptManager>

        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
            <div class="container">
                <a class="navbar-brand" runat="server" href="~/">Application name</a>
                <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item"><a class="nav-link" runat="server" href="~/">Home</a></li>
                        <li class="nav-item"><a class="nav-link" runat="server" href="~/About">About</a></li>
                        <li class="nav-item"><a class="nav-link" runat="server" href="~/Contact">Contact</a></li>
                        <li class="nav-item"><a class="nav-link" runat="server" href="~/EmpPage">EmployeeList</a></li>
                    </ul>
                </div>
            </div>
        </nav>
        <div class="container body-content">
            <asp:ContentPlaceHolder ID="MainContent" runat="server">
            </asp:ContentPlaceHolder>
            <hr />
            <footer>
                <p>&copy; <%: DateTime.Now.Year %> - My ASP.NET Application</p>
            </footer>
        </div>
    </form>
    <asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/Scripts/bootstrap.js") %>
    </asp:PlaceHolder>
</body>
</html>
Above File is EmployeeCRUDoperations\Site.Master




























Comments

Popular posts from this blog

Create a User Registration Form in ASP.NET using SQL Server, Visual Studio 2022 & Bootstrap

Create a Simple Login Form in ASP.NET using Visual Studio 2022

SqlCommand Class ADO.Net | ExecuteNonQuery | ExecuteReader | ExecuteScalar