C# CRUD Operations Insert,Update,Delete with MySQL Database

C# tutorial for beginners : How to create simple applications CRUD operation example Insert, Update, Delete in DataGridView C# with MySQL Database.

C# (Csharp) Tutorial for beginners - How to Edit, Update, Delete DataGridview in C# windows form? how to make CRUD example using MySQL database with ODBC connection in C# Windows Form programming languages? Today i will show you how to make simple applications using C# and MySQL Database and sure you can download full source code made from visual studio 2015.

What we needs to be prepared before you start making this application? before you must have a database (In this tutorial using MySQL database), make a connection to the database, so please read :
How to Create database with MySQL?
How to create connection using MySQL Database?

Create CRUD Operations Project

Create new project and make name with "SimpleCrudCsharp", then at the form1.cs just design as needed look like this image :
CRUD Operations Insert,Update,Delete with MySQL Database

After design our Form1.cs, we will start write line by line our code to create simple CRUD operations MySQL Database, Double click on the Form1.cs and first, we will import ODBC namespaces to our Project.
// we will create a connection
//to our project using ODBC class
using System.Data.Odbc;

Declaration Our Connection and new data in the bottom of Project Class

        // its for our connection
        public OdbcConnection connection = new OdbcConnection("DSN=java_db;MultipleActiveResultSets=True;");
        // declaration for NewData
        public Boolean NewData;

Bind Data Into DataGridView

        private void LoadData() {
            // create connection before
            //open our connection
            connection.Open();
            // query using dataadapter into our database
            OdbcDataAdapter da = new OdbcDataAdapter("SELECT * FROM biodata order by id",connection);
            // we will using datatable to bing data into datagridview
            DataTable dt = new DataTable();
            da.Fill(dt);
            // bind data into gridview
            dataGridView1.DataSource = dt;
            // close connections
            connection.Close();
            da.Dispose();
            dt.Dispose();
        }

Set TextBox Value from Datagridview Selected Value

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
            // value from datagrid where clicked cells is same in the textbox
            DataGridViewRow rows = dataGridView1.Rows[e.RowIndex];
            textBox1.Text = rows.Cells[0].Value.ToString();
            textBox2.Text = rows.Cells[1].Value.ToString();
            textBox3.Text = rows.Cells[2].Value.ToString();
            textBox4.Text = rows.Cells[3].Value.ToString();
            textBox5.Text = rows.Cells[4].Value.ToString();
            // new data is false if textbox not null
            NewData = false;
        }

Clear TextBox

        private void ClearText() {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox2.Focus();
        }

Function for Insert, Update and Delete Data

        private void UpdateData(string sql) {
            try {
                // open connection
                connection.Open();
                // we will using OdbC command
                OdbcCommand cmd = new OdbcCommand();
                cmd.Connection = connection;
                cmd.CommandText = sql;
                cmd.CommandType = CommandType.Text;
                // execute
                cmd.ExecuteNonQuery();
                // show message if update data is success
                MessageBox.Show("Data Hasbeen Updated!","Informations");
                connection.Close();
                cmd.Dispose();

            } catch(Exception e) {
                MessageBox.Show(e.ToString());
            }
        }

Source Code Start Up Project

        private void Form1_Load(object sender, EventArgs e) {
            // declaration for newdata is true
            // if newData is true, we will Insert new data to database
            // if newdata is false, so we will Update data into database while data is eksisting
            NewData = true;
            LoadData();
            textBox1.Enabled = false;
        }

Source Code New Button (Button1)

        private void button1_Click(object sender, EventArgs e) {
            // its method for add new data,
            // we will declaration NewData to true if we want to add new data
            // if newdata= false, so we will Update while eksisting data
            NewData = true;
            ClearText();
        }

Source Code Save Button (Button 2)

       // its method for save or update data into database
        private void button2_Click(object sender, EventArgs e) {

            DialogResult Message;
            string SaveData = "";
            // if Newdata is True, so we will create query "UPDATE"
            // if newdata is False, we will create wuery "INSERT"
            if(NewData == true) {
                Message = MessageBox.Show("Are you sure to add new data into database?","Informations",MessageBoxButtons.YesNo);
                if(Message == DialogResult.No) {
                    return;
                } // SAVE DATA
                SaveData = "INSERT INTO biodata(nama,nis,kelas,alamat)VALUES('"+ textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
            } else {

                // UPDATE DATA
                SaveData = "UPDATE biodata SET nama='"+ textBox2.Text + "',nis='" + textBox3.Text + "',kelas='" + textBox4.Text + "',alamat='" + textBox5.Text + "' WHERE id='"+ textBox1.Text +"'";
            }
            // call functions to update or insert new data
            UpdateData(SaveData);
            // load datagridview with new data
            LoadData();
        }

Source Code Delete Button (Button 3)

        private void button3_Click(object sender, EventArgs e) {

            DialogResult Message;
            string delete = "";
            Message = MessageBox.Show("Are you sure to delete this data?","Warning",MessageBoxButtons.YesNo);
            if(Message == DialogResult.No) {
                // if users klick "NO" dialog, will exit the method and do nothing
                return;
            } else {
                // else, we will delete all data from selected id in TextBox1
                delete = "DELETE from biodata WHERE id='"+ textBox1.Text +"'";
                // call functions update data to execute the string query
                UpdateData(delete);
                LoadData();
            }
        }

Source Code Exit Button (Button 4)

        private void button4_Click(object sender, EventArgs e) {
            this.Close();
        }

Complete Source Code CRUD Example Project

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// we will create a connection
//to our project using ODBC class
using System.Data.Odbc; 

namespace SimpleCsharpCRUD {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
        // its for our connection
        public OdbcConnection connection = new OdbcConnection("DSN=java_db;MultipleActiveResultSets=True;");
        // declaration for NewData
        public Boolean NewData;
        private void Form1_Load(object sender, EventArgs e) {
            // declaration for newdata is true
            // if newData is true, we will Insert new data to database
            // if newdata is false, so we will Update data into database while data is eksisting
            NewData = true;
            LoadData();
            textBox1.Enabled = false;
        }

        // load data from a datatable
        // you must have a database (MySQL Database) before.
        // i was have a database in my localhost
        // if you don't know how to create database? how to create connection with C#
        // link available in descriptions

        private void LoadData() {
            // create connection before
            //open our connection
            connection.Open();
            // query using dataadapter into our database
            OdbcDataAdapter da = new OdbcDataAdapter("SELECT * FROM biodata order by id",connection);
            // we will using datatable to bing data into datagridview
            DataTable dt = new DataTable();
            da.Fill(dt);
            // bind data into gridview
            dataGridView1.DataSource = dt;
            // close connections
            connection.Close();
            da.Dispose();
            dt.Dispose();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
            // value from datagrid where clicked cells is same in the textbox
            DataGridViewRow rows = dataGridView1.Rows[e.RowIndex];
            textBox1.Text = rows.Cells[0].Value.ToString();
            textBox2.Text = rows.Cells[1].Value.ToString();
            textBox3.Text = rows.Cells[2].Value.ToString();
            textBox4.Text = rows.Cells[3].Value.ToString();
            textBox5.Text = rows.Cells[4].Value.ToString();
            // new data is false if textbox not null
            NewData = false;
        }

        private void ClearText() {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox2.Focus();
        }

        private void button1_Click(object sender, EventArgs e) {
            // its method for add new data,
            // we will declaration NewData to true if we want to add new data
            // if newdata= false, so we will Update while eksisting data
            NewData = true;
            ClearText();
        }

        // Functions for SAVE,UPDATE,DELETE data into database
        private void UpdateData(string sql) {
            try {
                // open connection
                connection.Open();
                // we will using OdbC command
                OdbcCommand cmd = new OdbcCommand();
                cmd.Connection = connection;
                cmd.CommandText = sql;
                cmd.CommandType = CommandType.Text;
                // execute
                cmd.ExecuteNonQuery();
                // show message if update data is success
                MessageBox.Show("Data Hasbeen Updated!","Informations");
                connection.Close();
                cmd.Dispose();

            } catch(Exception e) {
                MessageBox.Show(e.ToString());
            }
        }

        // its method for save or update data into database
        private void button2_Click(object sender, EventArgs e) {

            DialogResult Message;
            string SaveData = "";
            // if Newdata is True, so we will create query "UPDATE"
            // if newdata is False, we will create wuery "INSERT"
            if(NewData == true) {
                Message = MessageBox.Show("Are you sure to add new data into database?","Informations",MessageBoxButtons.YesNo);
                if(Message == DialogResult.No) {
                    return;
                } // SAVE DATA
                SaveData = "INSERT INTO biodata(nama,nis,kelas,alamat)VALUES('"+ textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
            } else {

                // UPDATE DATA
                SaveData = "UPDATE biodata SET nama='"+ textBox2.Text + "',nis='" + textBox3.Text + "',kelas='" + textBox4.Text + "',alamat='" + textBox5.Text + "' WHERE id='"+ textBox1.Text +"'";
            }
            // call functions to update or insert new data
            UpdateData(SaveData);
            // load datagridview with new data
            LoadData();
        }

        private void button3_Click(object sender, EventArgs e) {

            DialogResult Message;
            string delete = "";
            Message = MessageBox.Show("Are you sure to delete this data?","Warning",MessageBoxButtons.YesNo);
            if(Message == DialogResult.No) {
                // if users klick "NO" dialog, will exit the method and do nothing
                return;
            } else {
                // else, we will delete all data from selected id in TextBox1
                delete = "DELETE from biodata WHERE id='"+ textBox1.Text +"'";
                // call functions update data to execute the string query
                UpdateData(delete);
                LoadData();
            }
        }
        private void button4_Click(object sender, EventArgs e) {
            this.Close();
        }
    }
}

Video C# CRUD MySQL Database Tutorials



Time to Debug your simple application, press "F5" and let me know what happening to our project with writing your comment on the Comment box bellow.

Information :

  1. Download Example Project Database CRUD Operations
  2. Download Full source code CRUD Operation MySQL Database

COMMENTS

Next Recomended


Feel free to code it up and send us a pull request.

Hi everyone, let's me know how much this lesson can help your work. Please Subscribe and Follow Our Social Media 'kodeajaib[dot]com' to get Latest tutorials and will be send to your email everyday for free!, Just hit a comment if you have confused. Nice to meet you and Happy coding :) all ^^



Follow by E-Mail


Name

ADO.NET,3,Ajax,6,Android,9,AngularJS,4,ASP.NET,4,Blogger Tutorials,7,Bootstrap,7,C++,1,Codeigniter,2,Cplusplus,6,Crystal Report,6,CSharp,25,Ebook Java,2,FlyExam,1,FSharp,3,Game Development,2,Java,35,JDBC,2,Laravel,84,Lumen,2,MariaDB,2,Ms Access,3,MySQL,31,ODBC,6,OleDB,1,PHP,14,PHP Framework,5,PHP MYSQLI,9,PHP OOP,5,Python,8,Python 3,4,SQL Server,4,SQLite,4,Uncategorized,5,Vb 6,2,Vb.Net,89,Video,48,Vue Js,4,WPF,2,Yii,3,
ltr
item
KODE AJAIB: C# CRUD Operations Insert,Update,Delete with MySQL Database
C# CRUD Operations Insert,Update,Delete with MySQL Database
C# tutorial for beginners : How to create simple applications CRUD operation example Insert, Update, Delete in DataGridView C# with MySQL Database.
https://3.bp.blogspot.com/-w75hY4ug9qg/V1GyXqQRcdI/AAAAAAAAB5A/dPTa_be6X1EJ_o1Q3NExcVuCb-R8o8znwCLcB/s320/crud-operations-c-sharp-mysql-database.jpg
https://3.bp.blogspot.com/-w75hY4ug9qg/V1GyXqQRcdI/AAAAAAAAB5A/dPTa_be6X1EJ_o1Q3NExcVuCb-R8o8znwCLcB/s72-c/crud-operations-c-sharp-mysql-database.jpg
KODE AJAIB
https://www.kodeajaib.com/2016/06/c-crud-operations-insertupdatedelete.html
https://www.kodeajaib.com/
https://www.kodeajaib.com/
https://www.kodeajaib.com/2016/06/c-crud-operations-insertupdatedelete.html
true
3214704946184383982
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy