insert update delete edit in datagridview using c#

Advertisement
In this Article I will explain How to insert, update, edit, delete, clear using datagridview in C# from one Form to another Form.

We can see my Out Put looks like


In this example I am having Two Forms.



Now I am adding another form, Form2.cs and I designed my Form2.cs as shown below

After completion of UI design.
My Solution explorer looks as shown below.

I design my table with name Employee looks like this


For this table i written two stored procedures for Insert and update.

USE [dotnetdb]
GO

/****** Object:  StoredProcedure [dbo].[SP_InsertEmpinfo]    Script Date: 07/21/2013 15:09:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create procedure [dbo].[SP_InsertEmpinfo]
(
@EmpId nvarchar(50),
@EmpName nvarchar(50),
@EmpAddress nvarchar(50),
@EmpDesignation nvarchar(50)
)

As Begin

Insert into Employee (EmpId,EmpName,EmpAddress,EmpDesignation) values (@EmpId,@EmpName,@EmpAddress,@EmpDesignation)
end

GO


USE [dotnetdb]
GO

/****** Object:  StoredProcedure [dbo].[SP_UpdateEmpInfo]    Script Date: 07/21/2013 15:09:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create procedure [dbo].[SP_UpdateEmpInfo]


(
@Empid nvarchar(50),
@EmpName nvarchar(50),

@EmpAddress nvarchar(50),
@EmpDesignation nvarchar(50)

)

As Begin


update Employee set EmpName = @EmpName,EmpAddress = @EmpAddress,EmpDesignation = @EmpDesignation where Empid = @Empid

End

GO

After Creating Stored Procedure, I Written the code for Insert,Update,Edit,Delete,Clear. In Form1.cs and Form2.cs.

Form2.cs Code
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;
using System.Data.SqlClient;

namespace DatagridviewExample
{
    public partial class Form2 : Form
    {
        public static string Employeeid;

        SqlConnection con = new SqlConnection("Data Source = CHINNU;Initial Catalog = dotnetdb;Uid = sa;Password = password123;");

        public Form2()
            
        {

            if (Form1.empid != null)
            {

                Employeeid = Form1.empid;
            }
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Form1.empid))
            {
                
                con.Open();
                SqlCommand Command = new SqlCommand("Select * from employee where EmpId='" + Employeeid + "'", con);
                SqlDataReader Reader = Command.ExecuteReader();
                if (Reader.HasRows)
                {
                    if (Reader.Read())
                    {
                        txtempid.Text = Reader.GetValue(0).ToString();
                        txtempid.Enabled = false;
                        
                        txtempname.Text = Reader.GetValue(1).ToString();
                        txtempaddress.Text = Reader.GetValue(2).ToString();

                        txtdesignation.Text = Reader.GetValue(3).ToString();
                  
                    }
                    con.Close();
                }

            }
        }

        private void submit_Click(object sender, EventArgs e)
        {

            string empupdateid = txtempid.Text;
            if (empupdateid != Employeeid)
            {
                SqlCommand cmd = new SqlCommand("SP_InsertEmpinfo", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@EmpId", SqlDbType.NVarChar).Value = txtempid.Text;
                cmd.Parameters.Add("@EmpName", SqlDbType.NVarChar).Value = txtempname.Text;
                cmd.Parameters.Add("@EmpAddress", SqlDbType.NVarChar).Value = txtempaddress.Text;
                cmd.Parameters.Add("@EmpDesignation", SqlDbType.NVarChar).Value = txtdesignation.Text;
                con.Open();
                cmd.ExecuteNonQuery();
                lblmessage.Text = "Data inserted";
                con.Close();
            }

            else
            {
                SqlCommand cmd = new SqlCommand("SP_UpdateEmpInfo", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@EmpId", SqlDbType.NVarChar).Value = txtempid.Text;
                cmd.Parameters.Add("@EmpName", SqlDbType.NVarChar).Value = txtempname.Text;
                cmd.Parameters.Add("@EmpAddress", SqlDbType.NVarChar).Value = txtempaddress.Text;
                cmd.Parameters.Add("@EmpDesignation", SqlDbType.NVarChar).Value = txtdesignation.Text;
                con.Open();
                cmd.ExecuteNonQuery();
                lblmessage.Text = "Data Updated";
                con.Close();


            }

        }

        private void btnReset_Click(object sender, EventArgs e)
        {

            txtempname.Text = "";
            txtempaddress.Text = "";
            txtdesignation.Text = "";
           
                lblmessage.Text = "Data Cleared";
            

        }




    }
}



Form1.cs having datagridview with Edit and Delete LinkButtons.
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;
using System.Data.SqlClient;

namespace DatagridviewExample
{


    public partial class Form1 : Form
    {
         SqlConnection con = new SqlConnection("Data Source = CHINNU;Initial Catalog = dotnetdb;Uid = sa;Password = password123;");
        public static string empid;

        public string emp
        {
            get { return empid; }
            set { empid = value; }

        }
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            displayDataGridView();

            DataGridViewLinkColumn Editlink = new DataGridViewLinkColumn();
            Editlink.UseColumnTextForLinkValue = true;
            Editlink.HeaderText = "Edit";
            Editlink.DataPropertyName = "lnkColumn";
            Editlink.LinkBehavior = LinkBehavior.SystemDefault;
            Editlink.Text = "Edit";
            dataGridView1.Columns.Add(Editlink);

            DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn();
            Deletelink.UseColumnTextForLinkValue = true;
            Deletelink.HeaderText = "delete";
            Deletelink.DataPropertyName = "lnkColumn";
            Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
            Deletelink.Text = "Delete";
            dataGridView1.Columns.Add(Deletelink);

        }


        public void displayDataGridView()
        {


           
            
                SqlCommand cmd;
                cmd = new SqlCommand("select * from Employee", con);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];

                dataGridView1.AutoGenerateColumns = false;
                dataGridView1.AllowUserToAddRows = false;
                int i = 1;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    row.Cells["SNO"].Value = i;
                    i++;
                }


            

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 5)
            {

            
                     empid = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["EmpId"].Value);
                Form2 fm2 = new Form2();
                fm2.Show();
                
            }

            if (e.ColumnIndex == 6)
            {
                empid = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["EmpId"].Value);
                
                    SqlDataAdapter da = new SqlDataAdapter("delete from employee where EmpId = '"+empid+"'",con);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                  displayDataGridView();
                    dataGridView1.Refresh();
                
            }
        }
                 
        }
    }



App.Config:

    
  
After Completing all the steps Press F5.

OutPut:

Inserting the data with Label message.


The Data we inserted in Form2 it was displayed in Form1 as shown below.

Now if you want to Edit the Information,when we click on edit it shows form2.cs
I updated the EmpAdress from Us to America.

Now after Updating Form2 it will display Form1 with updated information.


Now if we click on delete the row will be deleted from the datagridview as well as from database as shown below in Datagridview.




Advertisements
SHARE

Unknown

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

57 comments:

  1. Very Nice and helpful too..

    but after updation my gridview is not updated..

    ReplyDelete
  2. dear sir/ma"am
    i have 2 button in gridview(edit and delete).edit button working properly but delete button not working properly.after deletion a row. the delete operation done by another cellindex not by delete button.

    ReplyDelete
  3. SIR..
    ,edit and delete link buttons,update,delete,binding data to grid view ,auto generate sno..is working..but how to insert data..

    ReplyDelete
  4. if i click edit it will show form2 ..then it will have auto generate key..and all field values will populated..and also i can update..by showing data updated..

    ReplyDelete
    Replies
    1. In your..example only how can i insert data..?? i came to know that updateid != empid....but how to insert i am getting ..every time i can update and delete

      Delete
    2. i mean i am not getting how to insert data..

      Delete
  5. Well I have a problem. Where you have named it empid I setted it as id and there's an error 'Example.Form1' does not contain a definition for 'id' '
    The other errors are "The name 'lblmessage' does not exist in the current context" , "The name 'con' does not exist in the current context"

    ReplyDelete
    Replies
    1. You have to change the name id on 'Example.Form1' also

      Delete
  6. Woow Nice.
    All working properly .........

    ReplyDelete
  7. on which way use add and clear button using stored procedures

    ReplyDelete
  8. I dont want the datas to be bind in textboxes for editing purpose.i just want to edit them inside gridview by clicking on them.please help.

    ReplyDelete
  9. Informative, i learned how to do insert, delete and update using C# from your blog, keep sharing...
    Regards,
    DOT NET Training in Chennai|DOT NET Course in Chennai

    ReplyDelete
  10. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information&its very useful to me...
    Android training in chennai
    Ios training in chennai

    ReplyDelete
  11. I'm freshers now I want to need an entry for IT For Dot Net Framework.The instructor gives some task how to insert date for dot net code delete for that data to him I'm not prepared not properly. I back again my home that task check for google search seen for our site your useful this information. If you want to be learning from automation testing tools reached and visit there for below web page.
    Selenium Training in Chennai

    ReplyDelete
  12. Franchise Opportunities@ https://franolaxy.com
    Franchise opportunities in India@ https://franolaxy.com
    Franchise Opportunities India@ https://franolaxy.com
    Brand Establishment@ https://franolaxy.com

    ReplyDelete
  13. Thanks a lot for sharing this with all of us, I like it and we can communicate. Do you need buy app ratings and reviews. To boost app ranking and double app downloads now.

    ReplyDelete

  14. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    java training in bangalore

    ReplyDelete
  15. It is interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving.very specific nice content.
    Thanks & Regards

    Digital marketing training in chennai | Embedded System Training in Chennai.

    ReplyDelete
  16. Thanks for posting useful information.You have provided an nice article, Thank you very much for this one.I hope this will be useful for many people and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article.very interesting to read..please sharing like this information.

    Matlab Training in Chennai | Java Spring Training in Chennai.

    ReplyDelete
  17. Nice post and this is a very interested and valuable posting.

    ME Projects Chennai | ME Project Centers Chennai.

    ReplyDelete
  18. Great Article...Thanks for sharing the best information.It was so good to read and useful to improve my knowledge as updated one.

    Android Training
    Android Training in Chennai

    ReplyDelete
  19. HTML dialect or else HTML codes can likewise be utilized to make usable structures and you have to pursue a few stages in filling these structures. https://edit-pdf.pdffiller.com/

    ReplyDelete
  20. I think things like this are really interesting. I absolutely love to find unique places like this. It really looks super creepy though!!
    machine learning course in Chennai

    machine learning certification in chennai

    top institutes for machine learning in chennai

    ReplyDelete
  21. Thank you so much for your information,its very useful and helful to me.Keep updating and sharing. Thank you.
    RPA training in chennai | UiPath training in chennai


    ReplyDelete
  22. Such a Great Article!! I learned something new from your blog. Amazing stuff. I would like to follow your blog frequently. Keep Rocking!!
    Blue Prism training in chennai | Best Blue Prism Training Institute in Chennai

    ReplyDelete
  23. Thanks for such a great article here. I was searching for something like this for quite a long time and at last, I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.AngularJS Training in Chennai | Best AngularJS Training Institute in Chennai

    ReplyDelete
  24. Given so much info in it, The list of your blogs are very helpful for those who want to learn more interesting facts. Keeps the users interest in the website, and keep on sharing more
    Our Credo Systemz Which is designed to offer you OpenStack Training skills required to kick-start your journey as an OpenStack Cloud Administrator.
    Please free to call us @ +91 9884412301 / 9600112302
    Openstack course training in Chennai | best Openstack course in Chennai | best Openstack certification training in Chennai | Openstack certification course in Chennai | openstack training in chennai omr | openstack training in chennai velachery | openstack training in Chennai | openstack course fees in Chennai | openstack certification training in Chennai | best openstack training in Chennai | openstack certification in Chennai

    ReplyDelete
  25. Wow!! Really a nice Article. Thank you so much for your efforts. Definitely, it will be helpful for others. I would like to follow your blog. Share more like this. Thanks Again.
    iot training in Chennai | Best iot Training Institute in Chennai

    ReplyDelete
  26. Great post! I am actually getting ready to across this information, It's very helpful for this blog. Also great with all of the valuable information you have Keep up the good work you are doing well.DevOps Training in Chennai | Best DevOps Training Institute in Chennai

    ReplyDelete
  27. Nice blog..! I really loved reading through this article. Thanks for sharing such a
    amazing post with us and keep blogging... Best React js training near me | React js training online

    ReplyDelete
  28. Online casino is the best solution to money issues the best online casino with us come in and win.

    ReplyDelete
  29. Thanks for such a great article here. I was searching for something like this for quite a long time and at last, I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.angularjs best training center in chennai | angularjs training in velachery | angularjs training in chennai | angularjs training in omr

    ReplyDelete
  30. Современная диодная лента по всем стандартам отличного качества я обычно беру у компании Ekodio

    ReplyDelete
  31. Its a good post and keep posting good article.its very interesting to read.
    Machine Learning in Chennai

    ReplyDelete
  32. Hi, I met one gambling site, new play online gambling real money it was very cool, it was fun and spent some time with the conclusion that there were no problems the very best site cool design, a bunch of slots and slot machines

    ReplyDelete
  33. This is a topic that is near to my heart. Thank you! Exactly where are your contact details though? His comment is here: Password Protect Folder It.

    ReplyDelete
  34. This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up machine learning certification

    ReplyDelete
  35. Nice post...Thanks for sharing useful information..

    Python training in Chennai/<a

    ReplyDelete