Vous êtes sur la page 1sur 6

Code C#.Net : Connexion. 2021/2022 Formateur : L.KARIM.

Codes C# Connexion Entre PC (Local=Client) et PC(Serveur)


L’application et la base de données
Version 2021_2022
Phase Classe
Création de la calsse de connexion (Exemple : CN_MID.CS)
 Zone Importation
using System.Data.SqlClient;
using System.Data;

 Dans la Classe CN_MID.CS


public SqlConnection con = new SqlConnection();
//POUR CHAQUE TABLE
public DataRow NewLigne;
public SqlCommandBuilder CmdBuild;
public SqlDataAdapter dtadapter = new SqlDataAdapter();
public DataSet dtset = new DataSet();
//Méthode Connecter
public void CONNECTER()
{
if (con.State == ConnectionState.Closed || con.State == ConnectionState.Broken)
{
con.ConnectionString = @"Data Source=Nom du Serveur;Initial Catalog=Nom BD;Integrated Security=True";
//Exemple
con.ConnectionString = @"Data Source=DESKTOP-J6T3CDK\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
con.Open();
}
}
//Méthode Déconnecter
public void DECONNECTER()
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
//Enregistrer et fermer la Classe CN_MID.CS
Phase 1 : Au niveau Interface
Zone Importation (Au Début de la page de code)
//Pour le fournisseur Ms SqlServer
using System.Data.SqlClient;
Phase 2 : Au niveau Interface
Zone Déclaration (Déclaration Au Début de la classe)
// Création de l’objet BD pour Eviter l’épuisement de la connexion Après public partial class
CN_MID BD = new CN_MID();
Phase 3 : Au niveau Interface
Evénement Load
BD.CONNECTER();
BD.dtadapter = new SqlDataAdapter("select * from TADH", BD.con);
BD.dtset = new DataSet();
BD.dtadapter.Fill(BD.dtset, "TADH");
G1.DataSource = BD.dtset.Tables["TADH"];
Codes Nouveau (Bouton)
L’application et la base de données
//Bounton Nouveau
ID.ResetText();
NOM.ResetText();
PRENOM.ResetText();

Codes Bouton Ajouter (Bouton Enregistrer)


L’application et la base de données
//Bouton Ajout
int sw=0,s;
for (s = 0;s<=this.G1.RowCount - 2;s++)
{
if( ID.Text == this.G1.Rows[s].Cells[0].Value.ToString())

1
Code C#.Net : Connexion. 2021/2022 Formateur : L.KARIM.
{
sw = 1;
}
}
if (sw == 0)
{
if (ID.Text != "" && NOM.Text != "" && PRENOM.Text != "")
{

BD.NewLigne = BD.dtset.Tables["TADH"].NewRow();
BD.NewLigne[0] = ID.Text;
BD.NewLigne[1] = NOM.Text;
BD.NewLigne[2] = PRENOM.Text;
BD.dtset.Tables["TADH"].Rows.Add(BD.NewLigne);
BD.CmdBuild = new SqlCommandBuilder(BD.dtadapter);
BD.dtadapter.InsertCommand = BD.CmdBuild.GetInsertCommand();
BD.dtadapter.Update(BD.dtset, "TADH");
MessageBox.Show("Ajout Avec Succes");
// BD.DECONNECTER();
}
else
{
MessageBox.Show("Vous Devez Remplir Tous Les Champs SVP");
}
}
else
{
MessageBox.Show("Référence Existe Déjà");
}
}
Recherche Unique (Quatre Méthodes)
Codes Recherché (Consultation)
L’application et la base de données
Méthode 1 : Contrôle TextBox (Bouton Evénement Click)
int sw = 0;
if (ID.Text != "")
{
for (int s = 0; s <= this.G1.RowCount - 2; s++)
{
if (ID.Text == this.G1.Rows[s].Cells[0].Value.ToString())
{
ID.Text = this.G1.Rows[s].Cells[0].Value.ToString();
NOM.Text = this.G1.Rows[s].Cells[1].Value.ToString();
PRENOM.Text = this.G1.Rows[s].Cells[2].Value.ToString();
MemoryStream ms = new MemoryStream((byte[])this.G1.Rows[s].Cells[3].Value);
pictureBox1.Image = Image.FromStream(ms);
sw = 1;
}

}
if (sw == 0)
{
MessageBox.Show("ID Introuvable");
}
}
else
{
MessageBox.Show("Vous Devez Remplir ID");
}

Méthode 2 : Boite de Message InputBox (Bouton Evénement Click)


Attention NB/
using Microsoft.VisualBasic;
Puis cochez Microsoft.VisualBasic dans réfécences.

string a;
a = Interaction.InputBox("entrer l'id a rechercher");

2
Code C#.Net : Connexion. 2021/2022 Formateur : L.KARIM.
for (int s = 0; s <= this.G1.RowCount - 2; s++)
{
if (a == this.G1.Rows[s].Cells[0].Value.ToString())
{
ID.Text = this.G1.Rows[s].Cells[0].Value.ToString();
NOM.Text = this.G1.Rows[s].Cells[1].Value.ToString();
PRENOM.Text = this.G1.Rows[s].Cells[2].Value.ToString();
MemoryStream ms = new MemoryStream((byte[])this.G1.Rows[s].Cells[3].Value);
pictureBox1.Image = Image.FromStream(ms);
sw = 1;
}
}
if (sw == 0)
{
MessageBox.Show("ID Introuvable");
}

Méthode 3 : Combo Box (Evénement C1_SelectedIndexChanged)


N.B. : Avant de saisir le Code de cette méthode veuillez saisir le code de rechargement des élèments
du Combo lors du démarrage de la Forme.

Etape 1 : code de rechargement des élèments du Combo


ID.Items.Clear();
for (int s = 0; s <= this.G1.RowCount - 2; s++)
{
ID.Items.Add(this.G1.Rows[s].Cells[0].Value.ToString());
}
Etape 2 : Evénement C1_SelectedIndexChanged
for (int s = 0; s <= this.G1.RowCount - 2; s++)
{
if (ID.Text == this.G1.Rows[s].Cells[0].Value.ToString())
{
ID.Text = this.G1.Rows[s].Cells[0].Value.ToString();
NOM.Text = this.G1.Rows[s].Cells[1].Value.ToString();
PRENOM.Text = this.G1.Rows[s].Cells[2].Value.ToString();
MemoryStream ms = new MemoryStream((byte[])this.G1.Rows[s].Cells[3].Value);
pictureBox1.Image = Image.FromStream(ms);
}
}

Méthode 4 : Grid (Evénement Grid_CellClick)


int ligneencours;
ligneencours = G1.CurrentRow.Index;
ID.Text = this.G1.Rows[ligneencours].Cells[0].Value.ToString();
NOM.Text = this.G1.Rows[ligneencours].Cells[1].Value.ToString();
PRENOM.Text = this.G1.Rows[ligneencours].Cells[2].Value.ToString();
MemoryStream ms = new MemoryStream((byte[])this.G1.Rows[ligneencours].Cells[3].Value);
pictureBox1.Image = Image.FromStream(ms);

Codes Modification (Bouton Modification)


L’application et la base de données
« Base de Données Local »
if (ID.Text == "" || NOM.Text == "" || PRENOM.Text == "")
{
MessageBox.Show("Merci de Remplir Tous Les Champs");
return;
}

bool SW = false;

for (int i = 0; i <= this.G1.RowCount - 2; i++)


{
if (ID.Text == this.G1.Rows[i].Cells[0].Value.ToString())
{
//effectuer la modification
SW = true;
BD.dtset.Tables["TADH"].Rows[i][1] = NOM.Text;
BD.dtset.Tables["TADH"].Rows[i][2] = PRENOM.Text;

3
Code C#.Net : Connexion. 2021/2022 Formateur : L.KARIM.
BD.dtset.Tables["TADH"].Rows[i][3] = imageToByteArray(this.pictureBox1.Image);
Random rnd;
int number;
rnd = new Random();
number = rnd.Next(999, 10000);
BD.dtset.Tables["TADH"].Rows[i][4] = number.ToString();
BD.CmdBuild = new SqlCommandBuilder(BD.dtadapter);
BD.dtadapter.UpdateCommand= BD.CmdBuild.GetUpdateCommand();
BD.dtadapter.Update(BD.dtset, "TADH");
MessageBox.Show("Employé Modifié Avec Succès");
break;
}
}
if (SW == false)
{
MessageBox.Show("ID NON VALIDE");
}
Codes Suppression (Bouton Suppression)
L’application et la base de données
if (ID.Text == "")
{
MessageBox.Show("Merci de Saisir ID");
return;
}

bool SW = false;

for (int i = 0; i <= this.G1.RowCount - 2; i++)


{
if (ID.Text == this.G1.Rows[i].Cells[0].Value.ToString())
{
SW = true;
BD.dtset.Tables["TADH"].Rows[i].Delete();
BD.CmdBuild = new SqlCommandBuilder(BD.dtadapter);
BD.dtadapter.DeleteCommand = BD.CmdBuild.GetDeleteCommand();
BD.dtadapter.Update(BD.dtset, "TADH");
MessageBox.Show("Employé Supprimé Avec Succès");
break;
}
}
if (SW == false)
{
MessageBox.Show("ID NON VALIDE");
}
}
Utilisation de la Fonction RND pour Générer le Mot de Passe
Random rnd;
int number;
rnd = new Random();
number = rnd.Next(999, 10000);
BD.NewLigne[N°Champ] = number.ToString();
E.Mail
L’application et la base de données
Phase 1 Au Début Insérer :
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
Phase 2 Insérer le Bloc de code pour l’envoi :
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("Mail Expéditeur", "Mot de Passe Mail Expéditeur");
MailMessage msg = new MailMessage();
msg.To.Add("Mail Destinataire");
msg.From = new MailAddress("Mail Expéditeur");

4
Code C#.Net : Connexion. 2021/2022 Formateur : L.KARIM.
msg.Body = "un Simple Test";
client.Send(msg);
MessageBox.Show("Mail Envoyé");
Exploitation Photo Dans une Table & Interface
AJOUT & MODIFICATION
Phase 1
Insérer un Champ Dans la Table Avec Type Varbinary(Max)
Phase 2 Code à Insérer au début de la Page de Codes.
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
Phase 3Code à InsérerForm_Load
N.B. :Avant d’insérer ce bloc de codes veuillez spécifier au niveau propriètés une image de BackgroundImage au
contrôle PictureBox1
pictureBox1.Image = pictureBox1.BackgroundImage;
pictureBox1.BackgroundImageLayout = ImageLayout.Stretch;
Phase 4 Code à Insérer Bouton Enregistrer (Ajout + Modification)
BD.NewLigne[N° Champ] = imageToByteArray(this.pictureBox1.Image);
N.B. : imageToByteArray est une Fonction que vous devez la créer (Phase 5)
Phase 5 Fonction imageToByteArray
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
Phase 6 Création de Bouton Parcourir
1. Insérer le Contrôle OpenFileDialog
2. Inserer le Bloc de Code Suivant (Bouton Parcourir)
this.openFileDialog1.FileName = "";
this.openFileDialog1.ShowDialog();
if (this.openFileDialog1.FileName !="")
this.pictureBox1.ImageLocation = this.openFileDialog1.FileName;
Exploitation Photo Dans une Table & Interface
RECHERCHE
MemoryStream ms = new MemoryStream((byte[])this.G1.Rows[N° Ligne].Cells[N° Champ].Value);
pictureBox1.Image = Image.FromStream(ms);

Site Web Images


www.pngfactory.net
www.icon8.net
Site Web Convertir Texte En Message Vocal
www.fromtexttospeech.com

PictureBox en format Circulaire


 Zone Importation
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Drawing;

 Dans la Classe CircularPictureBox.CS

public class CircularPictureBox : PictureBox


{
protected override void OnPaint(PaintEventArgs pe)
{
GraphicsPath g = new GraphicsPath();
g.AddEllipse(0, 0, ClientSize.Width, ClientSize.Height);
this.Region = new System.Drawing.Region(g);
base.OnPaint(pe);

5
Code C#.Net : Connexion. 2021/2022 Formateur : L.KARIM.
}
}

 Dans un Evénement : Exemple Load


System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
gp.AddEllipse(0, 0, pictureBox1.Width - 3, pictureBox1.Height - 3);
Region rg = new Region(gp);
pictureBox1.Region = rg;

 Code Pour Image Réctangulaire : Dans un Evénement : Exemple Load


Rectangle r = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
int d = 50;
gp.AddArc(r.X, r.Y, d, d, 180, 90);
gp.AddArc(r.X + r.Width - d, r.Y, d, d, 270, 90);
gp.AddArc(r.X + r.Width - d, r.Y + r.Height - d, d, d, 0, 90);
gp.AddArc(r.X, r.Y + r.Height - d, d, d, 90, 90);
pictureBox1.Region = new Region(gp);

Connexion Avec Base De Données Sous Système MySql

Phase Classe
Création de la calsse de connexion (Exemple : CN_MID.CS)
 Zone Importation
using MySql.Data.MySqlClient;
using System.Data

 Dans la Classe CN_MID.CS


public MySqlConnection con = new MySqlConnection();
//POUR CHAQUE TABLE
public DataRow NewLigne;
public MySqlCommandBuilder CmdBuild;
public MySqlDataAdapter dtadapter = new MySqlDataAdapter();
public DataSet dtset = new DataSet();
//Méthode Connecter
public void CONNECTER()
{
if (con.State == ConnectionState.Closed || con.State == ConnectionState.Broken)
{
con.ConnectionString = @"Server=localhost;port=3306;Database=Nom DB;UID=root;Password=root;";
con.Open();
}
}
//Méthode Déconnecter
public void DECONNECTER()
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
//Enregistrer et fermer la Classe CN_MID.CS

Vous aimerez peut-être aussi