Thursday 19 April 2012

How to Insert, Edit, Update and Delete Data in DataGridView using Windows Form C#.Net.

To implement this concept you need to follow the below steps :

Step1 :
First you need to design a table in Sql Database to insert and retrieve the records in database.

Step2:
On the File menu, click New Project. Select Windows Forms Application as your project type.
Design the Form using controls from Toolbox.

Step3:
Now open the Form.cs page and write the following source code.

Form.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.Configuration;
using System.Data.SqlClient;

namespace savedatatomdf
{
    public partial class Form1 : Form
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sqlcon"].ConnectionString);
        public Form1()
        {
            InitializeComponent();
            Bind();

        }

        private void Clear()
        {
            txtName.Text = string.Empty;
            txtLocation.Text = string.Empty;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Insert Into Test_Data(Name,Location) Values (@Name,@Location)", con);
            cmd.Parameters.AddWithValue("Name", txtName.Text);
            cmd.Parameters.AddWithValue("Location", txtLocation.Text);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Inserted sucessfully");
            Bind();
            Clear();
        }

        private void Bind()
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select * from Test_Data", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlCommand delcmd = new SqlCommand();
            if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
            {
                delcmd.CommandText = "DELETE FROM Test_Data WHERE ID=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
                con.Open();
                delcmd.Connection = con;
                delcmd.ExecuteNonQuery();
                con.Close();
                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                MessageBox.Show("Row Deleted");
            }
            Bind();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Update Test_Data set Name=@Name,Location=@Location Where(Name=@Name)", con);
            cmd.Parameters.AddWithValue("@Name", txtName.Text);
            cmd.Parameters.AddWithValue("@Location", txtLocation.Text);
            cmd.ExecuteNonQuery();
            MessageBox.Show("updated......");
            con.Close();
            Bind();
            Clear();
        }

        private void btnEdit_Click_1(object sender, EventArgs e)
        {
            int i;
            i = dataGridView1.SelectedCells[0].RowIndex;
            txtName.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
            txtLocation.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
        }
    }
}



Step4:
Now build the Solution and Debug it for the output.


Output :






17 comments:

  1. I want to delete the grid items without additional button outside grid,
    If i right click on a grid it should ask me for deletion of that row,
    I am using access db

    waiting for ur reply

    thank you

    ReplyDelete
  2. How to get right click button function in c# windows application,

    Is it possible or not, if yes means how, if no means why,

    ReplyDelete
  3. Not Working.So Pl give example source code(exe/source code)

    ReplyDelete
    Replies
    1. Try to use this code.

      private void dataGridView1_RowContextMenuStripNeeded(object sender, DataGridViewRowContextMenuStripNeededEventArgs e)
      {
      //Activate your row to pop up a menu
      e.ContextMenuStrip = contextMenuStrip1;
      rownum = e.RowIndex;
      }

      private void deleteRowToolStripMenuItem_Click(object sender, EventArgs e)
      {

      //Then delete row, and call update
      dt.Rows[rownum].Delete();
      dt.AcceptChanges(); //For batch updating in SQL, plz do adapter.Update(dt)
      }

      Delete
    2. k,;,,d;fdnmflnlslmlmlsmlskfmlmlfmlskfs

      Delete
  4. Nice Sridhar bayya....
    naku emina doubts untey mimmalini adagavacha bayya??/

    ReplyDelete
  5. when i delete any row... after that i want maintain the sequence of id number for eg. 1,2,3,4,5 and so on... i delete the 2 id record then move the third record on 2 position, 4th record move on 3rd position, and 5th record move on 4 position.... it may be happen or not if yes how to do that

    ReplyDelete
  6. when i go for connect to mysql >connect to database>chose data source > mysql data source> when i put data server name that windows hide so tell me any one plz help me

    ReplyDelete
  7. A simple and detailed datagridview tutorial in C# Datagridview tutorial

    ling

    ReplyDelete
  8. How to get right click button function in c# windows application.Please Let me know.

    Thanks

    ReplyDelete