This blog will explain to you how to perform CRUD operations (Insert, Select, Update and Delete operations) with DataGridView in Windows Forms Application using VB.NET and C# both languages with example.

Create Windows Forms Application

Step 1. Create Windows Forms Application from Visual Studio. (Steps: Open Visual Studio then Select File-> New Project-> Windows Forms Application-> OK)

Step 2. Create database and table in MSSQL Server with required columns i.e ID, FullName, EmailAddress, Gender, Hobbies, State. Set Primary key to ID column and also set Auto increment to it.

Step 3. Now design a form with all fields to perform insert, update, delete and select. Drag and drop Label, Textbox, RadioButton, CheckBox, Button and DataGridView from Toolbox. Your form may look like.

Step 4. Give proper name to all controls. And take click event of all button by double clicking on buttons.

Step 5. Take Row Double Click event of DataGridView. By this event, when you double click on any row of DataGridView, all the records of that row will reflect in controls and provide an update and delete button to perform respective operations.

Steps to take DoubleClick event of DataGridView: Right click on DataGridView-> Select Properties-> Select Event from Property Window-> Double click on DoubleClick event.

Step 6. Now to go to Form1.vb file, which code-behind file Form1. Write below code to perform insert, update, delete and select a task on proper events. Please read my comments to understand code properly. You have to import System.Data.SqlClient and System.Data namespaces at the top of the page.

Below is the code in VB.NET.

Form1.vb

Imports System.Data.SqlClient ' Add this namespace '

Imports System.Data ' Add this namespace '

  

Public Class Form1

  

    ' Connection String '

    Dim strCon As String = "Data Source=DELL-PC;Initial Catalog=dbCRUD;Integrated Security=True"

  

    ' Declaration of Connection objects '

    Dim con As SqlConnection

    Dim cmd As SqlCommand

    Dim da As SqlDataAdapter

    Dim dt As DataTable

  

    ' Form Load event '

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

  

        ' Set visibility of buttons on Form load '

        btnAdd.Visible = True

        btnRefresh.Visible = True

        btnUpdate.Visible = False

        btnDelete.Visible = False

        btnCancel.Visible = False

  

        ' Bind DataGridView on Form load '

        getData()

  

    End Sub

  

    ' Get data from table and Bind to DataGridView '

    Public Sub getData()

  

        con = New SqlConnection(strCon)

        da = New SqlDataAdapter("select * from tblCustomer", con)

        dt = New DataTable()

        da.Fill(dt)

        grdData.DataSource = dt

  

    End Sub

  

    ' Add button click event '

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click

  

        Dim FullName As String = "", EmailAddress As String = "", Gender As String = "", Hobbies As String = "", State As String = ""

  

        FullName = txtFullName.Text

        EmailAddress = txtEmailAddress.Text

  

        If rdoMale.Checked = True Then

            Gender = rdoMale.Text

        End If

        If rdoFemale.Checked = True Then

            Gender = rdoFemale.Text

        End If

  

        If chkCricket.Checked = True Then

            If Hobbies = "" Then

                Hobbies = chkCricket.Text

            Else

                Hobbies = Hobbies + "," + chkCricket.Text

            End If

        End If

        If chkFootball.Checked = True Then

            If Hobbies = "" Then

                Hobbies = chkFootball.Text

            Else

                Hobbies = Hobbies + "," + chkFootball.Text

            End If

        End If

  

        State = cmbState.SelectedItem.ToString()

  

        con = New SqlConnection(strCon)

        cmd = New SqlCommand("insert into tblCustomer(FullName,EmailAddress,Gender,Hobbies,State) values('" + FullName + "','" + EmailAddress + "','" + Gender + "','" + Hobbies + "','" + State + "')", con)

        con.Open()

        cmd.ExecuteNonQuery()

        con.Close()

  

        MessageBox.Show("Inserted Successfully..")

  

        getData()

        ResetAllControls()

  

    End Sub

  

    ' DataGridView row double click event '

    Private Sub grdData_DoubleClick(sender As Object, e As EventArgs) Handles grdData.DoubleClick

  

ResetAllControls()

  

        Dim ID As Integer = Integer.Parse(grdData.CurrentRow.Cells(0).Value.ToString())

  

        con = New SqlConnection(strCon)

        da = New SqlDataAdapter("select * from tblCustomer where ID='" + ID.ToString() + "'", con)

        dt = New DataTable()

        da.Fill(dt)

  

        txtFullName.Text = dt.Rows(0)("FullName").ToString()

        txtEmailAddress.Text = dt.Rows(0)("EmailAddress").ToString()

  

        Dim gender As String = dt.Rows(0)("Gender").ToString()

        If gender = "Male" Then

            rdoMale.Checked = True

        End If

        If gender = "Female" Then

            rdoFemale.Checked = True

        End If

  

        Dim hobbies As String() = dt.Rows(0)("Hobbies").ToString().Split(",")

        For i = 0 To hobbies.Length - 1

  

            If hobbies(i) = "Cricket" Then

                chkCricket.Checked = True

            End If

            If hobbies(i) = "Football" Then

                chkFootball.Checked = True

            End If

  

        Next

  

        cmbState.Text = dt.Rows(0)("State").ToString()

  

        btnAdd.Visible = False

        btnRefresh.Visible = False

        btnUpdate.Visible = True

        btnDelete.Visible = True

        btnCancel.Visible = True

  

    End Sub

  

    ' Update button click event '

    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click

  

        Dim ID As Integer = Integer.Parse(grdData.CurrentRow.Cells(0).Value.ToString())

  

        Dim FullName As String = "", EmailAddress As String = "", Gender As String = "", Hobbies As String = "", State As String = ""

  

        FullName = txtFullName.Text

        EmailAddress = txtEmailAddress.Text

  

        If rdoMale.Checked = True Then

            Gender = rdoMale.Text

        End If

        If rdoFemale.Checked = True Then

            Gender = rdoFemale.Text

        End If

  

        If chkCricket.Checked = True Then

            If Hobbies = "" Then

                Hobbies = chkCricket.Text

            Else

                Hobbies = Hobbies + "," + chkCricket.Text

            End If

        End If

        If chkFootball.Checked = True Then

            If Hobbies = "" Then

                Hobbies = chkFootball.Text

            Else

                Hobbies = Hobbies + "," + chkFootball.Text

            End If

        End If

  

        State = cmbState.SelectedItem.ToString()

  

        con = New SqlConnection(strCon)

        cmd = New SqlCommand("update tblCustomer set FullName='" + FullName + "',EmailAddress='" + EmailAddress + "',Gender='" + Gender + "',Hobbies='" + Hobbies + "',State='" + State + "' where ID='" + ID.ToString() + "'", con)

        con.Open()

        cmd.ExecuteNonQuery()

        con.Close()

  

        MessageBox.Show("Updated Successfully..")

  

        getData()

        ResetAllControls()

  

    End Sub

  

    ' Delete button click event '

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click

  

        Dim ID As Integer = Integer.Parse(grdData.CurrentRow.Cells(0).Value.ToString())

  

        con = New SqlConnection(strCon)

        cmd = New SqlCommand("delete from tblCustomer where ID='" + ID.ToString() + "'", con)

        con.Open()

        cmd.ExecuteNonQuery()

        con.Close()

  

        MessageBox.Show("Deleted Successfully..")

  

        getData()

        ResetAllControls()

  

    End Sub

  

    ' Cancel button click event '

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click

  

        ResetAllControls()

  

    End Sub

  

    ' Refresh button click event '

    Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click

  

        ResetAllControls()

  

    End Sub

  

    ' Reset all controls '

    Public Sub ResetAllControls()

  

        txtFullName.Text = ""

        txtEmailAddress.Text = ""

        rdoMale.Checked = False

        rdoFemale.Checked = False

        chkCricket.Checked = False

        chkFootball.Checked = False

        cmbState.Text = "--Select State--"

        btnAdd.Visible = True

        btnRefresh.Visible = True

        btnUpdate.Visible = False

        btnDelete.Visible = False

        btnCancel.Visible = False

  

    End Sub

  

End Class

Below is the code in C#.

Form1.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Data.SqlClient; /* Add this namespace */

using System.Data; /* Add this namespace */

  

namespace CRUDOperationsCSharp

{

    public partial class Form1 : Form

    {

        /* Connection String */

        string strCon = "Data Source=DELL-PC;Initial Catalog=dbCRUD;Integrated Security=True";

  

        /* Declaration of Connection objects */

        SqlConnection con;

        SqlCommand cmd;

        SqlDataAdapter da;

        DataTable dt;

  

        public Form1()

        {

            InitializeComponent();

        }

  

        /* Form Load event */

        private void Form1_Load(object sender, EventArgs e)

        {

            /* Set visibility of buttons on Form load */

            btnAdd.Visible = true;

            btnRefresh.Visible = true;

            btnUpdate.Visible = false;

            btnDelete.Visible = false;

            btnCancel.Visible = false;

  

            /* Bind DataGridView on Form load */

            getData();

        }

  

        /* Get data from table and Bind to DataGridView */

        public void getData()

        {

            con = new SqlConnection(strCon);

            da = new SqlDataAdapter("select * from tblCustomer", con);

            dt = new DataTable();

            da.Fill(dt);

            grdData.DataSource = dt;

        }

  

        /* Add button click event */

        private void btnAdd_Click(object sender, EventArgs e)

        {

            string FullName = "", EmailAddress = "", Gender = "", Hobbies = "", State = "";

  

            FullName = txtFullName.Text;

            EmailAddress = txtEmailAddress.Text;

  

            if (rdoMale.Checked == true)

            {

                Gender = rdoMale.Text;

            }

            if (rdoFemale.Checked == true)

            {

                Gender = rdoFemale.Text;

            }

  

            if (chkCricket.Checked == true)

            {

                if (Hobbies == "")

                {

                    Hobbies = chkCricket.Text;

                }

                else

                {

                    Hobbies = Hobbies + "," + chkCricket.Text;

                }

            }

            if (chkFootball.Checked == true)

            {

                if (Hobbies == "")

                {

                    Hobbies = chkFootball.Text;

                }

                else

                {

                    Hobbies = Hobbies + "," + chkFootball.Text;

                }

            }

  

            State = cmbState.SelectedItem.ToString();

  

            con = new SqlConnection(strCon);

            cmd = new SqlCommand("insert into tblCustomer(FullName,EmailAddress,Gender,Hobbies,State) values('" + FullName + "','" + EmailAddress + "','" + Gender + "','" + Hobbies + "','" + State + "')", con);

            con.Open();

            cmd.ExecuteNonQuery();

            con.Close();

  

            MessageBox.Show("Inserted Successfully..");

  

            getData();

            ResetAllControls();

        }

  

        /* DataGridView row double click event */

        private void grdData_DoubleClick(object sender, EventArgs e)

        {

            ResetAllControls();

           

            int ID = int.Parse(grdData.CurrentRow.Cells[0].Value.ToString());

  

            con = new SqlConnection(strCon);

            da = new SqlDataAdapter("select * from tblCustomer where ID='" + ID.ToString() + "'", con);

            dt = new DataTable();

            da.Fill(dt);

  

            txtFullName.Text = dt.Rows[0]["FullName"].ToString();

            txtEmailAddress.Text = dt.Rows[0]["EmailAddress"].ToString();

  

            string gender = dt.Rows[0]["Gender"].ToString();

            if (gender == "Male")

            {

                rdoMale.Checked = true;

            }

            if (gender == "Female")

            {

                rdoFemale.Checked = true;

            }

  

            string[] hobbies = dt.Rows[0]["Hobbies"].ToString().Split(',');

            for (int i = 0; i < hobbies.Length; i++)

            {

                if (hobbies[i] == "Cricket")

                {

                    chkCricket.Checked = true;

                }

                if (hobbies[i] == "Football")

                {

                    chkFootball.Checked = true;

                }

            }

  

            cmbState.Text = dt.Rows[0]["State"].ToString();

  

            btnAdd.Visible = false;

            btnRefresh.Visible = false;

            btnUpdate.Visible = true;

            btnDelete.Visible = true;

            btnCancel.Visible = true;

        }

  

        /* Update button click event */

        private void btnUpdate_Click(object sender, EventArgs e)

        {

            int ID = int.Parse(grdData.CurrentRow.Cells[0].Value.ToString());

  

            string FullName = "", EmailAddress = "", Gender = "", Hobbies = "", State = "";

  

            FullName = txtFullName.Text;

            EmailAddress = txtEmailAddress.Text;

  

            if (rdoMale.Checked == true)

            {

                Gender = rdoMale.Text;

            }

  

            if (rdoFemale.Checked == true)

            {

                Gender = rdoFemale.Text;

            }

  

            if (chkCricket.Checked == true)

            {

                if (Hobbies == "")

                {

                    Hobbies = chkCricket.Text;

                }

                else

                {

                    Hobbies = Hobbies + "," + chkCricket.Text;

                }

            }

            if (chkFootball.Checked == true)

            {

                if (Hobbies == "")

                {

                    Hobbies = chkFootball.Text;

                }

                else

                {

                    Hobbies = Hobbies + "," + chkFootball.Text;

                }

            }

  

            State = cmbState.SelectedItem.ToString();

  

            con = new SqlConnection(strCon);

            cmd = new SqlCommand("update tblCustomer set FullName='" + FullName + "',EmailAddress='" + EmailAddress + "',Gender='" + Gender + "',Hobbies='" + Hobbies + "',State='" + State + "' where ID='" + ID.ToString() + "'", con);

            con.Open();

            cmd.ExecuteNonQuery();

            con.Close();

  

            MessageBox.Show("Updated Successfully..");

  

            getData();

            ResetAllControls();

        }

  

        /* Delete button click event */

        private void btnDelete_Click(object sender, EventArgs e)

        {

            int ID = int.Parse(grdData.CurrentRow.Cells[0].Value.ToString());

  

            con = new SqlConnection(strCon);

            cmd = new SqlCommand("delete from tblCustomer where ID='" + ID.ToString() + "'", con);

            con.Open();

            cmd.ExecuteNonQuery();

            con.Close();

  

            MessageBox.Show("Deleted Successfully..");

  

            getData();

            ResetAllControls();

        }

  

        /* Cancel button click event */

        private void btnCancel_Click(object sender, EventArgs e)

        {

            ResetAllControls();

        }

  

        /* Refresh button click event */

        private void btnRefresh_Click(object sender, EventArgs e)

        {

            ResetAllControls();

        }

  

        /* Reset all controls */

        public void ResetAllControls()

        {

            txtFullName.Text = "";

            txtEmailAddress.Text = "";

            rdoMale.Checked = false;

            rdoFemale.Checked = false;

            chkCricket.Checked = false;

            chkFootball.Checked = false;

            cmbState.Text = "--Select State--";

            btnAdd.Visible = true;

            btnRefresh.Visible = true;

            btnUpdate.Visible = false;

            btnDelete.Visible = false;

            btnCancel.Visible = false;

        }

    }

}

Step 7. Run the form and check all operations. Your output may look like below.

Output preview

Hope you will like this blog. Feel free to ask the question in comments. Thank You… :)