Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    APIs
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> C# >> 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#


by AVADHESH PATEL on 7/21/2012 4:39:29 PM

Views: 17460       Comments: 15

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

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

Step 1:-

Make table in database

create table gridview

(

id int primary key,

name varchar(50) NOT NULL,

age int NOT NULL,

salary float NOT NULL,

country varchar(50) NOT NULL,

city varchar(50) NOT NULL

)

Step 2:-    

Take datagridview and button on windows form and disable checkbox of Adding, Editing, Deleting, Column Recordering  of datagridview

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

Step 3:- Add a new Class for globally 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 Operation Form

        /// </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 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 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:- 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 record 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 for you.

Report Abuse Form
Reason:    
 


Help me
by Horas Panjaitan 12/14/2012 11:25:54 AM
Hi AVADHESH PATEL

How do I replace the following code "1001" to "K001"

thanks

 SqlCommand cmd = new SqlCommand("Select max(kode_barang) from tblbarang", myConnection);

                    SqlDataReader dr = cmd.ExecuteReader();

                    if (dr.Read())
                    {

                        string d = dr[0].ToString();

                        if (d == "")
                        {

                            txtkode.Text = "1001"; // this may code........<<<

                        }

                        else
                        {

                            r = Convert.ToInt32(dr[0].ToString());

                            r = r + 1;

                            txtkode.Text = r.ToString();

                        }

                    }

                    myConnection.Close();


                }

                catch (Exception ex)
                {

                    MessageBox.Show(ex.ToString());

                }

                finally
                {

                    myConnection.Close();

                }
Report Abuse

provide more details about your problem
by AVADHESH PATEL 12/17/2012 2:14:31 AM
Hi Horas Panjaitan

provide  more information  related your question with table structure!
Report Abuse

How do I replace the following code "1001" to "K001"
by Horas Panjaitan 12/19/2012 1:02:12 PM
this example my table

 table  student

nim  varchar(10) noot null, Primary key            Information nim = student identification number
name varchar(50) noot null,
class  varchar (35) noot null,

 table   quiz
code_quiz varchar(10) noot null, Primary key
semester char(4) noot null,
nim varchar(10) noot null,   FK




thank you in advance
Report Abuse

How do I replace the following code "1001" to "K001" ?
by Rohit Kesharwani 12/21/2012 1:30:46 AM
Hi Horas,

you can do like this:

       public string GetEmployeeId()
        {
            object sId = null;
            try
            {
                using (SqlConnection cn = new SqlConnection("Data Source=(local); Initial Catalog=db; User Id =userid;Password=password"))
                {
                    using (SqlCommand cmd = cn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "select max(Id) from Employee";
                        cn.Open();
                        sId = cmd.ExecuteScalar();
                    }
                }
            }
            catch { }

            if (string.IsNullOrEmpty(sId.ToString()))
            {
                sId = "K001";
            }
            else
            {
                int id = Convert.ToInt32(sId.ToString().Substring(1));
                id++;
                if (id >= 1 && id <= 9)
                    sId = "K00" + id;
                else if (id >= 10 && id <= 99)
                    sId = "K0" + id;
                else if (id >= 100 && id <= 999)
                    sId = "K" + id;
            }

            return sId.ToString();
}

after creating the above method, you can call and set the value whereever you want:
for eg. txtEmployeeId.Text = GetEmployeeId();
Report Abuse

Thanks
by Horas Panjaitan 12/22/2012 12:56:32 AM
Thanks for the help Rohit kesharwani and Avadhesh PATEL
god bless us all
Report Abuse

Help This Code To Asp.Net C#
by Horas Panjaitan 3/6/2013 5:04:08 AM
Hi Rohit Kesharwani
  The code I cob in asp.net why does not work, I ask you please to explain it?

   public string GetEmployeeId()
        {
            object sId = null;
            try
            {
                using (SqlConnection cn = new SqlConnection("Data Source=(local); Initial Catalog=db; User Id =userid;Password=password"))
                {
                    using (SqlCommand cmd = cn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "select max(Id) from Employee";
                        cn.Open();
                        sId = cmd.ExecuteScalar();
                    }
                }
            }
            catch { }

            if (string.IsNullOrEmpty(sId.ToString()))
            {
                sId = "K001";
            }
            else
            {
                int id = Convert.ToInt32(sId.ToString().Substring(1));
                id++;
                if (id >= 1 && id <= 9)
                    sId = "K00" + id;
                else if (id >= 10 && id <= 99)
                    sId = "K0" + id;
                else if (id >= 100 && id <= 999)
                    sId = "K" + id;
            }

            return sId.ToString();
}
Report Abuse

Help This Code To Asp.Net C#
by AVADHESH PATEL 3/8/2013 12:35:50 AM
Hi Horas Panjaitan! 

 I have tried the above code in my asp.net project and it works nice. 
Could you explain me your problem in more details along with the database.
Report Abuse

thanks for the response
by Horas Panjaitan 3/8/2013 10:19:44 PM
HI..AVADHESH VATEL

This My database
 
Name database = dbbarang

Culum Name        data type     lenght
Kode_barang          ntext            16
Nama_barang         ntext            59
Harga                    numeric         9

after I click buttun get the code, a message saying = if (String.IsNullOrEmpty (sId.ToString ()))

this code

public string getcodeid()
        {
            object sId = null;
          
            try
            {
                using (SqlConnection cn = new SqlConnection("Data Source=(local); Initial Catalog=db; User Id =userid;Password=password"))
                {
                    using (SqlCommand cmd = cn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "select max(Id) from Employee";
                        cn.Open();
                        sId = cmd.ExecuteScalar();
                    }
                }
            }
            catch { }

            if (string.IsNullOrEmpty(sId.ToString()))
            {
                sId = "K001";
            }
            else
            {
                int id = Convert.ToInt32(sId.ToString().Substring(1)); this source error
                id++;
                if (id >= 1 && id <= 9)
                    sId = "K00" + id;
                else if (id >= 10 && id <= 99)
                    sId = "K0" + id;
                else if (id >= 100 && id <= 999)
                    sId = "K" + id;
            }

            return sId.ToString();
        }

Report Abuse

performed on the two form
by John fugio 3/10/2013 4:33:46 AM
if I have 2 fEmployee and fCustomer, how?
I open fEmployee before Then open to fCustomer, back fEmployee is faulty.
when using the event DataGridView1_CellDoubleClick
Report Abuse

Help This Code To Asp.Net C#
by AVADHESH PATEL 3/15/2013 5:32:07 AM
Hi Horas!

Which table structured you are described here, there is no id column, and you are try to get value based on id in below line of code

cmd.CommandText = "select max(Id) from Employee";

Create id column with varchar datatype into your table
Report Abuse

re: performed on the two form
by AVADHESH PATEL 3/15/2013 5:43:53 AM
Hi John!

Could you explain more information related to your problem, because i con't understand what you want. 
Report Abuse

Thanks to Rohit Kesharwani and AVADHESH PATEL
by Horas Panjaitan 3/22/2013 9:37:12 PM
Hi  AVADHESH PATEL Thank you so much, I was in the wrong code placement, and now the code is working.

god bless us
Report Abuse

Help Me about date of birth
by Horas Panjaitan 3/31/2013 12:53:37 PM
Hi AVADHESH PATEL

want to get the age of the following dates   06/04/1984  format date indonesia:(dd/MM/yyyy)


textAge.tex =   here I

how to code / syntak in this asp.net

please help me.
Report Abuse

Help me get age date of birth
by Horas Panjaitan 3/31/2013 12:57:30 PM
Hi Rohit Kesharwani

want to get the age of the following dates   06/04/1984  format date indonesia:(dd/MM/yyyy)


textAge.tex =   here I

how to code / syntak in this asp.net

please help me.
Report Abuse

Re: Help me get age date of birth
by AVADHESH PATEL 4/1/2013 9:48:16 AM
Hi Horas!

try this line of code

// Get current date time

DateTime d = DateTime.Now;

// Changed MM/dd/yyyy format to dd/MM/yyyy fromat

string s = d.ToString("dd/MM/yyyy");

// Convert date time in string (s) to DateTime (Todate) data type

DateTime Todate = DateTime.Parse(s, CultureInfo.CreateSpecificCulture("en-IA"));

// Convert entered date string (TextBox1.Text) to DateTime (givenDate) Data Type

DateTime givenDate = DateTime.Parse(TextBox1.Text);

// Count total days

double days = Todate.Subtract(givenDate).Days;

// Convert days to year and display into Label.Text

txtAge.Text = Math.Floor(days / 365.24219).ToString();

get more help from below link

Report Abuse
Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by AVADHESH PATELRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 2827
Advertisement
MindStick SurveyManager
Advertise with Us
  
Copyright © 2013MindStick. All Rights Reserved.