• June 13, 2021

PHSARIT

Bring Technology Ideas with you

 Simple Select Data From MySQL Server into Datagridview using C#

Before we start to select data into Datagridview, please visit our previous post (Simple Connection to MySql Server using C#.net) about how your visual studio can work with Mysql Server. Go to your Window Form then design as below (you can design by your own way) ( Tools Label, Datagridview)

    Go go to your PHPMyAdmin then design the table as below

      Enter some data into the table

        Try the codes below!

        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 MySql.Data.MySqlClient;
        
        namespace SQL_Insert
        {
            public partial class Form1 : Form
            {
               MySqlConnection cn;
                public Form1()
                {
                    InitializeComponent();
                }
        
                private void Form1_Load(object sender, EventArgs e)
                {
                    //declare connection to mysql server
                    String StringConnection;
                    StringConnection = "server=localhost; userid=root; password=; database=pos;";
                    cn = new MySqlConnection(StringConnection);
                    try
                    {
                        cn.Open(); //open connection
                        MessageBox.Show("Connected successfully");
                    }
                    catch (Exception ex)
                    {
                        //if there is no connection, it will show
                        MessageBox.Show(ex.ToString());
                    }
                    //create sql select statement
                    string mysqlselectdata;
                    mysqlselectdata = "select * from tbl_product"; // select data from mysqlserver with the table name is tbl_product
                    MySqlDataAdapter Adapter = new MySqlDataAdapter(mysqlselectdata, cn); //put data into memory
                    MySqlCommandBuilder cmd = new MySqlCommandBuilder(Adapter); // execute table with filling from memory storing
                    DataTable table = new DataTable(); // create a new table to get data
                    Adapter.Fill(table); // fill data into the new table
                    dataGridView1.DataSource = table; // show table in datagridviews
                }
            }
        }
        

        Then Run your code, you should see the form get data as below:

          Related post