CRUD Operation in ASP NET MVC With Source Code

CRUD Operation in ASP NET MVC With Source Code

CRUD Operation in ASP NET is an abbreviation for Create, Read, Update, and Delete. These are the four most fundamental operations that most traditional database systems can execute, and they provide the foundation for interacting with any database.

CRUD Operation In ASP.NET Core MVC : About the project

This 2022 article, you will learn on How To Create CRUD Operation In ASP.NET MVC, This CRUD Application In ASP.NET was developed using ASP.NET and SQL Server as the system’s Back-End.

CRUD Operation In ASP.NET Core : Project Details and Technology

Project Title: CRUD Operation Project In ASP.NET
Abstract :CRUD Operation in ASP NET is an abbreviation for Create, Read, Update, and Delete.
Project Type:Website
Technology :ASP.Net Visual Studio 2022 with C# Language
Database :SQL-Server 2021
CRUD Operation Project In ASP.NET – Project Details

To start creating this CRUD Operation in ASP.NET make sure that you have a Microsoft Visual Studio and SQL Server installed in your computer.

How To Create CRUD Operation In ASP.NET MVC?

On this part of tutorial we want to set up first the SQL Server for creating a database as the system’s back-end after that we want to create new project in visual studio.

These are the steps on How To Create CRUD Operation In ASP.NET MVC

  • Step 1: Open SQL Server

    Open SQL Server (enter the Server Name, Id and Password then click on Connect).
    crud operation in asp.net connect sql server

  • Step 2: Create new database

    Create a new database (right-click on Database then select New Database).
    crud operation in asp.net create new database

  • Step 3: Name your database

    Enter “ASPCRUD” for the database name then click OK.
    crud operation in asp.net database name

  • Step 4: Create new table

    Create a new table (explore the CRUD database then right-click on Tables then select New Table).
    crud operation in asp.net create table

  • Step 5: Design the table

    Design the table (name the columns and set the data types as shown in the following figure).
    crud operation in asp.net design table

  • Step 6: Open Visual Studio

    Create a New Web Application (open Visual Studio then select File -> New ->New Project).

    crud operation in asp.net create new project

  • Step 7: Select ASP.NET Web Application

    Next, select ASP.NET Web Application(.NET Framework).
    crud operation in asp.net web application

  • Step 8: Name your project

    Next, name your project and then, click create button.
    crud operation in asp.net project name

  • Step 9: Select empty project

    Next, select empty project, then click create.
    crud operation in asp.net empty project

  • Step 10: Add new item

    Next, right click on your project name on the right side under solution explorer and click add then new item.
    crud operation in asp.net add new item

  • Step 11: Select web form

    Next, select web form the click add and name your form “Contact”
    crud operation in asp.net select web form

  • Step 12 : Add reference

    Next, right click the project in the solution explorer then click add the click reference.
    crud operation in asp.net add reference

  • Step 13: Add mysql.data.dll

    Next, add mysql.data.dll then click ok.
    crud operation in asp.net select mysql data dll

  • Step 14: Copy the code given

    Final, copy all code given below and paste it to each designated file.

Contact.aspx

here’s the code for the Contact.aspx file.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Contact.aspx.cs" Inherits="asp.netcrud.Contact" %>

<!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="Adddress"></asp:Label>
                </td>
                <td colspan="2">
                    <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    
                </td>
                <td colspan="2">
                    <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
                    <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
                    <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>
                <td>
                    
                </td>
                <td colspan="2">
                    <asp:Label ID="lblErrorMessage" runat="server" Text="" ForeColor="Red"></asp:Label>
                </td>
            </tr>
            </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>

Contact.aspx.cs

Here’s the code for Contact.aspx.cs file

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

namespace asp.netcrud
{
    public partial class Contact : System.Web.UI.Page
    {

        SqlConnection sqlCon = new SqlConnection(@"Data Source=LAPTOP-AMM1MQ8C;Initial Catalog=ASPCRUD;Integrated Security=true;");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnDelete.Enabled = false;
                FillGridView();
            }
        }

        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 = "Save";
            btnDelete.Enabled = false;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (sqlCon.State == ConnectionState.Closed)
                sqlCon.Open();
            SqlCommand sqlCmd = new SqlCommand("ContactCreateOrUpdate",sqlCon);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@ConatctID",(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();
        }

        void FillGridView()
        {
            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();
        
        }

        protected void lnk_OnClick(object sender, EventArgs e)
        {
            int contactID = Convert.ToInt32((sender as LinkButton).CommandArgument);
            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;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            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();
            sqlCon.Close();
            Clear();
            FillGridView();
            lblSuccessMessage.Text = "Deleted Successfully";
        }
    }
}

Contact.aspx.designer.cs

Here’s the code for Contact.aspx.designer.cs.

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated. 
// </auto-generated>
//------------------------------------------------------------------------------

namespace asp.netcrud
{


    public partial class Contact
    {

        /// <summary>
        /// form1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlForm form1;

        /// <summary>
        /// hfContactID control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hfContactID;

        /// <summary>
        /// Label1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label1;

        /// <summary>
        /// txtName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtName;

        /// <summary>
        /// Label2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label2;

        /// <summary>
        /// txtMobile control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtMobile;

        /// <summary>
        /// Label3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label3;

        /// <summary>
        /// txtAddress control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtAddress;

        /// <summary>
        /// btnSave control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnSave;

        /// <summary>
        /// btnDelete control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnDelete;

        /// <summary>
        /// btnClear control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnClear;

        /// <summary>
        /// lblSuccessMessage control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblSuccessMessage;

        /// <summary>
        /// lblErrorMessage control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblErrorMessage;

        /// <summary>
        /// gvContact control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView gvContact;
    }
}

Conclusion

Using the .Net Framework 4.7.2 and a code generation tool, we learned how to develop an ASP.NET Web application and link it to a SQL Server to execute basic CRUD tasks. I hope you found it beneficial. Please let us know what you think in the comments area below.

Download Source Code below

Anyway, if you want to level up your programming knowledge, especially ASP.net, try this new article I’ve made for you ASP.Net Projects With Source Code For Final Year Students.

Related Articles

Inquiries

If you have any questions or suggestions about CRUD Operation in ASP NET MVC With Source Code, please feel free to leave a comment below.

Frequently Asked Questions

What does this ASP.NET CRUD example demonstrate?

Basic Create, Read, Update, Delete operations against one entity via Entity Framework. Foundation tutorial showing routes, controllers, Razor views, scaffolding, validation.

What ASP.NET and Visual Studio versions does this project require?

Most projects in this batch use ASP.NET MVC 5 on .NET Framework 4.5+ OR ASP.NET Core 3.1/6.0+. Check the .csproj file’s TargetFramework for exact version. To run: install Visual Studio 2019/2022 (Community is free) with the ‘ASP.NET and web development’ workload, open the .sln, restore NuGet packages, build, then F5.

How do I set up the database for this ASP.NET project?

Open SQL Server Management Studio (SSMS) and connect to your SQL Server (typically localhost\SQLEXPRESS). Right-click Databases > Restore (or run the included .sql script). Update the connection string in Web.config (or appsettings.json for .NET Core) with your server name + credentials. For EF Code-First: run Update-Database in Package Manager Console.

Can I use this ASP.NET project for a BSIT capstone or thesis?

Yes, but extend it. A bare CRUD app is too narrow for full capstone scope. Add: ASP.NET Identity roles, dashboards (Chart.js + AJAX endpoints), PDF exports (iTextSharp or Rotativa), email notifications (SmtpClient), real domain extension (analytics, audit log, multi-branch). Pair with Chapter 1-5 documentation.

Why am I getting ‘login failed’ or ‘cannot connect to SQL Server’ errors?

Three common ASP.NET startup issues: (1) Connection string in Web.config has wrong server name OR SQL Server service isn’t running (check SQL Server Configuration Manager). (2) Login failed: SQL Server authentication mode is set to ‘Windows only’ but connection string uses SQL auth – enable Mixed Mode in SSMS server properties. (3) ‘Cannot open database’: database name in connection string doesn’t match the restored database name.

Where can I find more ASP.NET projects with source code?

Browse the ASP.NET Projects hub for the full library. For C# WinForms desktop alternatives see C# Projects (55+ Windows Forms systems). For other .NET stacks see VB.NET Projects (300+ systems). For BSIT capstone idea lists see 150 Best Capstone Project Ideas.

Angel Jude Suarez

Full-Stack Developer at PIES IT Solution

Focuses on Python development, machine learning, and AI integration. Has built production AI systems including OpenAI Whisper integration for medical transcription and GPT-4o-powered diagnosis assistance. Strong background in pandas, scikit-learn, and TensorFlow.

Expertise: Python · PHP · Java · VB.NET · ASP.NET · Machine Learning · AI Integration · OpenCV · Django · CodeIgniter  · View all posts by Angel Jude Suarez →

Leave a Comment