Complete CRUD Operation in Asp.Net C# with SQL Using Stored Procedure with Validation(Best CRUD for Practice)

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


<!DOCTYPE html>


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

<head runat="server">

    <title></title>

    

    <style type="text/css">

        .auto-style1 {

            width: 100%;

        }

        .auto-style2 {

            height: 23px;

        }

        .auto-style3 {

            width: 85px;

        }

        .auto-style4 {

            height: 23px;

            width: 85px;

        }

    </style>

    

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <table class="auto-style1">

                <tr>

                    <td colspan="2" style="font-family:Arial,Helvetica,sans-serif; font-size:x-large; font-weight:bold; color:#333333">Complete CRUD Operation in Asp.Net C# with SQL Using Stored Procedure with Validation</td>

                </tr>

                <tr>

                    <td class="auto-style3">&nbsp;</td>

                    <td></td>

                </tr>

                <tr>

                    <td class="auto-style3">

                        <asp:Label ID="Label1" runat="server" Text="Product ID" Font-Size="Medium"></asp:Label>

                    </td>

                    <td>

                        <asp:TextBox ID="TextBox1" runat="server" Font-Size="Medium" Width="200px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please Enter Product ID" ForeColor="Red" Text="*" ControlToValidate="TextBox1" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>

                        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please Enter Product ID" ForeColor="Red" Text="*" ControlToValidate="TextBox1" SetFocusOnError="true" Display="Dynamic"></asp:CustomValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style3">

                        <asp:Label ID="Label2" runat="server" Text="Item Name" Font-Size="Medium"></asp:Label>

                    </td>

                    <td>

                        <asp:TextBox ID="TextBox2" runat="server" Font-Size="Medium" Width="200px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Enter Item Name" ForeColor="Red" Text="*" ControlToValidate="TextBox2" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>

                        <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="Please Enter Item Name" ForeColor="Red" Text="*" ControlToValidate="TextBox2" SetFocusOnError="true" Display="Dynamic"></asp:CustomValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style3">

                        <asp:Label ID="Label3" runat="server" Text="Specification" Font-Size="Medium"></asp:Label>

                    </td>

                    <td>

                        <asp:TextBox ID="TextBox3" runat="server" Font-Size="Medium" Width="200px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please Enter Specification" ForeColor="Red" Text="*" ControlToValidate="TextBox3" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>

                        <asp:CustomValidator ID="CustomValidator3" runat="server" ErrorMessage="Please Enter Specification" ForeColor="Red" Text="*" ControlToValidate="TextBox3" SetFocusOnError="true" Display="Dynamic"></asp:CustomValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style4">

                        <asp:Label ID="Label4" runat="server" Text="Unit" Font-Size="Medium"></asp:Label>

                    </td>

                    <td class="auto-style2">

                        <asp:DropDownList ID="DropDownList1" runat="server" Font-Size="Medium" Width="200px">

                            <asp:ListItem Text="-- Select --" Value="" Selected="True"></asp:ListItem>

                            <asp:ListItem>PCS</asp:ListItem>

                            <asp:ListItem>KG</asp:ListItem>

                            <asp:ListItem>DZ</asp:ListItem>

                            <asp:ListItem>Ltr</asp:ListItem>

                        </asp:DropDownList>

                        <asp:CustomValidator ID="CustomValidator4" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Please Select Unit" ForeColor="Red" Text="*" SetFocusOnError="true" Display="Dynamic" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

                        <asp:Label ID="lblMessage" runat="server"></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style3">

                        <asp:Label ID="Label5" runat="server" Text="Status" Font-Size="Medium"></asp:Label>

                    </td>

                    <td>

                        <asp:RadioButtonList ID="RadioButtonList1" runat="server" Font-Size="Medium" Width="200px" RepeatDirection="Horizontal">

                            <asp:ListItem Value="Running">Running</asp:ListItem>

                            <asp:ListItem Value="Unused">Unused</asp:ListItem>

                        </asp:RadioButtonList>

                        <asp:CustomValidator ID="CustomValidator5" runat="server" ErrorMessage="Please select status" Display="Dynamic" ForeColor="Red" Text="*" ControlToValidate="RadioButtonList1" SetFocusOnError="true" OnServerValidate="CustomValidator2_ServerValidate"></asp:CustomValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style3">

                        <asp:Label ID="Label6" runat="server" Text="Creation Date" Font-Size="Medium"></asp:Label>

                    </td>

                    <td>

                        <asp:TextBox ID="TextBox4" runat="server" Font-Size="Medium" Width="200px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Please Enter Creation Date" ForeColor="Red" Text="*" ControlToValidate="TextBox4" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>

                        <asp:CustomValidator ID="CustomValidator6" runat="server" ErrorMessage="Please Enter Creation Date" ForeColor="Red" Text="*" ControlToValidate="TextBox4" SetFocusOnError="true" Display="Dynamic"></asp:CustomValidator>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style3">&nbsp;</td>

                    <td>&nbsp;</td>

                </tr>

                <tr>

                    <td class="auto-style3">&nbsp;</td>

                    <td>

                        <asp:Button ID="Button1" runat="server" Font-Size="Large" Text="Insert" ForeColor="White" BackColor="#6600CC" OnClick="Button1_Click"/>

                        &nbsp;&nbsp;<asp:Button ID="Button2" runat="server" Font-Size="Large" Text="Update" ForeColor="White" BackColor="#6600CC" OnClick="Button2_Click"/>

                        &nbsp;&nbsp;<asp:Button ID="Button3" runat="server" Font-Size="Large" Text="Delete" ForeColor="White" BackColor="#6600CC" OnClick="Button3_Click" OnClientClick="return confirm('Are you sure to delete ?')"/>

                        &nbsp;&nbsp;<asp:Button ID="Button4" runat="server" Font-Size="Large" Text="Search" ForeColor="White" BackColor="#6600CC" OnClick="Button4_Click" CausesValidation="false"/>

                        &nbsp;&nbsp;<asp:Button ID="Button5" runat="server" Font-Size="Large" Text="Load" ForeColor="White" BackColor="#6600CC" OnClick="Button5_Click" CausesValidation="false"/>

                        &nbsp;&nbsp;<asp:Button ID="Button6" runat="server" Font-Size="Large" Text="Get" ForeColor="White" BackColor="#6600CC" OnClick="Button6_Click" CausesValidation="false"/>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style3">&nbsp;</td>

                    <td>

                        &nbsp;</td>

                </tr>

                <tr>

                    <td colspan="2">

                        <asp:GridView ID="GridView1" runat="server" Width="885px">

                            <HeaderStyle BackColor="#6600CC" ForeColor="White"/>

                        </asp:GridView>

                    </td>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

Above File is CRUD_ASP_SP\WebForm1.aspx




















using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Globalization;

namespace CRUD_ASP_SP
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetProductList();
            }
        }

        void EmptyFieldData()
        {
            TextBox1.Text = "";
            TextBox2.Text = "";
            TextBox3.Text = "";
            DropDownList1.SelectedValue = "";
            RadioButtonList1.SelectedValue = "";
            TextBox4.Text = "";
        }

        void GetProductList()
        {
            try
            {
                using (SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("ProductList_SP",con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.ToString());
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsValid)
                {
                    return;
                }

                if (DropDownList1.SelectedValue == "")
                {
                    lblMessage.Text = "Please select a Unit";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    return;
                }
                lblMessage.Text = "Unit Selected: " + DropDownList1.SelectedItem.Text;
                lblMessage.ForeColor = System.Drawing.Color.Green;

                using (SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("ProductSetup_SP",con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@ProductID",int.Parse(TextBox1.Text));
                    cmd.Parameters.AddWithValue("@ItemName",TextBox2.Text);
                    cmd.Parameters.AddWithValue("@Specification",TextBox3.Text);
                    cmd.Parameters.AddWithValue("@Unit",DropDownList1.SelectedValue);
                    cmd.Parameters.AddWithValue("@Status",RadioButtonList1.SelectedValue);

                    DateTime parsedDate;
                    string inputDate = TextBox4.Text.Trim();

                    if (!DateTime.TryParseExact(inputDate,"dd/MM/yyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out parsedDate))
                    {
                        Response.Write("<script>alert('Invalid date format.Please use dd/MM/yyyy')</script>");
                        return;
                    }
                    cmd.Parameters.AddWithValue("@CreationDate",parsedDate);
                    cmd.ExecuteNonQuery();
                    ScriptManager.RegisterStartupScript(this,this.GetType(),"script","alert('Successfully Inserted');",true);
                    GetProductList();
                    EmptyFieldData();
                }
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.ToString());
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("ProductUpdate_SP",con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@ProductID",int.Parse(TextBox1.Text));
                    cmd.Parameters.AddWithValue("@ItemName",TextBox2.Text);
                    cmd.Parameters.AddWithValue("@Specification",TextBox3.Text);
                    cmd.Parameters.AddWithValue("@Unit",DropDownList1.SelectedValue);
                    cmd.Parameters.AddWithValue("@Status",RadioButtonList1.SelectedValue);
                    cmd.Parameters.AddWithValue("@CreationDate",DateTime.Parse(TextBox4.Text));
                    cmd.ExecuteNonQuery();
                    ScriptManager.RegisterStartupScript(this,this.GetType(),"script","alert('Successfully Updated');",true);
                    GetProductList();
                    EmptyFieldData();
                }
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.ToString());
            }
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("ProductDelete_SP",con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@ProductID",int.Parse(TextBox1.Text));
                    cmd.ExecuteNonQuery();
                    ScriptManager.RegisterStartupScript(this,this.GetType(),"script","alert('Successfully Deleted');",true);
                    GetProductList();
                    EmptyFieldData();
                }
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.ToString());
            }
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            try
            {
                using(SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("ProductSearch_SP", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@ProductID",int.Parse(TextBox1.Text));
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.ToString());
            }
        }

        protected void Button5_Click(object sender, EventArgs e)
        {
            try
            {
                GetProductList();
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.ToString());
            }
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (DropDownList1.SelectedValue == "")
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (RadioButtonList1.SelectedIndex == -1)   //No option selected
            {
                args.IsValid = false;   //Validation fails, Mark as invalid
            }
            else
            {
                args.IsValid = true;    //Validation passes, Valid selection
            }
        }

        protected void Button6_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("ProductSearch_SP",con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@ProductID",int.Parse(TextBox1.Text));
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())    //Ensure data is available
                    {
                        TextBox1.Text = dr["ProductID"].ToString();
                        TextBox2.Text = dr["ItemName"].ToString();
                        TextBox3.Text = dr["Specification"].ToString();
                        DropDownList1.SelectedValue = dr["Unit"].ToString();
                        RadioButtonList1.SelectedValue = dr["Status"].ToString();
                        TextBox4.Text = dr["CreationDate"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.ToString());
            }
        }
    }
}
Above File is CRUD_ASP_SP\WebForm1.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=MyTest_DB;Integrated Security=True;Encrypt=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Above File is CRUD_ASP_SP\Web.config




















CREATE DATABASE MyTest_DB;

USE MyTest_DB;

CREATE TABLE ProductSetup_Tab(
ProductID INT NOT NULL PRIMARY KEY,
ItemName nvarchar(50) NOT NULL,
Specification nvarchar(150) NOT NULL,
Unit nvarchar(30) NOT NULL,
Status nvarchar(30) NOT NULL,
CreationDate datetime NOT NULL
);

INSERT INTO ProductSetup_Tab(ProductID,ItemName,Specification,Unit,Status,CreationDate)
VALUES(1,'Laptop','Core i7','PCS','Running',TRY_CONVERT(DATETIME,'22/10/2022',103)),
(2,'Laptop','Core i5','PCS','Running',TRY_CONVERT(DATETIME,'05/04/2024',103)),
(3,'Mobile','Snapdragon 888','PCS','Running',TRY_CONVERT(DATETIME,'02/11/2022',103)),
(4,'Mobile','Snapdragon 732','PCS','Running',TRY_CONVERT(DATETIME,'07/05/2024',103)),
(5,'Charger','Delux','PCS','Running',TRY_CONVERT(DATETIME,'12/02/2024',103));

SELECT * FROM ProductSetup_Tab;





--CREATING STORED PROCEDURE FOR INSERTING DATA IN DATABASE TABLE
CREATE PROC ProductSetup_SP
@ProductID INT,
@ItemName nvarchar(50),
@Specification nvarchar(150),
@Unit nvarchar(30),
@Status nvarchar(30),
@CreationDate datetime
AS
BEGIN
INSERT INTO ProductSetup_Tab(ProductID,ItemName,Specification,Unit,Status,CreationDate)
VALUES(@ProductID,@ItemName,@Specification,@Unit,@Status,@CreationDate);
END

EXECUTE ProductSetup_SP 6,'Laptop','HP Core i7','PCS','Running','01/01/2021';


--CREATING STORED PROCEDURE FOR SELECTING DATA FROM DATABASE TABLE
CREATE PROC ProductList_SP
AS
BEGIN
SELECT * FROM ProductSetup_Tab;
END

EXECUTE ProductList_SP;


--CREATING STORED PROCEDURE FOR UPDATING DATA FROM DATABASE TABLE
CREATE PROC ProductUpdate_SP
@ProductID INT,
@ItemName nvarchar(50),
@Specification nvarchar(150),
@Unit nvarchar(30),
@Status nvarchar(30),
@CreationDate datetime
AS
BEGIN
UPDATE ProductSetup_Tab SET ItemName=@ItemName,Specification=@Specification,Unit=@Unit,Status=@Status,CreationDate=@CreationDate WHERE ProductID=@ProductID;
END

EXECUTE ProductUpdate_SP 2,Laptop,'HP Core i5','PCS','Running','2024-11-26';

--IF THIS ERROR:"Error converting data type varchar to datetime." is occurred then Below code can be execute for UPDATE STORED PROCEDURE
--DECLARE @ConvertedDate DATETIME;
--SET @ConvertedDate = CONVERT(DATETIME,'24/11/2024',103);
--EXECUTE ProductUpdate_SP 2,'Laptop','Core i3','PCS','Running',@ConvertedDate;



--CREATING STORED PROCEDURE FOR DELETING DATA FROM DATABASE TABLE
CREATE PROC ProductDelete_SP
@ProductID INT
AS
BEGIN
DELETE FROM ProductSetup_Tab WHERE ProductID=@ProductID;
END

--EXECUTE ProductDelete_SP 6;


--CREATING STORED PROCEDURE FOR SEARCHING DATABASE TABLE DATA
CREATE PROC ProductSearch_SP
@ProductID INT
AS
BEGIN
SELECT * FROM ProductSetup_Tab WHERE ProductID=@ProductID;
END

EXECUTE ProductSearch_SP 4;







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