articles

Home / DeveloperSection / Articles / Insert, Delete, Update in DataGridView with DataTable in C#

Insert, Delete, Update in DataGridView with DataTable in C#

Insert, Delete, Update in DataGridView with DataTable in C#

AVADHESH PATEL166388 21-Jul-2012

Insert, Delete, Update in DataGridView with DataTable in C#

Hi guys, there is a very simple way to insert, delete, update data in DataGridVifew with the help of using DataTable. Steps are given below…
 

Step 1:-

Make a table in the database

create table gridview
(
id intprimarykey,
name varchar(50)NOTNULL,
age intNOTNULL,
salary floatNOTNULL,
country varchar(50)NOTNULL,
city varchar(50)NOTNULL
)

 

 

 

Step 2:-    

Take datagridview and button on a windows form and disable checkbox of Adding, Editing, Deleting, Column Reordering of DataGridview

Insert, Delete, Update in DataGridView with DataTable in C#

Step 3:- 

Add a new Class for global use of datatable and SqlAddapter ‘s objects 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace datagridview

{

    class GlobalClass

    {

        public static SqlDataAdapter adap;

        public static DataTable dt;

    }

}

 

 Step 4:-  Write code on form’s cs file

using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
 
namespace datagridview
{
    public partial class DataGridView : Form
    {
        SqlConnection con;
        SqlCommandBuilder bui;
 
        string str;
        int i;
        public DataGridView()
        {
            InitializeComponent();
        }
 
        /// <summary>
        /// gridfill method used for fill record in datagridview
        /// </summary>
        void gridfill()
        {
            string cnString = System.Configuration.ConfigurationManager.ConnectionStrings['dbconnection'].ConnectionString;
            con= new SqlConnection(cnString);
            GlobalClass.adap = new SqlDataAdapter('select * from gridview', con);
            bui= new SqlCommandBuilder(GlobalClass.adap);
            GlobalClass.dt = new DataTable();
            GlobalClass.adap.Fill(GlobalClass.dt);
            dataGridView1.DataSource= GlobalClass.dt;
            dataGridView1.ReadOnly= true;
        }
 
 
        private void DataGridView_Load(object sender, EventArgs e)
        {
            try
            {
                gridfill();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
 
        /// <summary>
        /// selected rows index and values passed to OperationForm
        /// </summary>
        /// <param name='sender'></param>
        /// <param name='e'></param>
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            str= dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();                       i = dataGridView1.Rows[e.RowIndex].Index;
            Opereation op = new Opereation(str,i);
            op.Show();
        }
       
        private void button1_Click(object sender, EventArgs e)
        {
            str= '';
            Opereation op = new Opereation(str, i);
            op.Show();
        }
   }
}

 Step 5:- Make the second form for display, insertion, deletion and updating data into datagridview 

 

Insert, Delete, Update in DataGridView with DataTable in C#

Step 6:- 

write code on form’s cs file

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace datagridview

{

  

    public partial class Opereation : Form

    {

        string userid;

        int rowId;

        public Opereation(string id,int i)

        {

            InitializeComponent();

            userid = id;

            rowId = i;

           

        }

 

        /// <summary>

        /// auto gererate column in datatable

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

        private void Opereation_Load(object sender, EventArgs e)

        {

            int rowcount = GlobalClass.dt.Rows.Count;

 

            if (GlobalClass.dt.Rows.Count == 0)

            {

                int set = 100;

                txtId.Text = set.ToString();

                btnUpdate.Visible = false;

                btnInsert.Visible = true;

                btnDelete.Enabled = false;

            }

            else if(userid == '')

            {

                int maxId = Convert.ToInt16(GlobalClass.dt.Compute('MAX(id)', string.Empty));

                maxId = maxId + 1;

                txtId.Text = maxId.ToString();

                btnUpdate.Visible = false;

                btnInsert.Visible = true;

                btnDelete.Enabled = false;

            }

 

            else

            {

               try

                {

                    txtId.Text = GlobalClass.dt.Rows[rowId]['id'].ToString();

                    txtName.Text = GlobalClass.dt.Rows[rowId]['name'].ToString();

                    txtAge.Text  = GlobalClass.dt.Rows[rowId]['age'].ToString();

                    txtSalary.Text = GlobalClass.dt.Rows[rowId]['salary'].ToString();

                    txtCountry.Text = GlobalClass.dt.Rows[rowId]['country'].ToString();

                    txtCity.Text = GlobalClass.dt.Rows[rowId]['city'].ToString();

                }

                catch (Exception ex)

                {

                    MessageBox.Show(ex.ToString());

                }

            }

        }

 

        private void btnClose_Click(object sender, EventArgs e)

        {

            this.Close();

        }

 

        /// <summary>

        /// delete record from datatable

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

        private void btnDelete_Click(object sender, EventArgs e)

        {

            try

            {

               GlobalClass.dt.Rows[rowId].Delete();

               GlobalClass.adap.Update(GlobalClass.dt);

               this.Close();      

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

            }

        }

 

        /// <summary>

        /// update record in datatable

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

        private void btnUpdate_Click(object sender, EventArgs e)

        {

            try

            {

                GlobalClass.dt.Rows[rowId]['name'] = txtName.Text.Trim();

                GlobalClass.dt.Rows[rowId]['age'] = txtAge.Text.Trim();

                GlobalClass.dt.Rows[rowId]['salary'] = txtSalary.Text.Trim();

                GlobalClass.dt.Rows[rowId]['country'] = txtCountry.Text.Trim();

                GlobalClass.dt.Rows[rowId]['city'] = txtCity.Text.Trim();

                GlobalClass.adap.Update(GlobalClass.dt);

                this.Close();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

            }

        }

 

        /// <summary>

        /// Insert record in datatable

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

        private void btnInsert_Click(object sender, EventArgs e)

        {       

            try

            {

                    if (txtId.Text.Trim() == '' || txtName.Text.Trim() == '' || txtAge.Text.Trim() == '' || txtSalary.Text.Trim() == '' || txtCountry.Text.Trim() == '' || txtCity.Text.Trim() == '')

                    {

                        MessageBox.Show('Please fill all the entry....');

                    }

                    else

                    {

                        DataRow dr;

                        dr = GlobalClass.dt.NewRow();

                        dr['id'] = txtId.Text.Trim();

                        dr['name'] = txtName.Text.Trim();

                        dr['salary'] = txtSalary.Text.Trim();

                        dr['age'] = txtAge.Text.Trim();

                        dr['country'] = txtCountry.Text.Trim();

                        dr['city'] = txtCity.Text.Trim();

                        GlobalClass.dt.Rows.Add(dr);

                        GlobalClass.adap.Update(GlobalClass.dt);

                        this.Close();   

                    }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

            }

        }

 

        /// <summary>

        /// Name Validatoin

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

        private void txtName_KeyPress(object sender, KeyPressEventArgs e)

        {

            e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);

        }

       

        /// <summary>

        /// txtAge Validation

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

 

        private void txtAge_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)

        {

            e.Handled = !(char.IsNumber(e.KeyChar) || e.KeyChar == (char)Keys.Back);

        }

        

        /// <summary>

        /// Salary Validatoin

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

        private void txtSalary_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)

        {

            e.Handled = !(char.IsNumber(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == (char)Keys.Back);

        }

 

        /// <summary>

        /// Country Validatoin

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

        private void txtCountry_KeyPress(object sender, KeyPressEventArgs e)

        {

            e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);

        }

 

        /// <summary>

        /// city Validatoin

        /// </summary>

        /// <param name='sender'></param>

        /// <param name='e'></param>

        private void txtCity_KeyPress(object sender, KeyPressEventArgs e)

        {

            e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);

        }

    }

}


 

  Step 6:- Execute the program and click button ‘Add Record’ for adding a new record.

 

Insert, Delete, Update in DataGridView with DataTable in C#

Step7:- Fill all appropriate record in text fields and then click button ‘Save’

 

Insert, Delete, Update in DataGridView with DataTable in C#

Insert, Delete, Update in DataGridView with DataTable in C#

Step 8:-  And then double click on datagridview row for updating record and make some changes whatever you want for example, here you want to change name from “Avadhesh Patel” to “Avadhesh Singh” then you have to replace name from “Avadhesh Patel” to “Avadhesh Singh” in Name text field and after that click on button ‘Update’. Now updated records will visible in datagridview.

Insert, Delete, Update in DataGridView with DataTable in C#

Insert, Delete, Update in DataGridView with DataTable in C#

Step9:- Double click on datagridview row and press button ‘Delete’ to deleting data.

 

Insert, Delete, Update in DataGridView with DataTable in C#

Insert, Delete, Update in DataGridView with DataTable in C#

I hope this article might be helpful to you.


 

You should also read this Article - Select Insert Update and Delete using Stored Procedure in ASP.NET MVC4


Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By