Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Tuesday 27 January 2015

Insert, Update and Delete Record in DataGridView C#

In this Article, we will learn How to Insert, Update and Delete Record in DataGridView in C# Windows Form Application. In Previous Post, we saw How to Create a simple Windows Form Login Application in C#.

Let's Begin:
1. Create a new Windows Form Application.
2. Create a Database (named as Sample). Add a Table tbl_Record. The following is the table schema for creating tbl_Record.
3. Create a form(named frmMain) and Drop Label, TextBox, Button and DataGridView control from  the ToolBox.
Now, Go to frmMain.cs code and add System.Data and System.Data.SqlClient namespace.
frmMain.cs Code:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InsertUpdateDeleteDemo
{
    public partial class frmMain : Form
    {
        SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
        SqlCommand cmd;
        SqlDataAdapter adapt;
        //ID variable used in Updating and Deleting Record
        int ID = 0;
        public frmMain()
        {
            InitializeComponent();
            DisplayData();
        }
        //Insert Data
        private void btn_Insert_Click(object sender, EventArgs e)
        {
            if (txt_Name.Text != "" && txt_State.Text != "")
            {
                cmd = new SqlCommand("insert into tbl_Record(Name,State) values(@name,@state)", con);
                con.Open();
                cmd.Parameters.AddWithValue("@name", txt_Name.Text);
                cmd.Parameters.AddWithValue("@state", txt_State.Text);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Inserted Successfully");
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Provide Details!");
            }
        }
        //Display Data in DataGridView
        private void DisplayData()
        {
            con.Open();
            DataTable dt=new DataTable();
            adapt=new SqlDataAdapter("select * from tbl_Record",con);
            adapt.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }
        //Clear Data
        private void ClearData()
        {
            txt_Name.Text = "";
            txt_State.Text = "";
            ID = 0;
        }
        //dataGridView1 RowHeaderMouseClick Event
        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
            txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        }
        //Update Record
        private void btn_Update_Click(object sender, EventArgs e)
        {
            if (txt_Name.Text != "" && txt_State.Text != "")
            {
                cmd = new SqlCommand("update tbl_Record set Name=@name,State=@state where ID=@id", con);
                con.Open();
                cmd.Parameters.AddWithValue("@id", ID);
                cmd.Parameters.AddWithValue("@name", txt_Name.Text);
                cmd.Parameters.AddWithValue("@state", txt_State.Text);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record Updated Successfully");
                con.Close();
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Select Record to Update");
            }
        }
        //Delete Record
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            if(ID!=0)
            {
                cmd = new SqlCommand("delete tbl_Record where ID=@id",con);
                con.Open();
                cmd.Parameters.AddWithValue("@id",ID);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Deleted Successfully!");
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Select Record to Delete");
            }
        }
    }
}
In the above code, I have created dataGridView1_RowHeaderMouseClick Event for updating and deleting the selected Record. When user click on the Row Header of any row then data present in the cell of the row is stored into the TextBoxes. DisplayData() method used to fill data in DataGridView. Clear() method clears the data present TextBox as well as in ID(int) variable.
Final Preview:
Hope you like it. Thanks.
[Download Source Code via Google Drive]

19 comments:

  1. Can you please, create a procedure to insert a image to SQLExpress database using C#? Thanks in advance.

    ReplyDelete
    Replies
    1. Thanks for your comment. I will post an Article on this topic within a week.

      Delete
    2. i want crud operation by using checkbox and radiobuttons.

      Delete
  2. Nice Application,great work.

    ReplyDelete
  3. Great Article. You Saved My Time.

    ReplyDelete
  4. Please Help Me (Database Name = CustomerSQL.mdf | Table = CustomerTB)

    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=CustomerSQL; Integrated Security=true;");
    SqlCommand cmd;


    //Insert Data
    private void btnSave_Click(object sender, EventArgs e)
    {
    if (txtNIC.Text != "" && txtLName.Text != "")
    {
    cmd = new SqlCommand("insert into CustomerTB(NIC,LName) values(@nic,@lastname)", con);
    con.Open();
    cmd.Parameters.AddWithValue("@nic", txtNIC.Text);
    cmd.Parameters.AddWithValue("@lastname", txtLName.Text);
    cmd.ExecuteNonQuery();
    con.Close();
    MessageBox.Show("Record Inserted Successfully");

    //ClearData();
    }
    else
    {
    MessageBox.Show("Please Provide Details!");
    }
    }


    "con" Not Open...
    Please How to Find Error???

    ReplyDelete
  5. hello sir apka code mujhe pasnd aya lakin vo gridview main se upper ke form id through pass nhi hota mera plese help mi
    my mail ID-dhanubeendale2311@gmail.com

    ReplyDelete
  6. InitializeComponent(); this function declare format

    ReplyDelete
  7. wow. it is indeed a great help for me as a leader on our group activity. thank you so much. :) :*

    ReplyDelete
  8. Hello. I can't get the
    dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)working.

    In your project it works fine, but when I copy the form contents to another form the event dont work.

    I've found that in the copied Form.resx file, two lines of code are missing in the dataGridView1 section:

    this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);
    this.dataGridView1.RowHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView1_RowHeaderMouseClick);

    How can I overcome this situation?
    Thanks in advance.
    Adriano

    ReplyDelete
  9. Sir why i can't update and delete the data on the datagridview? sir help me pls

    ReplyDelete
    Replies
    1. Hi, What kind of error you are getting while updating or deleting the record?

      Delete
  10. There is no error message, when I click on the record in the dgv, it should show in the table, this is not happening.

    ReplyDelete
  11. simply nice artcel thanks for haring follow

    ReplyDelete
  12. login and pick the image and display it in the main form plus the user name

    ReplyDelete

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook

Blog Archive