CRUD App in ASP.NET - How to Insert, Update, Delete and Read in ASP using SQL Server DB & Bootstrap

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="crud.aspx.cs" Inherits="CRUDApp_Bootstrap.crud" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"/>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>

    <style>

        .bgColor{

            background:#99b4d1;

        }

    </style>

</head>

<body>

    <div class="container text-center">

      <div class="row">

        <div class="col">

        </div>

        <div class="col-lg-5 bgColor rounded">

            <div class="bg-primary p-4 mb-3 mt-3">

                <h1 class="text-light text-center">CRUD Application</h1>

            </div>

          <form runat="server" method="post">

              <asp:GridView ID="GridView1" CssClass="table table-dark" runat="server"></asp:GridView>

              <div class="mb-3">

                <asp:TextBox ID="txtID" CssClass="form-control" placeholder="ID" runat="server"></asp:TextBox>

              </div>

              <div class="mb-3">

                <asp:TextBox ID="txtName" CssClass="form-control" placeholder="Name" runat="server"></asp:TextBox>

              </div>

              <div class="mb-3">

                <asp:TextBox ID="txtEmail" TextMode="Email" CssClass="form-control" placeholder="run@random.com" runat="server"></asp:TextBox>

              </div>

              <div class="mb-3">

                <asp:TextBox ID="txtUser" CssClass="form-control" placeholder="Username" runat="server"></asp:TextBox>

              </div>

              <div class="mb-3">

                <asp:TextBox ID="txtPass" CssClass="form-control" TextMode="Password" placeholder="Password" runat="server"></asp:TextBox>

              </div>

              <div class="d-grid gap-2 d-md-block mb-3">

                  <asp:HyperLink ID="HyperLink1" CssClass="btn btn-secondary" href="crud.aspx" runat="server">Home</asp:HyperLink>

                  <asp:Button ID="Button1" CssClass="btn btn-primary" runat="server" Text="Create" OnClick="Button1_Click"/>

                  <asp:Button ID="Button2" CssClass="btn btn-success" runat="server" Text="Read" OnClick="Button2_Click"/>

                  <asp:Button ID="Button3" CssClass="btn btn-warning" runat="server" Text="Update" OnClick="Button3_Click"/>

                  <asp:Button ID="Button4" CssClass="btn btn-danger" runat="server" Text="Delete" OnClick="Button4_Click" OnClientClick="return confirm('Are you sure to delete data ?')"/>

              </div>

          </form>

        </div>

        <div class="col">

        </div>

      </div>

     </div>

</body>

</html>

ABOVE FILE IS crud.aspx

















using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Antlr.Runtime;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Policy;

namespace CRUDApp_Bootstrap
{
    public partial class crud : System.Web.UI.Page
    {
        string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.Visible = false;
        }

        private void HideControls(Control control)
        {
            foreach (Control ctrl in control.Controls)
            {
                if (ctrl is TextBox)
                {
                    ctrl.Visible = false;
                }
                else if (ctrl is GridView)
                {
                    ctrl.Visible = true;
                }
                else if (ctrl.HasControls())
                {
                    HideControls(ctrl);
                }
                else
                {
                    ctrl.Visible = true;
                }
            }
        }

        protected void EmptyControls()
        {
            txtID.Text = "";
            txtName.Text = "";
            txtEmail.Text = "";
            txtUser.Text = "";
            txtPass.Text = "";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (txtName.Text == "" || txtEmail.Text == "" || txtUser.Text == "" || txtPass.Text == "")
            {
                Response.Write("<script type='text/javascript'>alert('All fields are required, please fill all fields !!')</script>");
            }
            else
            {
                try
                {
                    if (!Page.IsValid)
                    {
                        return;
                    }
                    using (SqlConnection con = new SqlConnection(cs))
                    {
                        con.Open();
                        string query = "INSERT INTO aspcrud(name,email,username,password) VALUES(@name,@email,@username,@password)";
                        SqlCommand cmd = new SqlCommand(query, con);
                        cmd.Parameters.AddWithValue("@name", txtName.Text);
                        cmd.Parameters.AddWithValue("@email", txtEmail.Text);
                        cmd.Parameters.AddWithValue("@username", txtUser.Text);
                        cmd.Parameters.AddWithValue("@password", txtPass.Text);
                        int a = cmd.ExecuteNonQuery();
                        if (a > 0)
                        {
                            Response.Write("<script type='text/javascript'>alert('Successfully Inserted !!')</script>");
                            EmptyControls();
                        }
                        else
                        {
                            Response.Write("<script type='text/javascript'>alert('Insertion Failed !!')</script>");
                        }
                    }
                }
                catch (SqlException ex)
                {
                    Response.Write("SqlException : " + ex.Message);
                }
                catch (Exception ex)
                {
                    Response.Write("Exception : " + ex.Message);
                }
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(cs))
                {
                //If your GridView is only for displaying data, use SqlDataReader because it is faster and more memory efficient
                //If you need to manipulate, filter, or edit the data, use SqlDataAdapter with DataTable.
                //Pros:
                //✔ Fastest Read Performance – SqlDataReader reads one row at a time, making it faster and more efficient than DataTable for large datasets.
                //✔ Lower Memory Usage – Since it processes one row at a time, it doesn’t store the entire result set in memory.
                //✔ Ideal for Read - Only Data – Best for scenarios where you just need to display data without modifications.


                    HideControls(this);
                    con.Open();
                    string query = "SELECT * FROM aspcrud";
                    SqlCommand cmd = new SqlCommand(query, con);
                    SqlDataReader reader = cmd.ExecuteReader();
                    GridView1.DataSource = reader;
                    GridView1.DataBind();
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException : " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception : " + ex.Message);
            }
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            if (txtID.Text == "" || txtName.Text == "" || txtEmail.Text == "" || txtUser.Text == "" || txtPass.Text == "")
            {
                Response.Write("<script type='text/javascript'>alert('All fields are required to update the data !!')</script>");
            }
            else
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(cs))
                    {
                        con.Open();
                        string query = "UPDATE aspcrud SET name=@name,email=@email,username=@username,password=@password WHERE id=@id";
                        SqlCommand cmd = new SqlCommand(query, con);
                        cmd.Parameters.AddWithValue("@name", txtName.Text);
                        cmd.Parameters.AddWithValue("@email", txtEmail.Text);
                        cmd.Parameters.AddWithValue("@username", txtUser.Text);
                        cmd.Parameters.AddWithValue("@password", txtPass.Text);
                        cmd.Parameters.AddWithValue("@id", txtID.Text);
                        int a = cmd.ExecuteNonQuery();
                        if (a > 0)
                        {
                            Response.Write("<script type='text/javascript'>alert('Successfully Updated !!')</script>");
                            EmptyControls();
                        }
                        else
                        {
                            Response.Write("<script type='text/javascript'>alert('Updation Failed !!')</script>");
                        }
                    }
                }
                catch (SqlException ex)
                {
                    Response.Write("SqlException : " + ex.Message);
                }
                catch (Exception ex)
                {
                    Response.Write("Exception : " + ex.Message);
                }
            }
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            if (txtID.Text == "")
            {
                Response.Write("<script type='text/javascript'>alert('ID is required to delete data !!')</script>");
            }
            else
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(cs))
                    {
                        con.Open();
                        string query = "DELETE FROM aspcrud WHERE id=@id";
                        SqlCommand cmd = new SqlCommand(query, con);
                        cmd.Parameters.AddWithValue("@id",txtID.Text);
                        int a = cmd.ExecuteNonQuery();
                        if (a > 0)
                        {
                            Response.Write("<script type='text/javascript'>alert('Deleted Successfully !!')</script>");
                            EmptyControls();
                        }
                        else
                        {
                            Response.Write("<script type='text/javascript'>alert('Deletion Failed !!')</script>");
                        }
                    }
                }
                catch (SqlException ex)
                {
                    Response.Write("SqlException : " + ex.Message);
                }
                catch (Exception ex)
                {
                    Response.Write("Exception : " + ex.Message);
                }
            }
        }
    }
}
ABOVE FILE IS crud.aspx.cs
















<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Web.Infrastructure" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
<connectionStrings>
<add name="dbcs" connectionString="Data Source=DESKTOP-77M6N4G\SQLEXPRESS;Initial Catalog=aspcrud;Integrated Security=True;TrustServerCertificate=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
ABOVE FILE IS Web.config

















CREATE DATABASE aspcrud;

USE aspcrud;

CREATE TABLE aspcrud(
id INT NOT NULL PRIMARY KEY IDENTITY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
);

SELECT * FROM aspcrud;











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