Skip to main content

Insert, update, delete, display, navigate in datagridview and download datagridview data in csv file

Insert, update, delete, display, navigate in datagridview and download datagridview data in csv file using C#

Below is the project which will demonstrates
1) how to insert, update, delete and display data in datagridview in C#. Also,

2) it will show navigate to records like navigate to first, last, previous and next record. In addition,

3) If we click on any record present in datagridview then it will display the corresponding record in number of textboxes. And Finally and most           important,

4) It will save all the records into csv file.

Below is the Design view of the project:




Below is the source code of the 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;
using System.IO;
using MySql.Data.MySqlClient;
namespace my_first_database_demo
{
    public partial class Form1 : Form
    {
        MySqlConnection con = new MySqlConnection("server=localhost;uid=root;pwd=root;database=test");
        MySqlCommand cmd;

        MySqlDataAdapter adp;

        int ID = 0;
        DataTable dt = new DataTable();

        public void DisplayData()
        {
            con.Open();
            DataTable dt = new DataTable();
            adp = new MySqlDataAdapter("select * from dept", con);
            adp.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }

        private void ClearData()
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            ID = 0;
        }

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //insert logic
            if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
            {
                cmd = new MySqlCommand("insert into dept(deptno, deptname, deptloc) values(@deptno,@deptname,@deptloc)", con);
                con.Open();
                cmd.Parameters.AddWithValue("@deptno", textBox1.Text);
                cmd.Parameters.AddWithValue("@deptname", textBox2.Text);
                cmd.Parameters.AddWithValue("@deptloc", textBox3.Text);
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {

                    MessageBox.Show("Error" + ex);
                }
                con.Close();
                MessageBox.Show("Record Inserted Successfully");
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Provide Details!");
            }

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            DisplayData();
        }

        private void button2_Click(object sender, EventArgs e)
        {
         
        }

        private void button3_Click(object sender, EventArgs e)
        {
         

        }



        private void button4_Click(object sender, EventArgs e)
        {
         
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //previous
            int prev = dataGridView1.CurrentRow.Index - 1;
            if (prev >= 0)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[prev].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            // Next
            int next = dataGridView1.CurrentRow.Index + 1;
            if (next < dataGridView1.Rows.Count)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[next].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button7_Click(object sender, EventArgs e)
        {
            //last
            int i = dataGridView1.Rows.Count - 1;
            if (i < dataGridView1.Rows.Count)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }
        }
        private void button8_Click(object sender, EventArgs e)
        {
            //data download in csv file logic

                    }
        public void ExportGridToCSV()
        {

            string filename = "";
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "CSV (*.csv)|*.csv";
            sfd.FileName = "Output.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("Data will be exported and you will be notified when it is ready.");
                if (File.Exists(filename))
                {
                    try
                    {
                        File.Delete(filename);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
                    }
                }
                int columnCount = dataGridView1.ColumnCount;
                string columnNames = "";
                string[] output = new string[dataGridView1.RowCount + 1];
                for (int i = 0; i < columnCount; i++)
                {
                    columnNames += dataGridView1.Columns[i].Name.ToString() + ",";
                }
                output[0] += columnNames;
                for (int i = 1; (i - 1) < dataGridView1.RowCount; i++)
                {
                    for (int j = 0; j < columnCount; j++)
                    {
                        try
                        {
                            output[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";
                        }
                        catch (Exception ex)
                        {
                            //  MessageBox.Show("Error"+ex);
                        }
                    }
                }
                System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
                MessageBox.Show("Your file was generated and its ready for use.");
            }
        }
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                //gets a collection that contains all the rows
                DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
                //populate the textbox from specific value of the coordinates of column and row.
                textBox1.Text = row.Cells[0].Value.ToString();
                textBox2.Text = row.Cells[1].Value.ToString();
                textBox3.Text = row.Cells[2].Value.ToString();

            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            DisplayData();
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            //Update logic
            if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
            {
                cmd = new MySqlCommand("update employee set deptname=@deptname,deptloc=@deptloc where deptno=@deptno", con);
                con.Open();
                cmd.Parameters.AddWithValue("@deptno", textBox1.Text);
                cmd.Parameters.AddWithValue("@deptname", textBox2.Text);
                cmd.Parameters.AddWithValue("@deptloc", textBox3.Text);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record Updated Successfully");
                con.Close();
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Select Record to Update");
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            //Delete logic is not working yet


            cmd = new MySqlCommand("delete from dept where deptno=@deptno", con);
            con.Open();
            cmd.Parameters.AddWithValue("@deptno", textBox1.Text);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Record Deleted Successfully!");
            DisplayData();
            ClearData();
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            //first
            int i = 0;
            this.dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[dataGridView1.CurrentCell.ColumnIndex];
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            //previous
            int prev = dataGridView1.CurrentRow.Index - 1;
            if (prev >= 0)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[prev].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }
        }

        private void button7_Click_1(object sender, EventArgs e)
        {
            // Next
            int next = dataGridView1.CurrentRow.Index + 1;
            if (next < dataGridView1.Rows.Count)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[next].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }
        }

        private void button8_Click_1(object sender, EventArgs e)
        {
            //last
            int i = dataGridView1.Rows.Count - 1;
            if (i < dataGridView1.Rows.Count)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }

        }

        private void dataGridView1_CellClick_1(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                //gets a collection that contains all the rows
                DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
                //populate the textbox from specific value of the coordinates of column and row.
                textBox1.Text = row.Cells[0].Value.ToString();
                textBox2.Text = row.Cells[1].Value.ToString();
                textBox3.Text = row.Cells[2].Value.ToString();

            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            ExportGridToCSV();

        }
    }
}

Below is the Database table for the project:






Comments

Popular posts from this blog

Add, remove, search an item in listview in C#

Below is the C# code which will help you to add, remove and search operations on listview control in C#. Below is the design view of the project: Below is the source code of the 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; namespace Treeview_control_demo {     public partial class Form2 : Form     {         public Form2()         {             InitializeComponent();             listView1.View = View.Details;                   }         private void button1_Click(object sender, EventArgs e)         {             if (textBox1.Text.Trim().Length == 0)...

MySQL practical Tutorials part 9- SQL not operator, SQL Not Like, SQL greater than, SQL less than greater than operator

 ========================================================================= Not Equal SELECT title FROM books WHERE released_year = 2017;   SELECT title FROM books WHERE released_year != 2017;   SELECT title, author_lname FROM books;   SELECT title, author_lname FROM books WHERE author_lname = 'Harris';   SELECT title, author_lname FROM books WHERE author_lname != 'Harris'; ========================================================================= Not Like SELECT title FROM books WHERE title LIKE 'W';   SELECT title FROM books WHERE title LIKE 'W%';   SELECT title FROM books WHERE title LIKE '%W%';   SELECT title FROM books WHERE title LIKE 'W%';   SELECT title FROM books WHERE title NOT LIKE 'W%'; ========================================================================= Greater Than SELECT title, released_year FROM books ORDER BY released_year;   SELECT title, released_year FROM books  WHERE released_year > 2000 ORDER BY release...

MULTIPLEXER , Design & Implement the given 4 variable function using IC74LS153. Verify its Truth-Table

TITLE: MULTIPLEXER   AIM: Design & Implement the given 4 variable function using IC74LS153. Verify its Truth-Table.   LEARNING OBJECTIVE: ·        To learn about IC 74153 and its internal structure. ·        To realize 8:1 MUX and 16:1 MUX using IC 74153.   COMPONENTS REQUIRED: IC 74153, IC 7404, IC 7432, CDS, wires, Power supply. IC PINOUT:            1)     IC 74153 2)      IC 7404:                                              3) IC 7432 THEORY:   ·        Multiplexer is a combinational circuit that is one of the most widely used in digital design. ·        The multiplexer is a data selector which gates one out of several inputs to a sin...