Windows Forms: Insert Update Delete data in Database from DataGridView in C#

How to Insert update delete data from datagridview in c# using sql database, Metro Framework, Modern UI

Step 1Click 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

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

install metro frameworkStep 3: Design your form as below

Form1

metro ui c#

frmAddEditStudent

c# metro ui

Step 4: Create a City, Student table, then add to your Entity Framework Model as below

ef model c#

Step 5: Add code to handle your winform as below

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

        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
                    {
                        studentBindingSource.Add(frm.StudentInfo);
                        db.Students.Add(frm.StudentInfo);
                        await db.SaveChangesAsync();
                        dataGridView.Refresh();
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        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;
        }

        DbEntities db;

        private void Form1_Load(object sender, EventArgs e)
        {
            //Init data
            db = new DbEntities();
            studentBindingSource.DataSource = db.Students.ToList();
            cityBindingSource.DataSource = db.Cities.ToList();
        }

        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
                        {
                            //End edit & save data to sql database
                            studentBindingSource.EndEdit();
                            await db.SaveChangesAsync();
                        }
                        catch(Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }

        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);
                        studentBindingSource.RemoveAt(dataGridView.Rows[i].Index);
                        await db.SaveChangesAsync();
                    }
                }
            }
        }

        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)
                {
                    //End edit data & save
                    studentBindingSource.EndEdit();
                    await db.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

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
    {
        //Init data
        public frmAddEditStudent(Student obj)
        {
            InitializeComponent();
            bindingSourceStudent.DataSource = obj;
            if (chkGender.CheckState == CheckState.Checked)
                chkGender.Text = "Male";
            else if (chkGender.CheckState == CheckState.Unchecked)
                chkGender.Text = "Female";
            else
                chkGender.Text = "???";
        }

        //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();
            }
        }

        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 = "???";
        }
    }
}

VIDEO TUTORIALS