How to Insert Update Delete data in Database from DataGridView in C#

By FoxLearn 12/12/2024 3:25:05 PM   13.55K
To manage Insert, Update, and Delete operations in a SQL database using a DataGridView in a C# Windows Forms application built with the Metro Framework (Modern UI), follow these steps.

This guide demonstrates how to build a modern Windows Forms application using the Metro Framework to perform CRUD operations (Create, Read, Update, Delete) on a SQL database.

How to Insert Update Delete data in Database from DataGridView 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 "MetroUI" and then click OK

Right click on your project select Manage NuGet Packages -> Search metro framework -> Install

install metro framework

Design your form as shown below.

Form1

metro ui c#

frmAddEditStudent

c# metro ui

Create a City, Student table, then add to your Entity Framework Model as shown below.

ef model c#

When the application starts, Form1_Load initializes the database context and loads data into the DataGridView.

private void Form1_Load(object sender, EventArgs e)
{
    // Initialize database context
    db = new DbEntities();
    studentBindingSource.DataSource = db.Students.ToList(); // Load students
    cityBindingSource.DataSource = db.Cities.ToList(); // Load cities
}

The BindingSource objects (studentBindingSource, cityBindingSource) simplify data binding for the DataGridView.

The DbEntities is the Entity Framework database context.

When the mtAdd button is clicked, the frmAddEditStudent form is displayed. The new student object is added to the database and refreshed in the grid.

private async void mtAdd_Click(object sender, EventArgs e)
{
    //Add new student to binding source
    using (frmAddEditStudent frm = new frmAddEditStudent(new Student() { Gender = false }))
    {
        if (frm.ShowDialog() == DialogResult.OK)
        {
            try
            {
                // Add to binding source
                studentBindingSource.Add(frm.StudentInfo);
                db.Students.Add(frm.StudentInfo); // Add to database
                await db.SaveChangesAsync(); // Save changes
                dataGridView.Refresh(); // Refresh grid
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

The mtRefresh button reloads data from the database into the BindingSource

private void mtRefresh_Click(object sender, EventArgs e)
{
    //Reload data
    Cursor.Current = Cursors.WaitCursor;
    studentBindingSource.DataSource = db.Students.ToList();
    cityBindingSource.DataSource = db.Cities.ToList();
    Cursor.Current = Cursors.Default;
}

The mtEdit button retrieves the selected student record for editing. Changes are saved back to the database.

private async void mtEdit_Click(object sender, EventArgs e)
{
    Student obj = studentBindingSource.Current as Student;
    if (obj != null)
    {
        using (frmAddEditStudent frm = new frmAddEditStudent(obj))
        {
            if (frm.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // Apply changes to binding source
                    studentBindingSource.EndEdit();
                    await db.SaveChangesAsync(); // Save to database
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}

The mtDelete button deletes selected rows from the DataGridView and database.

private async void mtDelete_Click(object sender, EventArgs e)
{
    //Delete data from binding source, then save to sql database
    if (MessageBox.Show("Are you sure want to delete this record?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        int rows = dataGridView.RowCount;
        for (int i = rows - 1; i >= 0; i--)
        {
            if (dataGridView.Rows[i].Selected)
            {
                db.Students.Remove(dataGridView.Rows[i].DataBoundItem as Student); // Remove from database
                studentBindingSource.RemoveAt(dataGridView.Rows[i].Index); // Remove from grid
                await db.SaveChangesAsync();
            }
        }
    }
}

The mtSave button commits pending changes in the BindingSource to the database.

private async void mtSave_Click(object sender, EventArgs e)
{
    try
    {
        if (MessageBox.Show("Do you want to save the changes?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            // Apply changes to binding source
            studentBindingSource.EndEdit();
            await db.SaveChangesAsync(); // Save to database
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Form1

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 MetroUI
{
    public partial class Form1 : MetroFramework.Forms.MetroForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        DbEntities db;
    }
}

This form binds a Student object to the controls for editing. The btnSave button commits changes to the BindingSource.

public frmAddEditStudent(Student obj)
{
    InitializeComponent();
    bindingSourceStudent.DataSource = obj; // Bind student object to form
    if (chkGender.CheckState == CheckState.Checked)
        chkGender.Text = "Male";
    else if (chkGender.CheckState == CheckState.Unchecked)
        chkGender.Text = "Female";
    else
        chkGender.Text = "???";
}

Updates the label when the checkbox state changes.

private void chkGender_CheckStateChanged(object sender, EventArgs e)
{
    if (chkGender.CheckState == CheckState.Checked)
        chkGender.Text = "Male";
    else if (chkGender.CheckState == CheckState.Unchecked)
        chkGender.Text = "Female";
    else
        chkGender.Text = "???";
}

Add/Edit Form (frmAddEditStudent)

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 MetroUI
{
    public partial class frmAddEditStudent : MetroFramework.Forms.MetroForm
    { 
        //Get current student
        public Student StudentInfo { get { return bindingSourceStudent.Current as Student; } }

        private void btnSave_Click(object sender, EventArgs e)
        {
            bindingSourceStudent.EndEdit();
            DialogResult = DialogResult.OK;
        }

        private void frmAddEditStudent_Load(object sender, EventArgs e)
        {
            cboCity.DisplayMember = "CityName";
            cboCity.ValueMember = "CityId";
            using(DbEntities db = new DbEntities())
            {
                cboCity.DataSource = db.Cities.ToList();
            }
        }
    }
}

VIDEO TUTORIAL