There is any way to make this C# form DataGridView with MySQL, setup more simpler? In this example project i ‘m using a myDB database person table to fill the DataGridView, and handling CRUD methods.
This simple project is handling the persons in the database, you can add new person to the database, you can delete, update or read. I made the project as compact as I could, but I think it could be shorter and easier to understand.
In this case dt is my DataGridView name, I made a Query function to make it clearer and more understandable, and I’m updating the the mysql database with the help of the adapter and the command builder’s update function.
I’m iterating through the DataSet’s tables and updating every table. The name of the query will be the name of the table’s name in the DataSet.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySqlConnector;
namespace WPF_crud
{
public partial class Form1 : Form
{
const string con = "server=localhost;database=myDB;username=root;";
MySqlConnection connection= new MySqlConnection(con);
//act as a bridge between a DataSet and a MySQL database for retrieving and saving data
MySqlDataAdapter adapter;
//DataSet is storing the data what he gets from the adapter (in correct variable string,int,bool stb.) it can store multiple tables from a query
DataSet data = new DataSet();
//automatically generates SQL commands (such as SELECT, INSERT, UPDATE, DELETE)
MySqlCommandBuilder command = new MySqlCommandBuilder();
public void Query(string query, string queryName)
{
// Create a MySqlDataAdapter to fill a DataSet
adapter = new MySqlDataAdapter(query, connection);
command = new MySqlCommandBuilder(adapter);
data.Clear();
//fill the DataSet
adapter.Fill(data, queryName);
//fill the DataGridView with the DataSet specified table
dt.DataSource = data.Tables[queryName];
}
public Form1()
{
InitializeComponent();
//only for design not required
dt.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dt.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
Query("SELECT * FROM person where 1", "person");
}
private void btn_Save_Click(object sender, EventArgs e)
{
//update all Table in a DataSet
foreach (DataTable table in data.Tables)
{
adapter.Update(data, table.TableName);
}
Query("SELECT * FROM person where 1", "person");
}
private void btn1_Click(object sender, EventArgs e)
{
Query("SELECT * FROM person where age < 50", "query1");
}
private void btn2_Click(object sender, EventArgs e)
{
Query("SELECT * FROM person where age > 50", "query2");
}
private void btn3_Click(object sender, EventArgs e)
{
Query("SELECT * FROM person where name like '%a%'", "query2");
}
}
}