Insert, Update and Delete Data using DataGridView and save changes to database:

GridView is a control that provides you a very easy way to insert update and delete data and save modifications to database. You only have to make changes in GridView and click the button changes will be saved to database. Here is an example which shows how to save changes to database.
·         Start a new WindowsFormApplication.
·         Make a connection with database.
·         Add a button on the form for inserting and updating data.
·         Add another button on the form which will delete record.
·         Add a DataGridView on the form located in Data section of toolbox.
·         Select the DataGridView and go to properties.
·         Change the name property of DataGridView to MyDataGridView.

Now here is the code for this example;

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 Data
{
    public partial class IUDForm : Form
    {

        private SqlConnection Con = new SqlConnection(@"Data Source=MINHAS-A65DA31B\SQLEXPRESS;Initial Catalog=class;Integrated Security=True");
      
        private SqlDataAdapter da;
        private DataTable dt;
        private SqlCommandBuilder sqlCommandBuilder = null;
        public ChildForm()
        {
            InitializeComponent();
        }



    //On the Form Load event show data in GridView
        private void IUDForm_Load(object sender, EventArgs e)
        {
            Con.Open();

            da = new SqlDataAdapter("select * from signin", Con);
            sqlCommandBuilder = new SqlCommandBuilder(da);
            dt = new DataTable();
            da.Fill(dt);
            MyDataGridView.DataSource = dt;
            Con.Close();
        }

        private void InsertUpdateBtn_Click(object sender, EventArgs e)
        {
            try
            {
                da.Update(dt);
                MessageBox.Show("Database updated");
            }
            catch (Exception se)
            {
                MessageBox.Show(se.Message);
            }
        }

        private void DeleteBtn_Click(object sender, EventArgs e)
        {
            try
            {


                MyDataGridView.Rows.RemoveAt(MyDataGridView.CurrentRow.Index);
                da.Update(dt);
                MessageBox.Show("Data deleted");
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }

        }
    }
}

Comments

Popular posts from this blog

Check if ViewBag is null or doesn't exist

Using Progress Bar In C#

Jquery serer side datatables in asp.net