Complément Chapitre 6

36
Cours VB 2007/2008 1 Complément Chapitre 6 Les Bases de Données en VB Exemples

description

Complément Chapitre 6. Les Bases de Données en VB Exemples. Contrôles dépendants. Préparation de l’interface. Dim aj As Integer Private Sub cmdajouter_Click() aj = 1 Call MAJAffichage(Me, aj) DataEnvironment1.rsTAutor.AddNew txtNumAutorisation.SetFocus End Sub. - PowerPoint PPT Presentation

Transcript of Complément Chapitre 6

Page 1: Complément Chapitre 6

Cours VB 2007/2008 1

Complément Chapitre 6

Les Bases de Données en VB

Exemples

Page 2: Complément Chapitre 6

Cours VB 2007/2008 2

Contrôles dépendants

Page 3: Complément Chapitre 6

3 Cours VB – ISG 2007/2008

Préparation de l’interface

Dim aj As IntegerPrivate Sub cmdajouter_Click()aj = 1Call MAJAffichage(Me, aj)DataEnvironment1.rsTAutor.AddNewtxtNumAutorisation.SetFocusEnd Sub

Private Sub cmdmodifier_Click()If txtNumAutorisation <> "" Thenaj = 0Call MAJAffichage(Me, aj)txtNumAutorisation.SetFocusElseMsgBox "Rien à modifier"End IfEnd Sub

Page 4: Complément Chapitre 6

4 Cours VB – ISG 2007/2008

Validation & Annulation

Private Sub CmdValider_Click()DataEnvironment1.rsTAutor.UpdateCall MAJAffichage(Me, aj)‘If aj = 1 Then‘Call Actualiser()‘DataEnvironment1.rsTAutor.MoveLast‘End If‘ dans le cas où le numéro du champ est un numéro ‘automatiqueEnd Sub

Private Sub cmdAnnuler_Click()If aj = 0 ThenDataEnvironment1.rsTAutor.AddNewDataEnvironment1.rsTAutor.CancelUpdateElseDataEnvironment1.rsTAutor.CancelUpdateEnd IfCall MAJAffichage(Me, aj)End Sub

Page 5: Complément Chapitre 6

5 Cours VB – ISG 2007/2008

Suppression

Private Sub cmdsupprimer_Click()If DataEnvironment1.rsTAutor.RecordCount = 0 Then Exit SubIf MsgBox("Voulez vous supprimer", vbYesNo + vbQuestion, "GSC") = vbNo ThenExit SubEnd IfDataEnvironment1.rsTAutor.DeleteIf DataEnvironment1.rsTAutor.RecordCount > 0 ThenIf DataEnvironment1.rsTAutor.BOF ThenDataEnvironment1.rsTAutor.MoveFirstElseDataEnvironment1.rsTAutor.MovePreviousEnd ifElseDataEnvironment1.rsTAutor.AddNewDataEnvironment1.rsTAutor.CancelUpdateEnd IfEnd Sub

Page 6: Complément Chapitre 6

6 Cours VB – ISG 2007/2008

Mise à jour affichage

Sub MAJaffichage(frm As Form, aj As Integer)Dim Cont As VariantFor Each Cont In frm.Controls If TypeOf Cont Is TextBox Then If Cont.Tag = "" Then Cont.Locked = Not Cont.Locked ElseIf Cont.Tag <> "" And aj = 1 Then Cont.Locked = Not Cont.Locked End If End If 'If TypeOf cont Is CommandButton Then ' cont.Enabled = Not cont.Enabled 'End If If TypeOf Cont Is CommandButton Then Cont.Visible = Not Cont.Visible End IfNext ContEnd Sub

Page 7: Complément Chapitre 6

Cours VB 2007/2008 7

Contrôles indépendants

Page 8: Complément Chapitre 6

8 Cours VB – ISG 2007/2008

Préparation de l’interface

Dim aj As IntegerDim sauv as VariantPrivate Sub cmdajouter_Click()aj = 1sauv = DataEnvironment1.rsTAutor.bookmarkCall PerparerInterface(Me)Call MAJAffichage(Me, aj)txtNumAutorisation.SetFocusEnd Sub

Private Sub cmdmodifier_Click()If txtNumAutorisation <> "" Thenaj = 0Call MAJAffichage(Me, aj)sauv = DataEnvironment1.rsTAutor.bookmarktxtNumAutorisation.SetFocusElseMsgBox "Rien à modifier"End IfEnd Sub

Page 9: Complément Chapitre 6

9 Cours VB – ISG 2007/2008

Validation & Annulation

Private Sub CmdValider_Click()If aj =1 thenDataEnvironment1.rsTAutor.addnewendifCall AffecterValeur ()DataEnvironment1.rsTAutor.UpdateCall MAJAffichage(Me, aj)

‘ dans le cas où le numéro du champ est un numéro ‘automatique‘If aj = 1 Then‘Call actualiser()‘DataEnvironment1.rsTAutor.MoveLast‘sauv = DataEnvironment1.rsTAutor.bookmark‘Call afficherEnregistrement()‘End IfEnd Sub

Private Sub cmdAnnuler_Click()Call afficherEnregistrement()Call MAJAffichage(Me, aj)End Sub

Page 10: Complément Chapitre 6

10 Cours VB – ISG 2007/2008

Suppression

Private Sub cmdsupprimer_Click()If DataEnvironment1.rsTAutor.RecordCount = 0 Then Exit SubIf MsgBox("Voulez vous supprimer", vbYesNo + vbQuestion, "GSC") = vbNo ThenExit SubEnd IfDataEnvironment1.rsTAutor.DeleteIf DataEnvironment1.rsTAutor.RecordCount > 0 ThenIf DataEnvironment1.rsTAutor.BOF ThenDataEnvironment1.rsTAutor.MoveFirstElseDataEnvironment1.rsTAutor.MovePreviousEnd ifSauv = DataEnvironment1.rsTAutor.BookmarkCall afficherEnregisterment()ElseCall PreparerInterface()End IfEnd Sub

Page 11: Complément Chapitre 6

11 Cours VB – ISG 2007/2008

Préparation de l’interface

Sub PreparerInterface(frm as form)Dim Cont As VariantFor Each Cont In frm.Controls If TypeOf Cont Is TextBox Then Cont.Text = "" End IfNext ContEnd Sub

Page 12: Complément Chapitre 6

12 Cours VB – ISG 2007/2008

Sub AfficherEnregistrement ()With DataEnvironment1.rsTAutor .bookmark = sauvtxtNumAutorisation =.Fields("NumAutorisation")txtNature =.Fields("Nature")txtQtéAutorisation = .Fields("QtéAutorisation")End withEnd Sub

Sub AffecterValeur ()With DataEnvironment1.rsTAutor.Fields("NumAutorisation") = txtNumAutorisation.Fields("Nature") = txtNature.Fields("QtéAutorisation") = txtQtéAutorisationend withEnd Sub

Page 13: Complément Chapitre 6

13 Cours VB – ISG 2007/2008

Actualisation de recodeset (Requery)

Sub Actualiser()Dim C As Control ‘ Un contrôle générique pour parcourir la collection de contrôles de feuille

Dim Pos As Variant ‘ Une variable de type variant pour sauvegarder la position courante dans le ‘recordset

Dim Conn As Connection ' Une référence pour sauvegarder la connexion courante de DataEnvironment

With DataEnvironment1.rsTAutor ' Sauvegarder la position courante

Pos = .Bookmark ' Sauvegarder la référence de connexion active

Set Conn = .ActiveConnection ' Fermer le recordset courant

.Close ' Ouverture du recordset

.Open , Conn ' Recréer le jeu d'enregistrements en ré-exécutant la requête Comme elle est ‘exécutée à nouveau, il peut y avoir des enregistrements en plus ou en moins

.Requery ' Une boucle pour parcourir tous les contrôles de feuille courante

Page 14: Complément Chapitre 6

14 Cours VB – ISG 2007/2008

For Each C In Me.Controls' Verifier si le contrôle courant est un contrôle dépendant (TextBox, DataCombo, ...)

If TypeOf C Is TextBox Or _ TypeOf C Is DataCombo Or _ TypeOf C Is DataList Or _ TypeOf C Is MSHFlexGrid Or _ TypeOf C Is DataGrid Then ' Rédefinir la propriété DataSource de contrôle dépendant

Set C.DataSource = DataEnvironment1 End If' Pour les contrôles DataCombo et DataList ont, en plus la propriété' RowSource

If TypeOf C Is DataCombo Or _ TypeOf C Is DataList Then Set C.RowSource = DataEnvironment1 End If Next .Bookmark = Pos End WithEnd Sub

Actualisation de recodeset (Requery)

Page 15: Complément Chapitre 6

Cours VB 2007/2008 15

ExempleGestion de la table

commandes

Page 16: Complément Chapitre 6

16 Cours VB – ISG 2007/2008

Page 17: Complément Chapitre 6

17 Cours VB – ISG 2007/2008

Propriétés des contrôles dataCombo

1. Code Client

RowSource= DataEnvironment1RowMember= TableClientsBoundColumn= Code clientListField=SociétéDataSource= DataEnvironment1DataMember= TableCdesDataField= Code client

2. N° employé

RowSource= DataEnvironment1RowMember= TableEmployeBoundColumn= N° employéListField=SociétéDataSource= DataEnvironment1DataMember= TableCdesDataField= N° employé

3. Messager

RowSource= DataEnvironment1RowMember= TableMessagersBoundColumn= N° messagerListField=SociétéDataSource= DataEnvironment1DataMember= TableCdesDataField= N° messager

Page 18: Complément Chapitre 6

18 Cours VB – ISG 2007/2008

Consultation ou Navigation

Private Sub CmdDernier_Click()With DataEnvironment1.rsTableCdesIf .RecordCount > 0 Then .MoveLastEnd IfEnd WithEnd Sub

Private Sub CmdPrecedent_Click()With DataEnvironment1.rsTableCdes If .RecordCount > 0 Then .MovePrevious If .BOF = True Then .MoveLast End If End IfEnd WithEnd Sub

Page 19: Complément Chapitre 6

19 Cours VB – ISG 2007/2008

Private Sub CmdPremier_Click()With DataEnvironment1.rsTableCdesIf .RecordCount > 0 Then .MoveFirstEnd IfEnd WithEnd Sub

Private Sub CmdSuivant_Click()With DataEnvironment1.rsTableCdes If .RecordCount > 0 Then .MoveNext If .EOF = True Then .MoveFirst End If End If End WithEnd Sub

Consultation ou Navigation

Page 20: Complément Chapitre 6

20 Cours VB – ISG 2007/2008

Consultation ou Navigation

Private Sub CmdRechercher_Click()Dim s As StringDim sauv As Variants = InputBox("n° Commande")sauv = DataEnvironment1.rsTableCdes.BookmarkDataEnvironment1.rsTableCdes.Find "[n° Commande]_ = '" + s + "'", , adSearchForward, 1If DataEnvironment1.rsTableCdes.EOF ThenMsgBox "Enregistrement inexistant"DataEnvironment1.rsTableCdes.Bookmark = sauvEnd IfEnd Sub

Page 21: Complément Chapitre 6

21 Cours VB – ISG 2007/2008

Opérations de mise à jour

Private Sub CmdNouveau_Click()aj = 1Call MAJaffichage(Me, aj)DataEnvironment1.rsTableCdes.AddNewtxtN°commande.SetFocusEnd Sub

Private Sub CmdEditer_Click()If txtN°commande <> "" Thenaj = 0Call MAJaffichage(Me, aj)txtN°commande.SetFocusElseMsgBox "Rien à modifier"End IfEnd Sub

Page 22: Complément Chapitre 6

22 Cours VB – ISG 2007/2008

Opérations de mise à jour

Private Sub CmdValider_Click()DataEnvironment1.rsTableCdes.UpdateCall MAJaffichage(Me, aj)Call Actualiser(Me)If aj = 1 ThenDataEnvironment1.rsTableCdes.MoveLastEnd If'le numéro du champ est un numéro automatiqueEnd SubPrivate Sub CmdAnnuler_Click()With DataEnvironment1.rsTableCdesIf aj = 0 Then.AddNew.CancelUpdateElse.CancelUpdateEnd IfCall MAJaffichage(Me, aj)End WithEnd Sub

Page 23: Complément Chapitre 6

23 Cours VB – ISG 2007/2008

Opérations de mise à jour

Private Sub CmdSupprimer_Click()With DataEnvironment1.rsTableCdesIf .RecordCount = 0 Then Exit SubIf MsgBox("Voulez vous supprimer", vbYesNo + vbQuestion, "Gestion Clients") = vbNo ThenExit SubEnd IfDataEnvironment1.rsTableDtCdes.OpenDataEnvironment1.rsTableDtCdes.Filter = "[n° Commande] = '" + txtN°commande + "'"If DataEnvironment1.rsTableDtCdes.RecordCount > 0 ThenDo While Not DataEnvironment1.rsTableDtCdes.EOF DataEnvironment1.rsTableDtCdes.Delete DataEnvironment1.rsTableDtCdes.MoveNext Loop End If DataEnvironment1.rsTableDtCdes.Close.Delete

If .RecordCount > 0 ThenIf .BOF Then.MoveFirstElse.MovePreviousEnd IfElse.AddNew.CancelUpdateEnd IfEnd WithEnd Sub

Page 24: Complément Chapitre 6

Cours VB 2007/2008 24

collection Errors

Page 25: Complément Chapitre 6

25 Cours VB – ISG 2007/2008

La collection Errors

C’est une collection qui permet de récupérer les propriétés des erreurs qui peuvent apparaître dans une application

Un objet Error contient des informations relatives aux erreurs d’accès aux données au cours d’une opération avec le fournisseur de données.

Page 26: Complément Chapitre 6

26 Cours VB – ISG 2007/2008

Exemple

Private Sub Cmdvalider_Click()

On Error GoTo etiq

DataEnvironment1.rsCTProduits.Update Exit Sub

etiq:If Err.Number = -2147467259 Then

MsgBox "Mon message pour doublon"

End Sub

Page 27: Complément Chapitre 6

27 Cours VB – ISG 2007/2008

Erreurs !! Réagissons avant !!!

1 –

2 –

1

2

Page 28: Complément Chapitre 6

28 Cours VB – ISG 2007/2008

Erreurs !! Réagissons avant !!!

3

4

3 –

4 –

Page 29: Complément Chapitre 6

29 Cours VB – ISG 2007/2008

Erreurs !! Réagissons avant !!!

5

6

5 –

6 –

Page 30: Complément Chapitre 6

Cours VB 2007/2008 30

AnnexeDataGrid

Page 31: Complément Chapitre 6

31 Cours VB – ISG 2007/2008

Utilisation du DataGrid (1)

Supposons qu'on a un bouton de commande Valider (CMDValider) et un DataGrid (DataGrid1) et qu'on veut que le bouton valider nous permette de récupérer la valeur de la deuxième colonne de la ligne sélectionnée

Private Sub CMDValider_Click() If DataGrid1.Col = 0 And DataGrid1.Row = -1 ThenMsgBox ("il faut faire un choix")ElseWith DataGrid1.Col = 1MsgBox .Text

‘ Equivalent à DataGrid1.Columns(0)

End WithEnd If 

End Sub

Page 32: Complément Chapitre 6

32 Cours VB – ISG 2007/2008

Utilisation du DataGrid (2)

Private Sub DataGrid1_HeadClick(ByVal ColIndex As Integer)

Dim x As String Select Case ColIndex Case 0: x = "Code_Passager" Case 1: x = "Nom" Case 2: x = "Prénom" End Select x = x + " ASC" DEBillet.rsListe.Sort = x DataGrid1.Refresh End Sub

• code pour permettre le tri (dans l’ordre croissant) de DataGrid1 par clic sur l’entête

de chacune de ses colonnes.

Page 33: Complément Chapitre 6

33 Cours VB – ISG 2007/2008

Annexe Représentations

graphiques

Page 34: Complément Chapitre 6

34 Cours VB – ISG 2007/2008

Représentations graphiques

Pour rajouter des représentations graphiques il faut utiliser le contrôle Mschart (microsft chart control 6.0) Exemple: pour afficher le résultat de la requête suivante (BD: NWIND) relative à l’objet commande (NombreProduits)

SELECT Catégories.`Nom de catégorie`, COUNT(*) AS `Nombre de produits` FROM Catégories, Produits WHERE Catégories.`Code catégorie` = Produits.`Code catégorie` GROUP BY `Nom de catégorie` ORDER BY COUNT(*)

Page 35: Complément Chapitre 6

35 Cours VB – ISG 2007/2008

Représentations graphiques

Private Sub Command1_Click() On Error Resume Next DataEnvironment1.rsNombreProduits.Open ' Initialisation du graphe MSChart1.AllowSelections = False ' Interdit la sélection d'objet

With MSChart1 .chartType = VtChChartType2dBar ' type de graphe .ColumnCount = 1 ' nombre de barre .RowCount=DataEnvironment1.rsNombreProduits.RecordCount ' nb de ligneslecture des noms des catégories dans la BDFor i = 1 To DataEnvironment1.rsNombreProduits.RecordCount .Row = i .Column = 1 ‘ le nom de catégorie. RowLabel =DataEnvironment1.rsNombreProduits.Fields(0) ' nombre de produits .Data = DataEnvironment1.rsNombreProduits.Fields(1) ' la catégorie suivante DataEnvironment1.rsNombreProduits.MoveNextNext i End With MSChart1.TitleText = "Nombre de produits par catégories"End Sub

Page 36: Complément Chapitre 6

36 Cours VB – ISG 2007/2008

Représentations graphiques

Nom de catégorie Nombre de produitsProduits secs 5Viandes 6Pâtes et céréales 7Produits laitiers 10Poissons et fruits de mer 12Condiments 12Boissons 12Desserts 13