IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VB.NET Discussion :

DataAdapter dans DAL, un ou plusieurs des paramètres requis.


Sujet :

VB.NET

  1. #1
    Membre éclairé

    Profil pro
    Inscrit en
    Juin 2002
    Messages
    291
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2002
    Messages : 291
    Par défaut DataAdapter dans DAL, un ou plusieurs des paramètres requis.
    Salut,

    Voilà j'ai réalisé, avec des codes pris à droite et à gauche, une D.A.L.

    Pour des essais, j'ai:
    # Une base avec une table Tbl_Energie (ID_Energie (Auto), Energie)
    # Un formulaire avec un DataGridview pour afficher, ajouter, modifier, supprimer, la table
    # Un bouton charger,pour afficher les données dans le DataGridview
    # Un bouton sauver, pour mettre à jour les données

    Dans la DAL:
    Pour charger la table
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
     
    Public Sub RemplirDataSet(ByVal objDataSet As DataSet, ByVal strNomTable As String, _
                                  ByVal strSelect As String, ByVal strInsert As String, _
                                  ByVal strUpdate As String, ByVal strDelete As String)
     
            Dim objConnection As DbConnection = Nothing
            Dim objDataAdapter As OleDb.OleDbDataAdapter = Nothing
     
            Try
     
                ' Création de l'objet connexion
                objConnection = GetConnection()
     
                ' Ouverture de la connexion
                objConnection.Open()
     
                objDataAdapter = CreateDataAdapter(CommandType.Text, strSelect, strInsert, strUpdate, strDelete)
                objDataAdapter.FillSchema(objDataSet, SchemaType.Mapped, strNomTable)
                objDataAdapter.Fill(objDataSet, strNomTable)
     
            Finally
                If objConnection.State <> System.Data.ConnectionState.Closed Then
                    objConnection.Close()
                End If
     
            End Try
     
        End Sub
    Pour sauver les données
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
     
    Public Sub MAJDataSet(ByVal objDataSet As DataSet, ByVal strNomTable As String, _
                              ByVal strSelect As String, ByVal strInsert As String, _
                              ByVal strUpdate As String, ByVal strDelete As String)
     
            Dim objConnection As DbConnection = Nothing
            Dim objDataAdapter As OleDb.OleDbDataAdapter = Nothing
     
            'Try
     
            objConnection = GetConnection()
     
            objDataAdapter = CreateDataAdapter(CommandType.Text, strSelect, strInsert, strUpdate, strDelete)
     
            objConnection.Open()
     
            ' UPDATE du dataset
            objDataAdapter.Update(objDataSet, strNomTable)
     
            objConnection.Close()
     
            'Catch ex As Exception
            'MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            'End Try
     
        End Sub
    La fonction CreateDataAdapter
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
     
     Public Function CreateDataAdapter(ByVal commandType As CommandType, ByVal selectStoredProcedure As String, ByVal insertStoredProcedure As String, _
                                                                            ByVal updateStoredProcedure As String, ByVal deleteStoredProcedure As String) As DbDataAdapter
     
            'Déclarations
            Dim dbSelectCommand As DbCommand = Nothing
            Dim dbInsertCommand As DbCommand = Nothing
            Dim dbUpdateCommand As DbCommand = Nothing
            Dim dbDeleteCommand As DbCommand = Nothing
            Dim dbDataAdapter As DbDataAdapter = Nothing
     
            Try
     
                Dim dbConnection As DbConnection = GetConnection()
     
                'Paramétrage de la commande de sélection
                dbSelectCommand = _dbProviderFactory.CreateCommand()
                dbSelectCommand.CommandType = commandType
                dbSelectCommand.Connection = dbConnection
     
                If Not selectStoredProcedure Is Nothing Then
                    dbSelectCommand.CommandText = selectStoredProcedure
                Else
                    dbSelectCommand.CommandText = ""
                End If
     
                'Paramétrage de la commande d'insertion
                dbInsertCommand = _dbProviderFactory.CreateCommand()
                dbInsertCommand.CommandType = commandType
                dbInsertCommand.Connection = dbConnection
     
                If Not insertStoredProcedure Is Nothing Then
                    dbInsertCommand.CommandText = insertStoredProcedure
                Else
                    dbInsertCommand.CommandText = ""
                End If
     
                'Paramétrage de la commande de mise à jour
                dbUpdateCommand = _dbProviderFactory.CreateCommand()
                dbUpdateCommand.CommandType = commandType
                dbUpdateCommand.Connection = dbConnection
     
                If Not updateStoredProcedure Is Nothing Then
                    dbUpdateCommand.CommandText = updateStoredProcedure
                Else
                    dbUpdateCommand.CommandText = ""
                End If
     
                'Paramétrage de la commande de suppression
                dbDeleteCommand = _dbProviderFactory.CreateCommand()
                dbDeleteCommand.CommandType = commandType
                dbDeleteCommand.Connection = dbConnection
     
                If Not deleteStoredProcedure Is Nothing Then
                    dbDeleteCommand.CommandText = deleteStoredProcedure
                Else
                    dbDeleteCommand.CommandText = ""
                End If
     
                'Paramétrage de l'adaptateur
                dbDataAdapter = _dbProviderFactory.CreateDataAdapter()
                dbDataAdapter.InsertCommand = dbInsertCommand
                dbDataAdapter.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
                dbDataAdapter.UpdateCommand = dbUpdateCommand
                dbDataAdapter.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
                dbDataAdapter.DeleteCommand = dbDeleteCommand
                dbDataAdapter.SelectCommand = dbSelectCommand
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
            'Retour
            Return dbDataAdapter
     
        End Function
    Le remplissage de la table dans le dataset fonctionne bien.

    J'ajoute une (ou plusieurs) ligne dans le datagridview, et lorsque je clique sur Sauver, j'obtiens cette erreur:
    Aucune valeur donnée pour un ou plusieurs des paramètres requis.
    sur la ligne
    objDataAdapter.Update(objDataSet, strNomTable)

    Je vois pas ou sa cloche...

    Merci d'avance pour le coup de main

    Gdal

  2. #2
    Membre éclairé

    Profil pro
    Inscrit en
    Juin 2002
    Messages
    291
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2002
    Messages : 291
    Par défaut
    Re, Tout le monde.

    Voici une DAL que j'ai créé:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    Imports System
    Imports System.Configuration            ' Récupérer les éléments contenus dans le fichier de configuration (notamment la chaine de connexion)
    Imports System.Collections.Generic
    Imports System.Data
    Imports System.Data.Common              ' Récupérer les classes abstraites d'ADO.net
    Imports System.Collections
    Imports System.String
     
    Public Class ClassDb
     
    #Region " Zone de réflexion "
     
        Private Sub fctDernierID(ByVal objConnection As DbConnection)
     
            Dim newID As Integer = 0
     
            Dim commandText As String
            commandText = "SELECT @@IDENTITY"
     
            Dim command As DbCommand
            command = CreateDbCommand(commandText, objConnection, CommandType.Text)
     
            newID = command.ExecuteScalar
     
            DernierID = newID
     
        End Sub
     
    #End Region
     
    #Region " Variables Privées "
     
        Private _DernierID As Integer
     
    #End Region
     
        Public Property DernierID()
            Get
                Return _DernierID
            End Get
            Set(ByVal value)
                _DernierID = value
            End Set
        End Property
     
    #Region "Propriétés Privées"
     
        '   "System.Data.Odbc"
     
     
        Private _strProviderName As String = "System.Data.OleDb"
        Private _strStringConnection As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                                                 "Data Source =" & Application.StartupPath & "\Source\Parc Vehicule.mdb;"
     
        'Private _strStringConnection As ConnectionStringSettings
        ' Objet créant le Command en fonction du fournisseur
        Private _dbProviderFactory As DbProviderFactory
     
    #End Region
     
    #Region "Constructeur de la classe"
     
        '/ <summary>
        '/ Constructeur de la classe
        '/ </summary>
        Sub New()
     
            ' Récupération de la classe fabrique suivant le provider
            _dbProviderFactory = DbProviderFactories.GetFactory(_strProviderName)
     
        End Sub
     
    #End Region
     
    #Region "Gestion de la connexion récupérer depuis un Setting"
     
        '/ <summary>
        '/ Crée une connexion depuis le fichier de configuration
        '/ </summary>
        '/ <returns>Objet implementant DbConnection</returns>
        Public Function GetConnection() As DbConnection
     
            Dim objConnection As DbConnection
            objConnection = Nothing
     
            Try
     
                ' Création de la connection
                objConnection = _dbProviderFactory.CreateConnection()
     
                ' Affectation de la chaine de connexion
                objConnection.ConnectionString = _strStringConnection
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
            ' retour de la connexion
            Return objConnection
     
        End Function
     
    #End Region
     
    #Region "Création d'un dbCommand"
     
        '/ <summary>
        '/ Créer un objet Command
        '/ </summary>
        ' TODO_1: Gestion des erreurs
        Public Function CreateDbCommand(ByVal commandText As String, ByVal connection As DbConnection, ByVal commandType As CommandType) As DbCommand
     
            Dim objCommand As DbCommand
            objCommand = Nothing
     
            Try
     
                objCommand = _dbProviderFactory.CreateCommand()
                objCommand.CommandType = commandType
                objCommand.CommandText = commandText
                objCommand.Connection = connection
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
            Return objCommand
     
        End Function
     
        '/ <summary>
        '/ Créer un objet Command : Surcharge
        '/ </summary>
        Public Function CreateDbCommand(ByVal commandText As String, ByVal commandType As CommandType) As DbCommand
     
            Dim objCommand As DbCommand
            objCommand = Nothing
     
            Try
     
                objCommand = _dbProviderFactory.CreateCommand()
                objCommand.CommandType = commandType
                objCommand.CommandText = commandText
                objCommand.Connection = GetConnection()
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
            Return objCommand
     
        End Function
     
    #End Region
     
    #Region "Récupération DataReader"
     
        '/ <summary>
        '/ Récupère un jeu d'enregistrement d'une base de donnée depuis un order T-SQL
        '/ </summary>
        Public Function GetReader(ByVal commandText As String) As DbDataReader
     
            Dim objDataReader As DbDataReader
            objDataReader = Nothing
     
            Dim objConnection As DbConnection
            objConnection = Nothing
     
            Try
                objConnection = GetConnection()
     
                Dim objCommand As DbCommand
                objCommand = CreateDbCommand(commandText, objConnection, CommandType.Text)
     
                objConnection.Open()
     
                objDataReader = objCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
     
            Catch
                If objConnection.State <> System.Data.ConnectionState.Closed Then
                    objConnection.Close()
                End If
     
            End Try
     
            ' Retour du objDataReader;
            Return objDataReader
     
        End Function
     
    #End Region
     
    #Region "Exécution d'un ordre qui ne renvoit pas de données"
        '/ <summary>
        '/ Exécute un ordre T-SQL et renvoit le nombre de lignes affectées
        '/ </summary>
        Public Function ExecuteNonQuery(ByVal commandText As String) As Integer
     
            Dim resultat As Integer = 0
            Dim objConnection As DbConnection = Nothing
     
            Try
                objConnection = GetConnection()
     
                Dim objCommand As DbCommand
                objCommand = CreateDbCommand(commandText, objConnection, CommandType.Text)
     
                objCommand.Connection = objConnection
     
                objConnection.Open()
     
                resultat = objCommand.ExecuteNonQuery()
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            Finally
                If objConnection.State <> System.Data.ConnectionState.Closed Then
                    objConnection.Close()
                End If
     
            End Try
     
            ' Retour du résultat
            Return resultat
     
        End Function
     
    #End Region
     
    #Region "Exécution d'un ordre qui renvoit une seule valeur"
     
        '/ <summary>
        '/ Exécute un ordre T-SQL et renvoit une valeur
        '/ </summary>
        '/ <param name="CommandText">Requète à éxécuter</param>
        '/ <returns>Valeur de retour</returns>
        Public Function ExecuteScalar(ByVal commandText As String) As Object
     
            Dim resultat As Integer
            resultat = Nothing
     
            Dim objConnection As DbConnection
            objConnection = Nothing
     
            Try
                objConnection = GetConnection()
     
                Dim command As DbCommand
                command = CreateDbCommand(commandText, objConnection, CommandType.Text)
     
                objConnection.Open()
     
                resultat = command.ExecuteScalar()
     
                ' Récupérer le dernier ID
                fctDernierID(objConnection)
     
            Finally
                If objConnection.State <> System.Data.ConnectionState.Closed Then
                    objConnection.Close()
                End If
     
            End Try
     
            ' Retour du résultat
            Return resultat
     
        End Function
     
    #End Region
     
    #Region "Gestion de la création d'un DataAdapter"
     
        '/ <summary>
        '/ Création d'un dataAdapter
        '/ </summary>
        Public Function CreateDataAdapter(ByVal commandType As CommandType, ByVal selectStoredProcedure As String, ByVal insertStoredProcedure As String, ByVal updateStoredProcedure As String, ByVal deleteStoredProcedure As String) As DbDataAdapter
     
            'Déclarations
            Dim dbSelectCommand As DbCommand = Nothing
            Dim dbInsertCommand As DbCommand = Nothing
            Dim dbUpdateCommand As DbCommand = Nothing
            Dim dbDeleteCommand As DbCommand = Nothing
            Dim dbDataAdapter As DbDataAdapter = Nothing
     
            Try
     
                Dim dbConnection As DbConnection = GetConnection()
     
                'Paramétrage de la commande de sélection
                dbSelectCommand = _dbProviderFactory.CreateCommand()
                dbSelectCommand.CommandType = commandType
                dbSelectCommand.Connection = dbConnection
     
                If Not selectStoredProcedure Is Nothing Then
                    dbSelectCommand.CommandText = selectStoredProcedure
                Else
                    dbSelectCommand.CommandText = ""
                End If
     
                'Paramétrage de la commande d'insertion
                dbInsertCommand = _dbProviderFactory.CreateCommand()
                dbInsertCommand.CommandType = commandType
                dbInsertCommand.Connection = dbConnection
     
                If Not insertStoredProcedure Is Nothing Then
                    dbInsertCommand.CommandText = insertStoredProcedure
                Else
                    dbInsertCommand.CommandText = ""
                End If
     
                'Paramétrage de la commande de mise à jour
                dbUpdateCommand = _dbProviderFactory.CreateCommand()
                dbUpdateCommand.CommandType = commandType
                dbUpdateCommand.Connection = dbConnection
     
                If Not updateStoredProcedure Is Nothing Then
                    dbUpdateCommand.CommandText = updateStoredProcedure
                Else
                    dbUpdateCommand.CommandText = ""
                End If
     
                'Paramétrage de la commande de suppression
                dbDeleteCommand = _dbProviderFactory.CreateCommand()
                dbDeleteCommand.CommandType = commandType
                dbDeleteCommand.Connection = dbConnection
     
                If Not deleteStoredProcedure Is Nothing Then
                    dbDeleteCommand.CommandText = deleteStoredProcedure
                Else
                    dbDeleteCommand.CommandText = ""
                End If
     
                'Paramétrage de l'adaptateur
                dbDataAdapter = _dbProviderFactory.CreateDataAdapter()
                dbDataAdapter.InsertCommand = dbInsertCommand
                dbDataAdapter.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
                dbDataAdapter.UpdateCommand = dbUpdateCommand
                dbDataAdapter.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
                dbDataAdapter.DeleteCommand = dbDeleteCommand
                dbDataAdapter.SelectCommand = dbSelectCommand
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
            'Retour
            Return dbDataAdapter
     
        End Function
     
    #End Region
     
    #Region "Récupération d'un DataSet"
     
        ''' <summary>
        ''' Récupère un DataSet, sans schémas de table, de la base de donnée depuis un ordre T-SQL
        ''' </summary>
        ''' <param name="objDataSet">Dataset devant contenir la table</param>
        ''' <param name="strNomTable">Nom de la table</param>
        ''' <param name="strCommandText">Requête servant à récupérer la table</param>
        ''' <remarks></remarks>
        Public Sub RemplirDataSetSsSchs(ByVal objDataSet As DataSet, ByVal strNomTable As String, _
                                        ByVal strCommandText As String)
     
            Dim objConnection As DbConnection = Nothing
            Dim objDbReader As DbDataReader = Nothing
     
            Try
     
                ' Création de l'objet connexion
                objConnection = GetConnection()
     
                Dim objCommand As DbCommand
                objCommand = CreateDbCommand(strCommandText, objConnection, CommandType.Text)
     
                ' Ouverture de la connexion
                objConnection.Open()
     
                objDbReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
                objDataSet.Load(objDbReader, LoadOption.PreserveChanges, strNomTable)
     
            Finally
                If objConnection.State <> System.Data.ConnectionState.Closed Then
                    objConnection.Close()
                End If
     
            End Try
     
        End Sub
     
        ''' <summary>
        ''' Récupère un DataSet, avec schémas de table, de la base de donnée depuis un ordre T-SQL
        ''' </summary>
        ''' <param name="objDataSet">Dataset devant contenir la table</param>
        ''' <param name="strNomTable">Nom de la table</param>
        ''' <param name="objDataAdapter">DataAdapter de la table</param>
        ''' <remarks></remarks>
        Public Sub RemplirDataSetAvcSchs(ByVal objDataSet As DataSet, ByVal strNomTable As String, _
                                         ByVal objDataAdapter As OleDb.OleDbDataAdapter)
     
            Dim objConnection As DbConnection = Nothing
     
            Try
     
                ' Création de l'objet connexion
                objConnection = GetConnection()
     
                objDataAdapter.SelectCommand.Connection = objConnection
                objDataAdapter.InsertCommand.Connection = objConnection
                objDataAdapter.UpdateCommand.Connection = objConnection
                objDataAdapter.DeleteCommand.Connection = objConnection
     
                ' Ouverture de la connexion
                objConnection.Open()
     
                objDataAdapter.FillSchema(objDataSet, SchemaType.Mapped, strNomTable)
                objDataAdapter.Fill(objDataSet, strNomTable)
     
            Finally
                If objConnection.State <> System.Data.ConnectionState.Closed Then
                    objConnection.Close()
                End If
     
            End Try
     
        End Sub
     
    #End Region
     
    #Region "Mise à jour du DataSet"
     
        Public Sub UpdateDataSet(ByVal objDataAdapter As DbDataAdapter, ByVal objDataSet As DataSet, ByVal strTable As String)
     
            Dim objConnection As DbConnection = Nothing
     
            Try
     
                ' Création de l'objet connexion
                objConnection = GetConnection()
     
                objDataAdapter.SelectCommand.Connection = objConnection
                objDataAdapter.InsertCommand.Connection = objConnection
                objDataAdapter.UpdateCommand.Connection = objConnection
                objDataAdapter.DeleteCommand.Connection = objConnection
     
                ' Ouverture de la connexion
                objConnection.Open()
     
                ' UPDATE du dataset
                objDataAdapter.Update(objDataSet, strTable)
     
            Catch ex As Exception
                'MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            Finally
                If objConnection.State <> System.Data.ConnectionState.Closed Then
                    objConnection.Close()
                End If
     
            End Try
     
        End Sub
     
    #End Region
     
    End Class
    La classe Métier:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    ' Couche Utilisateur (=Formulaire) <-> Couche Métier <-> Couche Accès aux données
    ' => Couche Métier
     
    Imports System
    Imports System.Data
    Imports System.Data.OleDb
     
    Public Class ClasseMarque
     
    #Region " Variables Privées "
     
        Private _clClassDb As New ClassDb
        Private _NomTable As String = "TblMarque"
        Private _DernierID As Integer
        Private _IdMarque As Integer
        Private _Marque As String
     
    #End Region
     
        Public Sub New()
     
        End Sub
     
    #Region "Propriétés de la Marque"
     
        Public Property DernierID() As Integer
            Get
                Return _DernierID
            End Get
            Set(ByVal value As Integer)
                _DernierID = value
            End Set
        End Property
     
        Public Property IdMarque() As Integer
            Get
                Return _IdMarque
            End Get
            Set(ByVal value As Integer)
                _IdMarque = value
            End Set
        End Property
     
        Public Property Marque() As String
            Get
                Return _Marque
            End Get
            Set(ByVal value As String)
                _Marque = value
            End Set
        End Property
     
    #End Region
     
    #Region "Charger les données"
     
        ''' <summary>
        ''' Créer le DataAdapter
        ''' </summary>
        ''' <param name="strFiltreTrie"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function CreerDataAdapter(Optional ByVal strFiltreTrie As String = "") As OleDbDataAdapter
     
            Dim objDataAdapter As New OleDbDataAdapter
            Dim tableMapping As New Common.DataTableMapping
     
            Try
     
                ' Mapping de la table
                tableMapping.SourceTable = "Table"
                tableMapping.DataSetTable = "Tbl_Marque"
                tableMapping.ColumnMappings.Add("ID_Marque", "ID_Marque")
                tableMapping.ColumnMappings.Add("Marque", "Marque")
                objDataAdapter.TableMappings.Add(tableMapping)
     
                ' SELECTCOMMAND
                objDataAdapter.SelectCommand = New OleDb.OleDbCommand
                'objDataAdapter.InsertCommand.Connection = objConnexion
                objDataAdapter.SelectCommand.CommandText = "SELECT Tbl_Marque.* FROM Tbl_Marque " & strFiltreTrie
                objDataAdapter.SelectCommand.CommandType = CommandType.Text
     
                ' INSERTCOMMAND
                objDataAdapter.InsertCommand = New OleDb.OleDbCommand
                'objDataAdapter.InsertCommand.Connection = objConnexion
                objDataAdapter.InsertCommand.CommandText = "INSERT INTO Tbl_Marque (Marque) VALUES (?)"
                objDataAdapter.InsertCommand.CommandType = CommandType.Text
                objDataAdapter.InsertCommand.Parameters.Add(New OleDb.OleDbParameter("Marque", OleDb.OleDbType.VarWChar, 0, ParameterDirection.Input, CType(0, Byte), CType(0, Byte), "Marque", DataRowVersion.Current, False, Nothing))
     
                ' UPDATECOMMAND
                objDataAdapter.UpdateCommand = New OleDb.OleDbCommand
                'objDataAdapter.UpdateCommand.Connection = objConnexion
                objDataAdapter.UpdateCommand.CommandText = "UPDATE Tbl_Marque SET Marque = ? WHERE ((ID_Marque = ?) AND ((? = 1 AND Marque IS NULL) OR (Marque = ?)))"
                objDataAdapter.UpdateCommand.CommandType = CommandType.Text
                objDataAdapter.UpdateCommand.Parameters.Add(New OleDb.OleDbParameter("Marque", OleDb.OleDbType.VarWChar, 0, ParameterDirection.Input, CType(0, Byte), CType(0, Byte), "Marque", DataRowVersion.Current, False, Nothing))
                objDataAdapter.UpdateCommand.Parameters.Add(New OleDb.OleDbParameter("Original_ID_Marque", OleDb.OleDbType.[Integer], 0, ParameterDirection.Input, CType(0, Byte), CType(0, Byte), "ID_Marque", DataRowVersion.Original, False, Nothing))
                objDataAdapter.UpdateCommand.Parameters.Add(New OleDb.OleDbParameter("IsNull_Marque", OleDb.OleDbType.[Integer], 0, ParameterDirection.Input, CType(0, Byte), CType(0, Byte), "Marque", DataRowVersion.Original, True, Nothing))
                objDataAdapter.UpdateCommand.Parameters.Add(New OleDb.OleDbParameter("Original_Marque", OleDb.OleDbType.VarWChar, 0, ParameterDirection.Input, CType(0, Byte), CType(0, Byte), "Marque", DataRowVersion.Original, False, Nothing))
     
                ' DELETECOMMAND
                objDataAdapter.DeleteCommand = New OleDb.OleDbCommand
                'objDataAdapter.DeleteCommand.Connection = objConnexion
                objDataAdapter.DeleteCommand.CommandText = "DELETE FROM Tbl_Marque WHERE ((ID_Marque = ?) AND ((? = 1 AND Marque IS NULL) OR (Marque = ?)))"
                objDataAdapter.DeleteCommand.CommandType = CommandType.Text
                objDataAdapter.DeleteCommand.Parameters.Add(New OleDb.OleDbParameter("Original_ID_Marque", OleDb.OleDbType.[Integer], 0, ParameterDirection.Input, CType(0, Byte), CType(0, Byte), "ID_Marque", DataRowVersion.Original, False, Nothing))
                objDataAdapter.DeleteCommand.Parameters.Add(New OleDb.OleDbParameter("IsNull_Marque", OleDb.OleDbType.[Integer], 0, ParameterDirection.Input, CType(0, Byte), CType(0, Byte), "Marque", DataRowVersion.Original, True, Nothing))
                objDataAdapter.DeleteCommand.Parameters.Add(New OleDb.OleDbParameter("Original_Marque", OleDb.OleDbType.VarWChar, 0, ParameterDirection.Input, CType(0, Byte), CType(0, Byte), "Marque", DataRowVersion.Original, False, Nothing))
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
            Return objDataAdapter
     
        End Function
     
        ''' <summary>
        ''' Charger un enregistrement
        ''' </summary>
        ''' <param name="IdMarque">ID de l'enregistrement à charger</param>
        ''' <remarks></remarks>
        Public Sub ChargerUn(ByVal IdMarque As Integer)
     
            Try
     
                Dim intResultatRech As Int16
                Dim objDataReader As OleDb.OleDbDataReader
                Dim strRecherche As String
     
                strRecherche = "SELECT Tbl_Marque.* " & _
                               "FROM Tbl_Marque " & _
                               "WHERE Tbl_Marque.ID_Marque = " & IdMarque & ";"
     
                intResultatRech = _clClassDb.ExecuteNonQuery(strRecherche)
     
                'If intResultatRech > 0 Then
     
                objDataReader = _clClassDb.GetReader(strRecherche)
     
                Do While objDataReader.Read
     
                    If objDataReader.IsDBNull(objDataReader.GetOrdinal("ID_Marque")) Then : _IdMarque = "-1" : Else : _IdMarque = objDataReader.GetInt32(objDataReader.GetOrdinal("ID_Marque")) : End If
                    If objDataReader.IsDBNull(objDataReader.GetOrdinal("Marque")) Then : _Marque = "" : Else : _Marque = objDataReader.GetString(objDataReader.GetOrdinal("Marque")) : End If
     
                Loop
     
                'Else
                ' MessageBox.Show("L'enregistrement n'existe pas")
                'End If
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            End Try
     
        End Sub
     
        ''' <summary>
        ''' Liste permettant d'indiquer s'il faut charger le schémas de la table
        ''' </summary>
        ''' <remarks></remarks>
        Public Enum lstChargerSchemas
     
            AvecSchemas
            SansSchemas
     
        End Enum
     
        ''' <summary>
        ''' Charger toute ou une partie de la table dans un DataSet
        ''' </summary>
        ''' <param name="objDataSet">Objet DataSet devant contenir la table</param>
        ''' <param name="strFiltreTrie">Filtre "WHERE" et/ou trie "ORDER BY"</param>
        ''' <returns>Retourne un objet DataTable</returns>
        ''' <remarks></remarks>
        Public Function ChargerTs(ByVal objDataSet As DataSet, _
                                       ByVal lstChargerSchemas As lstChargerSchemas, _
                                       Optional ByVal strFiltreTrie As String = "") As DataTable
     
            Dim objDataTable As DataTable = Nothing
     
            Try
     
                Select Case lstChargerSchemas
     
                    Case lstChargerSchemas.AvecSchemas
                        _clClassDb.RemplirDataSetAvcSchs(objDataSet, _NomTable, CreerDataAdapter(strFiltreTrie))
     
                    Case lstChargerSchemas.SansSchemas
                        Dim strRequete As String
                        strRequete = "SELECT Tbl_Marque.* FROM Tbl_Marque " & strFiltreTrie
                        _clClassDb.RemplirDataSetSsSchs(objDataSet, _NomTable, strRequete)
     
                End Select
     
                objDataTable = objDataSet.Tables(_NomTable)
     
                ' Renommer les colonnes du DataTable
                'objDataTable.Columns("ID_Marque").ColumnName = "ID_Marque"
                'objDataTable.Columns("Marque").ColumnName = "Marque"
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            End Try
     
            Return objDataTable
     
        End Function
     
        ''' <summary>
        ''' Trier le DataSet
        ''' </summary>
        ''' <param name="objDataSet">Objet DataSet à Trier</param>
        ''' <param name="strFiltre">Filtre Nom du champ = 'Valeur'</param>
        ''' <param name="strChampASCDESC">Type de trie ASC ou DESC</param>
        ''' <returns>Retourne un objet DataView</returns>
        ''' <remarks></remarks>
        ''' <example>TrierChargerTs(objDataSet, "Marque = 'Peugeot'", "Marque ASC")</example>
        Public Function TrierChargerTs(ByVal objDataSet As DataSet, ByVal strFiltre As String, _
                                        Optional ByVal strChampASCDESC As String = "") As DataView
     
            Dim objDataView As New DataView
     
            Try
     
                With objDataView
                    .Table = objDataSet.Tables("TblMarque")
                    .Sort = strChampASCDESC
                    .RowFilter = strFiltre
                End With
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            End Try
     
            Return objDataView
     
        End Function
     
        ''' <summary>
        ''' Charger une combobox
        ''' </summary>
        ''' <param name="cboNameComboBox">ComboBox à remplir</param>
        ''' <param name="strDisplayMember">Nom du membre à afficher</param>
        ''' <param name="strValueMember">Nom du membre à prendre pour valeur réelle</param>
        ''' <param name="strFiltreTrie">Filtre "WHERE" et/ou trie "ORDER BY"</param>
        ''' <remarks></remarks>
        ''' <example>clMarque.ChargerComboBox(Me.cboMarque, "Marque", "ID_Marque", "ORDER BY Marque")</example>
        Public Sub ChargerComboBox(ByVal cboNameComboBox As ComboBox, _
                                    ByVal strDisplayMember As String, _
                                    ByVal strValueMember As String, _
                                    Optional ByVal strFiltreTrie As String = Nothing)
     
            Try
     
                Dim objDataset As New DataSet
     
                cboNameComboBox.DisplayMember = strDisplayMember
                cboNameComboBox.ValueMember = strValueMember
                cboNameComboBox.DataSource = ChargerTs(objDataset, lstChargerSchemas.SansSchemas, strFiltreTrie)
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            End Try
     
        End Sub
     
    #End Region
     
    #Region "Ajouter / Modifier / Supprimer / Mise à jour les données"
     
        Public Function AjouterUn() As Boolean
     
            Try
     
                ' Tester l'existence de la valeur
                Dim strRequeteTest As String
                strRequeteTest = "SELECT COUNT(Tbl_Marque.Marque) " & _
                                 "FROM Tbl_Marque " & _
                                 "WHERE Tbl_Marque.Marque = """ & _Marque & """;"
     
                Dim intResultat As Integer
                intResultat = _clClassDb.ExecuteScalar(strRequeteTest)
     
                ' Enregistrer la nouvelle valeur si elle n'existe pas
                If intResultat > 0 Then
     
                    ' Indique l'enregistrement n'a pas été ajouté
                    AjouterUn = False
                    MessageBox.Show("Cette marque existe déjà.")
     
                Else
     
                    Dim strRequeteAjo As String
                    strRequeteAjo = "INSERT INTO Tbl_Marque(Marque) " & _
                                    "VALUES(""" & _Marque & """)"
     
                    ' Exécuter la requête d'ajout
                    _clClassDb.ExecuteScalar(strRequeteAjo)
     
                    ' Récupérer le dernier ID ajouté à la table
                    DernierID = _clClassDb.DernierID
     
                    ' Indique l'enregistrement a été ajouté
                    AjouterUn = True
     
                End If
     
                Return AjouterUn
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
        End Function
     
        Public Function ModifierUn() As Boolean
     
            Try
     
                ' Modifier la nouvelle valeur
                Dim strRequete As String
                strRequete = "UPDATE Tbl_Marque " & _
                             "SET Marque = """ & _Marque & """ " & _
                             "WHERE Tbl_Marque.ID_Marque = " & _IdMarque & ";"
     
                _clClassDb.ExecuteScalar(strRequete)
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
        End Function
     
        Public Function SupprimerUn() As Boolean
     
            Try
     
                ' Supprimer la valeur
                Dim strRequete As String = Nothing
     
                strRequete = "DELETE Tbl_Marque.* " & _
                             "FROM Tbl_Marque  " & _
                             "WHERE Tbl_Marque.ID_Marque = " & _IdMarque & ";"
     
                _clClassDb.ExecuteScalar(strRequete)
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
        End Function
     
        Public Sub UpdateDataSet(ByVal objDataSet As DataSet)
     
            Try
     
                ' UPDATE du dataset
                _clClassDb.UpdateDataSet(CreerDataAdapter, objDataSet, _NomTable)
     
            Catch ex As Exception
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop)
     
            End Try
     
        End Sub
     
    #End Region
     
    End Class
    Quelques exemples:
    + Déclarer la classe lorsque l'on souhaite s'en servir
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
        Private clMarque As New ClasseMarque
    + Avant d'enregistrer ou de modifier les valeurs saisies dans le formulaire, il faut les tranférer dans la classe métier:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #Region "Chargement Formulaire -> Classes // Classe Marque"
     
        Private Sub ChargerFrmClMarque()
            ' Marque
            clMarque.IdMarque = intIDTblMarque
            clMarque.Marque = Me.txtMarque.Text
     
        End Sub
     
    #End Region
    Ensuite on enregistre ou modifie:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
                        ' Ajouter
                        clMarque.AjouterUn()
                        ' Modifier
                        clMarque.ModifierUn()
    Charger une combobox:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
            ' Remplissage de la ComboBox
            clMarque.ChargerComboBox(Me.cboMarque, "Marque", "ID_Marque", "ORDER BY Marque")
    Voilà. Elle est très loin d'être parfaite, mais elle fonctionne.

    Gdal

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. aucune valeur donnée pour un ou plusieurs des paramètres requis
    Par rec82 dans le forum Bases de données
    Réponses: 14
    Dernier message: 10/06/2016, 12h59
  2. Aucune valeur donnée pour un ou plusieurs des paramètres requis
    Par bboy_lil_mak dans le forum Bases de données
    Réponses: 8
    Dernier message: 10/06/2016, 12h40
  3. Delphi : Aucune valeur donnée pour un ou plusieurs des paramètres requis
    Par bboy_lil_mak dans le forum Bases de données
    Réponses: 8
    Dernier message: 22/07/2013, 00h11
  4. Réponses: 9
    Dernier message: 01/06/2011, 14h33
  5. [AC-2000] Erreur : Aucune des valeurs données pour plusieur des paramètres requis
    Par mcfly37 dans le forum VBA Access
    Réponses: 10
    Dernier message: 21/04/2009, 14h11

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo