Situatie
Cum ne conectam la baza de date MySQL si afisam datele intr-un DataGridView C#.
Solutie
Pasi de urmat
Se instaleaza MySQL .Net Connector si se adauga referinta in proiect
Descarcare: https://dev.mysql.com/downloads/connector/net/6.10.html
In Project Explorer se acceseaza “Form1” cu “DubluClick”, din “ToolBox” se face “Drag&Drop” la “DataGridView” pe “Form1”
Se adauga cod pe “Form1”
Se sterge tot codul (generat) si se adauga urmatorul cod:
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Clienti
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Sirul de conectare – modificati IP_SERVER, DATABASE, USER_DB, PASS_DB.
string conString = @”server=IP_SERVER;database=DATABASE;uid=USER_DB;pwd=PASS_DB;”;
using (MySqlConnection con = new MySqlConnection(conString))
{
//Selectare tabela (va trebui sa creati in baza de date tabela “tabela_clienti” sau sa modificati selectul de mai jos.
using (MySqlCommand cmd = new MySqlCommand(“SELECT * FROM tabela_clienti”, con))
{
cmd.CommandType = CommandType.Text;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
//Se populeaza dataGridView1
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
}
}
Leave A Comment?