News
IBM to offer mobile security as a service IBM will start delivering mobile security-as-a-service (MaaS) through its own cloud infrastructure in India, a move that is expected to better address in-country data requirements... IBM Spectrum Computing: IBM has enlarged its portfolio of software-defined infrastructure solutions with cognitive features for workload management.  * LiFi internet technology has been introduced, the new type of wireless internet connection that gives 100 times faster than traditional WiFi -- Invented by Professor Harald Haas from the University of Edinburgh. * Sci. Rachid Yazami has developed a smart chip that charges smartphones in less than 10 minutes. BenQ has launched BlueCore projector - Consumer electronics major BenQ has launched its first BlueCore laser light source projector. For those unaware, devices with BlueCore laser technology have a high contrast output of 80000:1 with an extended lamp life and efficiency. *** 
  Mar 1 2015 9:10AM     Michael Ryan
  2 Comments    9162 Views  
Here Michael Ryan provided a short tutorial with example, How to perform Insert, Update and Delete in DataGridView control in Windows Forms Application using C#.
Database
For binding the gridview and to Perform other operations, First have to create a table in Microsoft SQL Server Database as shown below.
Creating a table
When creating a table make Identity Specification as true for column 'ID'.

Set the table name as shown below.
Stored Procedure
Execute the store procedure SP_Insert_Update_Empinfo to your Database.

CREATE procedure [dbo].[SP_Insert_Update_Empinfo]   
(   
@EmpId varchar(50),   
@EmpName varchar(50),   
@EmpDesg varchar(50),  
@EmpAge INT,  
@EmpAddress varchar(50),  
@EmpExp INT   
)   
As   
BEGIN   
  
DECLARE @Count INT  
SET @Count = (SELECT COUNT(*) FROM Employee WHERE ID=@EmpId)  
  
 IF(@Count = 0)  
  BEGIN  
   INSERT INTO Employee   
      (EmployeeName,EmployeeDesc,EmployeeAge,EmployeeAddress,EmployeeExperience) VALUES   
      (@EmpName, @EmpDesg, @EmpAge, @EmpAddress,@EmpExp)   
 END  
 ELSE  
  BEGIN  
   UPDATE Employee SET EmployeeName = @EmpName,EmployeeDesc =@EmpDesg, EmployeeAge=@EmpAge,  
      @EmpAddress = @EmpAddress,EmployeeExperience = @EmpExp WHERE ID = @Empid   
 END  
END

Adding a DataGridView to the Windows Form
Firstly you need to add a DataGridView control to the Windows Form from the Visual Studio ToolBox as shown below.

I have designed a Gridview form look like this
I have designed another form for Insert that look like this
After completion of UI design. My Solution explorer looks as shown below.
Namespaces
You will need to import the following namespace.

using System.Data;
using System.Data.SqlClient;

Binding of data to DataGridView and Insert, Update, Delete in C#
Form_Insert.cs Code
C#

namespace DemoApplication
{
    public partial class Form_Insert : Form
    {
        public static string Employeeid;
        SqlConnection con = new SqlConnection("server=SERVER_NAME;database=DB_NAME;uid=****;password=*****;");

        public Form_Insert()
        {
            if (Form_Grid.empid != null)
            {
                Employeeid = Form_Grid.empid;
            }

            InitializeComponent();
        }

        private void Form_Insert_Load(object sender, EventArgs e)
        {            
            if (!string.IsNullOrEmpty(Form_Grid.empid))
            {
                con.Open();
                SqlCommand Command = new SqlCommand("Select * from employee where Id='" + 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();
                        txtdesignation.Text = Reader.GetValue(2).ToString();
                        txtAge.Text = Reader.GetValue(3).ToString();
                        txtempaddress.Text = Reader.GetValue(4).ToString();
                        txtExp.Text = Reader.GetValue(5).ToString();                        
                    }
                    con.Close();
                }
            }
        }

        private void submit_Click_Click(object sender, EventArgs e)
        {

            SqlCommand cmd = new SqlCommand("SP_Insert_Update_Empinfo", 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("@EmpDesg", SqlDbType.NVarChar).Value = txtdesignation.Text;
            cmd.Parameters.Add("@EmpAge", SqlDbType.NVarChar).Value = txtAge.Text;
            cmd.Parameters.Add("@EmpAddress", SqlDbType.NVarChar).Value = txtempaddress.Text;
            cmd.Parameters.Add("@EmpExp", SqlDbType.NVarChar).Value = txtExp.Text;
            con.Open();
            cmd.ExecuteNonQuery();
            lblmessage.Text = "Query Executed Successfully..";
            con.Close();
        }

        private void btnReset_Click_Click(object sender, EventArgs e)
        {
            txtempid.Text = "";
            txtempname.Text = "";
            txtempaddress.Text = "";
            txtdesignation.Text = "";
            txtAge.Text = "";
            txtExp.Text = "";
            lblmessage.Text = "Data Cleared";

        }

        private void GoToGrid_Click(object sender, EventArgs e)
        {
            Form_Grid objForm_Grid = new Form_Grid();
            objForm_Grid.Show();
        }
    }
}

Form_Grid.cs Code
C#

namespace DemoApplication
{
    public partial class Form_Grid : Form
    {
        SqlConnection con = new SqlConnection("server=SERVER_NAME;database=DB_NAME;uid=***;password=****;");
        public static string empid;

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

        public Form_Grid()
        {

            InitializeComponent();
        }

        private void Form_Grid_Load(object sender, EventArgs e)
        {
            Form_Insert objForm_Insert = new Form_Insert();
            objForm_Insert.Close();
            objForm_Insert.Hide();

            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;           
        }       

        private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
       {
            if (e.ColumnIndex == 6)
            {
                empid = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["Id"].Value);
                Form_Insert fm2 = new Form_Insert();
                fm2.Show();
            }
            if (e.ColumnIndex == 7)
            {
                empid = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["Id"].Value);
                SqlDataAdapter da = new SqlDataAdapter("delete from employee where Id = '" + empid + "'", con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                displayDataGridView();
                dataGridView1.Refresh();
            }
        }
    }
}

Result
From the Form_Insert form, we can add Employee Details,
When clicks, Edit linkButton it will go to Form_Insert Form with appropriate Employee Details. We can edit employee details there.
I hope this page will helps to perform Insert, Update and Delete in DataGridView in Windows Forms Application. Thanks.
BackToTop
Comments


Vishwanath
Jun 7 2015 5:41AM
Nice article. Thanks
AnonymousUser
Jul 12 2018 3:00AM
YES IT HELPS M,E TO DO THE SAME

 
Search
Recent Posts
Create Amazon ElasticCache Using Memcached in CSharp
Oct 29 2018 12:09PM Posted By Amose
Get Google Map Lat Lng (Geo Point) By Pincode in C#
Oct 28 2018 12:09PM Posted By Pranav
Google URL Shortener in C#
Oct 20 2018 12:09PM Posted By Sanjay
Bind Gridview from CSV file in Asp.Net C#
Oct 5 2018 12:09PM Posted By Michael
Call WebService method from jQuery in every 1 minute
Sep 26 2018 12:09PM Posted By John
Gridview custom CSS in ASP.Net
Sep 14 2018 12:09PM Posted By Micheal Ryan
Read excel file and bind to Gridview in C#
Sep 10 2018 12:09PM Posted By Micheal
Tags
Follow us on Facebook
Follow us on Google +
Recent post in your Email inbox.
Enter your email address: