Advertisement
In this Article I will explain How to insert, update, edit, delete, clear using datagridview in C# from one Form to another Form.
In my previous articles I explained How to display data in datagridview, How to add auto generate SNo in datagridview and also How to add Edit and Deletelink buttons in datagridview.
In this example I am having Two Forms.
I designed Form1 looks like this, Please check my previouspost if you having any doubts
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 GOAfter 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.
Very Nice and helpful too..
ReplyDeletebut after updation my gridview is not updated..
yes
Deletedear sir/ma"am
ReplyDeletei 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.
SIR..
ReplyDelete,edit and delete link buttons,update,delete,binding data to grid view ,auto generate sno..is working..but how to insert data..
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..
ReplyDeleteIn 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
Deletei mean i am not getting how to insert data..
DeleteWell 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' '
ReplyDeleteThe other errors are "The name 'lblmessage' does not exist in the current context" , "The name 'con' does not exist in the current context"
You have to change the name id on 'Example.Form1' also
DeleteWoow Nice.
ReplyDeleteAll working properly .........
on which way use add and clear button using stored procedures
ReplyDeleteI 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.
ReplyDeleteInformative, i learned how to do insert, delete and update using C# from your blog, keep sharing...
ReplyDeleteRegards,
DOT NET Training in Chennai|DOT NET Course in Chennai
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.
ReplyDeleteSelenium Training in Chennai
I really enjoyed the post to sharing..
ReplyDeleteNo.1 Software Testing Training Institute in Chennai | Best Selenium Training Institute in Chennai | Java Training in Chennai
Franchise Opportunities@ https://franolaxy.com
ReplyDeleteFranchise opportunities in India@ https://franolaxy.com
Franchise Opportunities India@ https://franolaxy.com
Brand Establishment@ https://franolaxy.com
Thanks for sharing valuable information about dotnet framework..keep updating your information..
ReplyDeleteSoftware Testing Training Center in Chennai | | Best Selenium Training Institute in Chennai | RPA Training Institute in Chennai
great
ReplyDelete
ReplyDeleteNeeded to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
java training in bangalore
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.
ReplyDeleteThanks & Regards
Digital marketing training in chennai | Embedded System Training in Chennai.
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.
ReplyDeleteMatlab Training in Chennai | Java Spring Training in Chennai.
Nice post and this is a very interested and valuable posting.
ReplyDeleteME Projects Chennai | ME Project Centers Chennai.
Thanks for this kind of worthy information. this was really very helpful to me. keep continuing.
ReplyDeleteSpoken English Institutes in Bangalore
Spoken English Coaching Classes near me
English Speaking Classes in Bangalore
Spoken English Training Institute in Bangalore
Best Spoken English Coaching in Bangalore
English Speaking Course in Bangalore
English Spoking Coaching in Bangalore
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/
ReplyDeleteWonderful post. Thanks for taking time to share this information with us.
ReplyDeletePython courses in Chennai
Python Training in T.Nagar
Python and Django Training in Chennai
Blue Prism Training in Chennai
ccna Training in Chennai
Data Science Course in Chennai
Wonderful post. Thanks for taking time to share this information with us.
ReplyDeleteAngularjs Training in Chennai
Angularjs course in Chennai
Angular 6 Training in Chennai
AWS course in Chennai
Robotics Process Automation Training in Chennai
DevOps Certification Chennai
I think things like this are really interesting. I absolutely love to find unique places like this. It really looks super creepy though!!
ReplyDeletemachine learning course in Chennai
machine learning certification in chennai
top institutes for machine learning in chennai
Nice blog..! I really loved reading through this article. Thanks for sharing such a
ReplyDeleteamazing post with us and keep blogging... Best React js training near me | React js training online
Very Clear Explanation. Thank you to share this
ReplyDeleteRegards,
Data Science Course In Chennai
Data Science Course Training
Data Science Training in Chennai
Data Science Certification Course
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
ReplyDeleteIts a good post and keep posting good article.its very interesting to read.
ReplyDeleteMachine Learning in Chennai
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.
ReplyDeleteThanks for sharing this awesome content
ReplyDeletetop 10 biography health benefits bank branches offices in Nigeria dangers of ranks in health top 10 biography health benefits bank branches offices in Nigeria latest news ranking biography
Thanks for sharing this awesome content
ReplyDeletetop 10 biography health benefits bank branches offices in Nigeria dangers of ranks in health top 10 biography health benefits bank branches offices in Nigeria latest news ranking biography
Nice post...Thanks for sharing useful information..
ReplyDeletePython training in Chennai/<a
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.
ReplyDeleteSelenium Training in chennai | Selenium Training in anna nagar | Selenium Training in omr | Selenium Training in porur | Selenium Training in tambaram | Selenium Training in velachery
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.
ReplyDeleteCyber 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
Wonderful post. Thanks for taking time to share this information with us.
ReplyDeletejava training in chennai
java training in omr
aws training in chennai
aws training in omr
python training in chennai
python training in omr
selenium training in chennai
selenium training in omr
The article you presented here is really nice and there is no words to explain how you wrote this. Thank you and add more data in future.
ReplyDeletehardware and networking training in chennai
hardware and networking training in tambaram
xamarin training in chennai
xamarin training in tambaram
ios training in chennai
ios training in tambaram
iot training in chennai
iot training in tambaram
This comment has been removed by the author.
ReplyDeleteI have express a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon…
ReplyDeletehadoop training in chennai
hadoop training in velachery
salesforce training in chennai
salesforce training in velachery
c and c plus plus course in chennai
c and c plus plus course in velachery
machine learning training in chennai
machine learning training in velachery
Hi,
ReplyDeleteThank you for sharing informative post on your blog.
home network security router devices
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
ReplyDeletehttps://cuachongmuoiso1.blogspot.com/2020/11/cach-uoi-muoi-bang-tinh-dau-khuynh-diep.html
Thank for sharing such a nice post on your blog keep it up and share more.salesforce training in chennai
ReplyDeletesoftware testing training in chennai
robotic process automation rpa training in chennai
blockchain training in chennai
devops training in chennai
Thank you for sharing the post. promo codes
ReplyDeleteAmazing 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.
ReplyDeleteDevOps Training in Chennai
DevOps Course in Chennai
Vé máy bay Aivivu, tham khảo
ReplyDeleteve may bay di my gia re
vé máy bay tết
vé máy bay từ tpHCM đi San Francisco
ve may bay di Phap gia bao nhieu
vé máy bay đi Anh giá rẻ 2021
giá vé máy bay đi Los Angesles
combo du lịch đà nẵng 3 ngày 2 đêm
combo hà nội đà lạt 4 ngày 3 đêm
visa trung quốc 3 tháng
chi phí cách ly khách sạn
Awesome Blog with useful Concept. you shares such an Excellent Topic which I searched long days. Kindly Keep Blogging.
ReplyDeleteJava Training in Chennai
Java Course in Chennai
Thanks for sharing this.
ReplyDeleteRick Anderson
AMAZING SHARE!
ReplyDeleteELLA JAMES
Aivivu - đại lý chuyên vé máy bay trong nước và quốc tế
ReplyDeletevé máy bay đi Mỹ
đặt vé máy bay từ mỹ về việt nam
vé máy bay từ canada về việt nam giá rẻ
vé máy bay nhật việt
Giá vé máy bay Hàn Việt Vietjet
Vé máy bay từ Đài Loan về Việt Nam
vé máy bay tết 2022 pacific airlines
I have little bit confusion on these commands. After reading this post, I got clarification.
ReplyDeletebest digital marketing agency in dubai
This comment has been removed by the author.
ReplyDeleteYour artcile is truly fine, keep up writing.Top Real Estate Companies in Hyderabad
ReplyDeleteBest Real Estate Companies in Hyderabad
ReplyDeleteHey, I like your blog Please Checkout my website Advertising Agency in Hyderabad
ReplyDeleteRekordbox DJ 6.6.4 Crack is The modern software to arrange, create, mix, and extract music according to modern ideas. RekordBox Crack
ReplyDeleteMEGAsync 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
ReplyDeleteOur 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.
ReplyDeletedata science courses in malaysia
This is the best article that had ever read
ReplyDeletevirginia military divorce
Abogado Disputas Contratos Comerciales
İstanbul
ReplyDeleteSivas
Kırıkkale
Zonguldak
Iğdır
42A
malatya evden eve nakliyat
ReplyDeleteartvin evden eve nakliyat
kocaeli evden eve nakliyat
ankara evden eve nakliyat
düzce evden eve nakliyat
SİCU5
6CE17
ReplyDeleteKütahya Evden Eve Nakliyat
Bilecik Evden Eve Nakliyat
Sivas Lojistik
Düzce Parça Eşya Taşıma
Urfa Lojistik
35A0F
ReplyDeleteBursa Şehirler Arası Nakliyat
Siirt Evden Eve Nakliyat
Etimesgut Fayans Ustası
Hatay Şehirler Arası Nakliyat
Antalya Rent A Car
Osmaniye Lojistik
Ardahan Lojistik
Muğla Parça Eşya Taşıma
Sinop Şehir İçi Nakliyat
94AF1
ReplyDeleteSivas Parça Eşya Taşıma
Denizli Lojistik
Çerkezköy Ekspertiz
Artvin Şehirler Arası Nakliyat
MEME Coin Hangi Borsada
Binance Güvenilir mi
Urfa Parça Eşya Taşıma
Etimesgut Fayans Ustası
Ardahan Parça Eşya Taşıma
2233C
ReplyDeleteÇerkezköy Oto Boya
Iğdır Evden Eve Nakliyat
Tesla Coin Hangi Borsada
Bitfinex Güvenilir mi
Denizli Şehir İçi Nakliyat
Aptos Coin Hangi Borsada
Poloniex Güvenilir mi
Ardahan Evden Eve Nakliyat
Sivas Lojistik
8306E
ReplyDeleteBitcoin Çıkarma Siteleri
Bitcoin Nasıl Para Kazanılır
Cate Coin Hangi Borsada
Parasız Görüntülü Sohbet
Osmo Coin Hangi Borsada
Youtube Abone Hilesi
Onlyfans Beğeni Satın Al
Kripto Para Nasıl Kazılır
Likee App Beğeni Satın Al
73CA1
ReplyDeleteBinance Ne Zaman Kuruldu
Pi Network Coin Hangi Borsada
Binance Referans Kodu
Soundcloud Beğeni Satın Al
Nonolive Takipçi Hilesi
Referans Kimliği Nedir
Tiktok Takipçi Hilesi
Referans Kimliği Nedir
Dxgm Coin Hangi Borsada
9E6CF
ReplyDeletekredi kartı ile kripto para alma
canlı sohbet siteleri
gate io
bibox
bitrue
bingx
binance ne demek
canlı sohbet uygulamaları
kucoin
675C4
ReplyDelete----
----
----
----
matadorbet
----
----
----
----
Nice blog...Thanks for sharing...
ReplyDeleteBest embedded training in chennai| placement assurance in written agreement
A4B42
ReplyDeletegörüntülü şov whatsapp numarası