How to Insert Update Delete Select in SQL Server in C#

By FoxLearn 12/10/2024 2:46:19 PM   6.25K
To perform Insert, Update, Delete, and Select operations in SQL Server using Entity Framework Database First in C#, you can follow these steps.

In this article, we'll create a Contact Management Application using C#, Entity Framework (EF) Database First, and Windows Forms (WinForms). This application will manage a Contact table in a database and provide CRUD (Create, Read, Update, Delete) operations.

How to Insert Update Delete Select in SQL Server in C#?

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "EFCRUD" and then click OK

Design your form as shown below.

Create Form1 (Main Form)

Name your main form: Form1

c# contact

 

Add a DataGridView control named contactDataGridView to display contacts.

Add buttons for Add, Edit, and Delete operations (btnAdd, btnEdit, and btnDelete respectively).

Create frmAddEditContact (Add/Edit Form)

Name your detail form: frmAddEditContact

c# add contact

 

Add TextBox controls for Contact Name, Phone Number, Email, and Address.

Add OK and Cancel buttons.

First, create the Contact table in your SQL Server database with the following structure.

CREATE TABLE Contacts (
    Id INT PRIMARY KEY IDENTITY(1,1),
    ContactName NVARCHAR(100) NOT NULL,
    PhoneNumber NVARCHAR(20),
    Email NVARCHAR(100),
    Address NVARCHAR(255)
)

Right-click on your project in the Solution Explorer, then select Add > New Item > ADO.NET Entity Data Model.

Choose EF Designer from Database, then connect to your database and select the Contacts table.

Complete the wizard. This generates the ContactEntities DbContext and a Contact entity class.

Form1 (Main Form)

The main form (Form1) is responsible for loading and displaying contacts, as well as handling add, edit, and delete actions.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EFCRUD
{
    public partial class Form1 : Form
    {
        ContactEntities db;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Load contact data from the database
            db = new ContactEntities();
            contactBindingSource.DataSource = db.Contacts.ToList();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //Open form to add a contact
            using(frmAddEditContact frm = new frmAddEditContact(null))
            {
                if (frm.ShowDialog() == DialogResult.OK)
                    contactBindingSource.DataSource = db.Contacts.ToList();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (contactBindingSource.Current == null)
                return;
            using (frmAddEditContact frm = new frmAddEditContact(contactBindingSource.Current as Contact))
            {
                if (frm.ShowDialog() == DialogResult.OK)
                    contactBindingSource.DataSource = db.Contacts.ToList();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (contactBindingSource.Current != null)
            {
                if(MessageBox.Show("Are you sure want to delete this record ?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //Delete contact
                    db.Contacts.Remove(contactBindingSource.Current as Contact);
                    contactBindingSource.RemoveCurrent();
                    db.SaveChanges();
                }
            }
        }
    }
}

frmAddEditContact (Add/Edit Form)

This form allows users to add or edit a contact.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EFCRUD
{
    public partial class frmAddEditContact : Form
    {
        ContactEntities db;
        public frmAddEditContact(Contact obj)
        {
            InitializeComponent();
            db = new ContactEntities();
            if (obj == null)
            {
                // Add new contact
                contactBindingSource.DataSource = new Contact();
                //Add contact to model, allow insert
                db.Contacts.Add(contactBindingSource.Current as Contact);
            }
            else
            {
                contactBindingSource.DataSource = obj;
                // Edit existing contact
                db.Contacts.Attach(contactBindingSource.Current as Contact);
            }
        }

        private void frmAddEditContact_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.OK)
            {
                // Validate contact name
                if (string.IsNullOrEmpty(txtContactName.Text))
                {
                    MessageBox.Show("Please enter your contact name.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtContactName.Focus();
                    e.Cancel = true;
                    return;
                }
                db.SaveChanges();
                e.Cancel = false;
            }
            e.Cancel = false;
        }
    }
}

When the application starts, the contacts are loaded into the DataGridView.

Add Contact: Opens frmAddEditContact with empty fields. After saving, the new contact appears in the DataGridView.

Edit Contact: Opens frmAddEditContact with the selected contact’s details pre-filled. Changes are saved after editing.

Delete Contact: Prompts for confirmation before deleting the selected contact.

VIDEO TUTORIAL