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

Phani Kumar

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

69 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. 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
  11. Franchise Opportunities@ https://franolaxy.com
    Franchise opportunities in India@ https://franolaxy.com
    Franchise Opportunities India@ https://franolaxy.com
    Brand Establishment@ https://franolaxy.com

    ReplyDelete

  12. 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
  13. 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
  14. 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
  15. Nice post and this is a very interested and valuable posting.

    ME Projects Chennai | ME Project Centers Chennai.

    ReplyDelete
  16. 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
  17. 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
  18. 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
  19. 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
  20. Its a good post and keep posting good article.its very interesting to read.
    Machine Learning in Chennai

    ReplyDelete
  21. 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
  22. Nice post...Thanks for sharing useful information..

    Python training in Chennai/<a

    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.
    Selenium Training in chennai | Selenium Training in anna nagar | Selenium Training in omr | Selenium Training in porur | Selenium Training in tambaram | Selenium Training in velachery

    ReplyDelete
  24. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
    Cyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course

    ReplyDelete
  25. Dầu khuynh diệp có đuổi muỗi được không? Điều này có thể khiến những người có ý định sử dụng vật liệu này để đuổi muỗi quan tâm. Bởi không phải ai cũng có kinh nghiệm đuổi muỗi hiệu quả. Do đó, nếu bạn cũng có ý định đuổi muỗi bằng cách này. Mời các bạn tham khảo thông tin trong bài viết sau
    https://cuachongmuoiso1.blogspot.com/2020/11/cach-uoi-muoi-bang-tinh-dau-khuynh-diep.html

    ReplyDelete
  26. Amazing Article ! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  27. Awesome Blog with useful Concept. you shares such an Excellent Topic which I searched long days. Kindly Keep Blogging.

    Java Training in Chennai

    Java Course in Chennai

    ReplyDelete
  28. I have little bit confusion on these commands. After reading this post, I got clarification.
    best digital marketing agency in dubai

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. Your artcile is truly fine, keep up writing.Top Real Estate Companies in Hyderabad

    ReplyDelete
  31. Rekordbox DJ 6.6.4 Crack is The modern software to arrange, create, mix, and extract music according to modern ideas. RekordBox Crack

    ReplyDelete
  32. MEGAsync software utilizes a section called Power Management for your files transfer. You can apply the settings you need to transfer and synchronize your files by doing so.Mega Download Link

    ReplyDelete
  33. Our Data Science certification training with a unique curriculum and methodology helps you to get placed in top-notch companies. Avail all the benefits and become a champion.
    data science courses in malaysia

    ReplyDelete

Labels

.Net Interview Questions add custom button in sharepoint using javascript Add custom column property into a PageLayout in SharePoint Add Page Title on their browser's title bar in SharePoint Customly add zip files in blogger Add-SPOSiteCollectionAppCatalog : Must have Manage Web Site permissions or be a tenant admin in order to add or remove sites from the site collection app catalog allow list Advance SmartObject An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL. Angular 2 Angular JS Angularjs Angularjs 1 anonymous users accessing lists and libraries App Permissions for SharePoint 2013 asp.net membership unique email Asp.net TreeView Control asp.net. Attendees in SharePoint Auto refresh list using Content Editor WebPart in SharePoint 2013. Auto Refresh SharePoint list using JavaScript Block and unblock of attachment types in SharePoint Blogger C# Callouts in SharePoint 2013 Cascading Dropdown list in SharePoint change onenote to another location. change SuiteBarLeft in SharePoint 2013 check if userid exists in database c# click node text to expand/collapse in Treeview client object model Close webpart CQWP crate chart using BI site in PPS Create a modern team site collection in SharePoint online Create BI chart in PPS SharePoint 2013 create filter in dashboard designer. create kpi's in dashboard designer create kpi's in SharePoint 2013 dashboard designer Create List Create List In SharePoint Create List using Power Shell Script Create Lookup Field in List using Power Shell Script Create lookup field in List create SharePoint List custom view. create SharePoint List views in List Schema create site collection in site collection in SharePoint using powershell created Date Time calculated field in SharePoint Cross site Collection in SharePoint 2013 Crud Operation in Asp.net Using Stored Procedure Custom MasterPage Approval in SharePoint custom view for survey list Customly add SharePoint List view in Page. delete items in sharepoint using powershell Difference between Angular 1.x & Angular 2 difference between Office 365 and Windows Azure difference between Windows Azure and Office 365 in sharepoint? DifferenceBetween discussion board Display Data in Grid View display radio buttons and choice fields horizontally in SharePoint 2013 Document library DotNet Drag and drop documents in document library in SharePoint dynamically populating values from one list to another list using jquery in sharepoint edit and delete buttons in datagridview Edit Links email notification using Nintex enable anonymous access in SharePoint 2013 enable app catalog sharepoint online site collection powershell Enable appcatalog site collection level using PowerShell based on Input file Enable versions for list and library except the hidden lists using PowerShell Script Error occurred in deployment step 'Recycle IIS Application Pool': Cannot resolve model for the project package Errors&Solutions Export document library in sharepoint using powershell Export particular Group in Term Store Management in SharePoint 2013 Export to Excel first release Flow Flow features free disk space on servers using powershell Friendly URLs and Managed Navigation in SharePoint 2013 get a list of site collection with template in web application using PowerShell Script in SharePoint Get attachments in SharePoint custom list using c# get current list item id sharepoint programmatically Get current url using jquery Get data from SharePoint list using Rest api & Angular JS Get Random Get Random SharePoint items using PowerShell Get Random values from SharePoint list using PowerShell Get url of the last value using jquery Get-SPOSite : The managed path sites/yoursitename is not a managed path in this tenant. Getting Email From User Hide “Edit Links” in left navigation SharePoint 2013 hide button in sharepoint based on permissions Hide column in SharePoint List view hide fields using client side object model Hide list in Quick Launch in SharePoint using PowerShell How to add Custom Tiles to SharePoint site Page. How to add extension files in Search Navigation in SharePoint 2013 How to Add Multiple users Using SharePoint People Picker How to add SharePoint list view in Page using C# How to Approve MasterPage using PowerShell in SharePoint How to bind Multiple users Using SharePoint People Picker how to change indicators on kpi performance how to check if an email address already exists in the database in asp.net how to configure workflow manager platform for SharePoint 2013 how to create calculated value using powershell how to create certificate in SharePoint How to create flow. how to create gantt chart webpart in sharepoint how to create KPI indicators in Dashboard designer How to create moden communication site in SharePoint online How to create Multi selected filter in Dashboard How to create nintex workflow in sharepoint how to create rdlc reports in asp.net How to Display Data Grid View in ASP.net How to enable anonymous access in SharePoint How to find data in datagridview in c# How to get image names from the folder using C# how to get particular list content type id in SharePoint 2013 How to get QueryString value in SharePoint WebPart Programatically how to get the current item id for newly created item using REST API and JQuery how to hide list in sharepoint how to know who created list in sharepoint How to make a Site Collection Read-Only in SharePoint 2010 How to overlay Office 365 shared calendar on SharePoint Site how to pass jquery value to asp.net textbox control How to pass pagename as a browser's title bar in the page how to remove unused Application Pool in SharePoint how to remove zone using powershell script How to send mail to particular group of people using PowerShell how to update modified by and created by using powershell how to uplaod RAR files in blogger import csv data into sharepoint import data using powershell Import group to term store management using SharePoint 2013. InfoPath InfoPath Cascading Dropdown list Insert update delete in datagridview in C# winforms Integration from SharePoint to k2. K2 Smart Forms for SharePoint JavaScript Injection jquery JSON K2 blackpearl K2 Designer K2 Designer Workflow. K2 smartform cascading dropdown list k2 Workflow K2 workflow to send a mail with PDF left navigation Local Term Set in managed meta data Managed meta data navigation in SharePoint 2013 Managed metadata service in SharePoint 2013. Managed Navigation in SharePoint 2013. Managed Promoted Sites. meta data navigation Microsoft Flow New Features New-SPConfigurationDatabase The user does not exist or is not unique NintexWorkFlow Office 365 OneDrive OneNote overwrite existing document in sharepoint using javascript PDF Converter PDF Method in K2 Performance Point Service in SharePoint 2013 PerformancePoint Services Configurtion PerformancePoint Services Configurtion for SharePoint 2013 PerformancePoint Services in SharePoint Server 2013 Popularity trends in SharePoint 2013 Pages populate dropdown list dynamicallyusing jquery Power Power Automate Power Shell Power shell script to get SharePoint site size. PowerApps powershell read xml PowerShell Script PowerShell script to get list of users from SharePoint groups PowerShell Scripts in SharePoint 2013 Powershell to set the masterpage in SharePoint Promoted Links Promoted Sites psconfig.exe quick launch Rdlc reports Readonly Column in SharePoint Editview Realtime DotNet Interview Questions Recent Dotnet interview questions Recent SharePoint interview questions recover deleted OneNote page. OneNote content is missing Regional Settings in SharePoint 2013 Replace New Item text in SharePoint Rest API Schedule PowerShell Script Search in SharePoint 2013 Search navigation in SharePoint 2013 Secure store service SecureStore Services SecureStore Services configuration for SharePoint 2013 self-signed certificate on IIS Server Send email to members of SharePoint Group using PowerShell sharepint2010 sharepoin2010 SharePoint 2013 SharePoint 2010 SharePoint 2013 SharePoint 2013 Dashboard Designer SharePoint 2013 features SharePoint 2013 Interview Questions SharePoint 2013. SharePoint 2013.disable views from user to create SharePoint 2013.Power shell SharePoint 2013.SharePoint 2010 SharePoint 2016 SharePoint Administration SharePoint Alerts and Reminders SharePoint App Configuration SharePoint Apps SharePoint Bulk upload SharePoint Calculated field SharePoint Calendar View sharepoint interview questions SharePoint online interview questions SharePoint online training SharePoint Onprem vs Online SharePoint RealTime Online Training SharePoint2010 SharePoint2013 SharePoint2016 SharePointInterview SharePointOnline SharePointOnline;Restore deleted site;SharePoint 2013 show data in datagridview in C# Simple Insert update Delete Retrieve Clear in asp.net. Site Collection Operations in SharePoint 2013 Site Collection Read-Only in SharePoint 2013 site contents Sorting & Filtering SPO SPSite Site Collection Operation parameters in SharePoint 2013 Step by step to create rdlc report in .Net Store names in text files in C# Sub site Subsite Term store management. The server was unable to save the form at this time. please try again UI New look update created by using client side object model update field values in SharePoint using powershell update items in SharePoint list using client object model update modified by field using client side object model upload zip files in blog use IsNullOrEmpty in PowerShell VirtoSoftware VirtoSofware vitrosoftware WebParts what is Document Set in SharePoint 2010 What is Filter in SharePoint Dashboard what is Limited-access user permission lock down mode feature What is Modern Team site What is Target Audience in SharePoint Who Created Site Using PowerShell Workflow in SharePoint 2013 Workflow management platform in SharePoint 2013 Workflow manager for SharePoint 2013 XSL-Template.