C# Asp.Net Web Form CRUD : Insert, Update, Delete and View With Sql Server Database | CodAffection

 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.Data;

using System.Configuration;


namespace CRUD_Asp.Net

{

    public partial class Contacts : System.Web.UI.Page

    {

        string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                btnDelete.Enabled = false;

                FillGridView();

                btnSave.Text = "Save";

            }

        }

        protected void btnClear_Click(object sender, EventArgs e)

        {

            Clear();

        }


        public void Clear()

        {

            hfContactID.Value = "";

            txtName.Text = txtMobile.Text = txtAddress.Text = "";

            lblSuccessMessage.Text = lblErrorMessage.Text = "";

            btnSave.Text = "";

            btnDelete.Enabled = false;

        }


        protected void btnSave_Click(object sender, EventArgs e)

        {  

            try

            {

                using(SqlConnection sqlCon = new SqlConnection(cs))

                {

                    if (sqlCon.State == ConnectionState.Closed)

                    {

                        sqlCon.Open();

                        SqlCommand sqlCmd = new SqlCommand("ContactCreateOrUpdate", sqlCon);

                        sqlCmd.CommandType = CommandType.StoredProcedure;

                        sqlCmd.Parameters.AddWithValue("@ContactID", (hfContactID.Value == "" ? 0 : Convert.ToInt32(hfContactID.Value)));

                        sqlCmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());

                        sqlCmd.Parameters.AddWithValue("@Mobile", txtMobile.Text.Trim());

                        sqlCmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());

                        sqlCmd.ExecuteNonQuery();

                        sqlCon.Close();

                        string contactID = hfContactID.Value;

                        Clear();

                        if (contactID == "")

                        {

                            lblSuccessMessage.Text = "Saved Successfully";

                        }

                        else

                        {

                            lblSuccessMessage.Text = "Updated Successfully";

                        }

                        FillGridView();

                    }

                }     

            }

            catch (Exception ex)

            {

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

            }

        }


        void FillGridView()

        {   

            try

            {

                using (SqlConnection sqlCon = new SqlConnection(cs))

                {

                    if (sqlCon.State == ConnectionState.Closed)

                    {

                        sqlCon.Open();

                        SqlDataAdapter sqlDa = new SqlDataAdapter("ContactViewAll",sqlCon);

                        sqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;

                        DataTable dtbl = new DataTable();

                        sqlDa.Fill(dtbl);

                        sqlCon.Close();

                        gvContact.DataSource = dtbl;

                        gvContact.DataBind();

                    }

                }

            }

            catch (Exception ex)

            {

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

            }

        }


        protected void lnk_OnClick(object sender, EventArgs e)

        {

            int ContactID = Convert.ToInt32((sender as LinkButton).CommandArgument);

            try

            {

                using (SqlConnection sqlCon = new SqlConnection(cs))

                {

                    if (sqlCon.State == ConnectionState.Closed)

                    {

                        sqlCon.Open();

                        SqlDataAdapter sqlDa = new SqlDataAdapter("ContactViewByID", sqlCon);

                        sqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;

                        sqlDa.SelectCommand.Parameters.AddWithValue("@ContactID",ContactID);

                        DataTable dtbl = new DataTable();

                        sqlDa.Fill(dtbl);

                        sqlCon.Close();

                        hfContactID.Value = ContactID.ToString();

                        txtName.Text = dtbl.Rows[0]["Name"].ToString();

                        txtMobile.Text = dtbl.Rows[0]["Mobile"].ToString();

                        txtAddress.Text = dtbl.Rows[0]["Address"].ToString();

                        btnSave.Text = "Update";

                        btnDelete.Enabled = true;

                    }

                }

            }

            catch (Exception ex)

            {

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

            }

        }


        protected void btnDelete_Click(object sender, EventArgs e)

        {

            try

            {

                using(SqlConnection sqlCon = new SqlConnection(cs))

                {

                    if (sqlCon.State == ConnectionState.Closed)

                    {

                        sqlCon.Open();

                        SqlCommand sqlCmd = new SqlCommand("ContactDeleteByID", sqlCon);

                        sqlCmd.CommandType = CommandType.StoredProcedure;

                        sqlCmd.Parameters.AddWithValue("@ContactID", Convert.ToInt32(hfContactID.Value));

                        sqlCmd.ExecuteNonQuery();

                        Clear();

                        FillGridView();

                        lblSuccessMessage.Text = "Deleted Successfully";


                    }

                }

            }

            catch (Exception ex)

            {

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

            }

        }

    }

}

Above File is CCRUD_Asp.Net\Contacts.aspx.cs











<%@ Page EnableViewState="true" Language="C#" AutoEventWireup="true" CodeBehind="Contacts.aspx.cs" Inherits="CRUD_Asp.Net.Contacts" %>


<!DOCTYPE html>


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

<head runat="server">

    <title></title>

</head>

<body>

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

        <div>

            <asp:HiddenField ID="hfContactID" runat="server"/>

            <table>

                <tr>

                    <td>

                        <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>

                    </td>

                    <td colspan="2">

                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>

                        <asp:Label ID="Label2" runat="server" Text="Mobile"></asp:Label>

                    </td>

                    <td colspan="2">

                        <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>

                        <asp:Label ID="Label3" runat="server" Text="Address"></asp:Label>

                    </td>

                    <td colspan="2">

                        <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>&nbsp;</td>

                    <td colspan="2">

                        <asp:Button ID="btnSave" runat="server" Text="Save" EnableViewState="true" OnClick="btnSave_Click"/>

                        &nbsp;<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click"/>

                        &nbsp;<asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click"/>

                    </td>

                </tr>

                <tr>

                    <td></td>

                    <td colspan="2">

                        <asp:Label ID="lblSuccessMessage" runat="server" Text="" ForeColor="Green"></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td></td>

                    <td colspan="2">

                        <asp:Label ID="lblErrorMessage" runat="server" Text="" ForeColor="Red"></asp:Label>

                    </td>

                </tr>

            </table>

            <br/>

            <asp:GridView ID="gvContact" runat="server" AutoGenerateColumns="false">

                <Columns>

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

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

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

                    <asp:TemplateField>

                        <ItemTemplate>

                            <asp:LinkButton ID="lnkView" runat="server" CommandArgument='<%# Eval("ContactID") %>' OnClick="lnk_OnClick">View</asp:LinkButton>

                        </ItemTemplate>

                    </asp:TemplateField>

                </Columns>

            </asp:GridView>

        </div>

    </form>

</body>

</html>

Above File is CRUD_Asp.Net\Contacts.aspx

















<?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=HEER\SQLEXPRESS;Initial Catalog=ASPCRUD;Integrated Security=True;Encrypt=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Above File is CRUD_Asp.Net\Web.config












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