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

C# Discussion :

conseils et bug sur appli avec une base access


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Invité
    Invité(e)
    Par défaut
    bonjour,

    je suis en train de faire des tests pour comprendre comment faire fonctionner une appli avec une base access.
    j'utilise visualstudio 2013 avec le framework 4.5.

    j'ai galéré pour trouver de la doc pour faire tout ça.

    ma base à 2 tables
    Personnes
    • Num
    • Nom
    • Prenom
    • Naissance (date)
    • Humain (entier)



    Humain
    • Num
    • Nom


    pour le moment je fais mes test sur la première table seulement. (on verra avec 2 tables ensuite...)

    j'ai un datagridview qui affiche la liste complète, et des textbox pour afficher les différentes données de la ligne sélectionnées
    je charge toutes les données, ensuite je veux les modifier comme je veux (ajout, suppression et modif) et enregistrer toutes mes modifs à la fin.
    j'ai également des boutons pour le déplacer entre les enregistrements.

    j'ai donc écris ce code :

    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
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
     
    using System.IO;
    using System.Data.OleDb;
    using System.Collections;
     
    namespace Base2
    {
        public partial class Form1 : Form
        {
            #region variables
            private string pathDB = Path.Combine(Application.StartupPath, "BaseTest.accdb");
            private OleDbConnection conn;
            private string sqlPerson = "select * from Personnes";
            private DataTable dt;
            #endregion
     
            public Form1()
            {
                InitializeComponent();
            }
     
            private void Form1_Load(object sender, EventArgs e)
            {
                this.conn = GetConnection();
                OleDbDataAdapter da = new OleDbDataAdapter(this.sqlPerson, this.conn);
                DataSet ds = new DataSet();
                this.dt = new DataTable();
     
                try
                {
                    da.Fill(ds, "Personnes");
                }
                catch (Exception)
                {
                    MessageBox.Show("Erreur à l'ouverture de la base !", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
     
                this.dt = ds.Tables["Personnes"];
     
                this.dgv1.AllowUserToAddRows = false;
                this.dgv1.AllowUserToDeleteRows = false;
     
                this.dgv1.DataSource = this.dt;
     
                this.dgv1.Columns["Num"].HeaderText = "N°";
     
                this.dgv1.AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight;
                this.dgv1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
     
                this.MajTb();
     
                this.Show();
     
            }
     
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                this.conn.Close();
            }
     
            private void dgv1_CurrentCellChanged(object sender, EventArgs e)
            {
                this.MajTb();
            }
     
            #region maj des composants
            private void MajTb()
            {
                if (this.dt != null && dgv1.CurrentRow != null && dgv1.CurrentRow.Index < this.dt.Rows.Count)
                {
                    this.tbNum.Text = this.dt.Rows[dgv1.CurrentRow.Index]["Num"].ToString();
                    this.tbNom.Text = this.dt.Rows[dgv1.CurrentRow.Index]["Nom"].ToString();
                    this.tbPrenom.Text = this.dt.Rows[dgv1.CurrentRow.Index]["Prenom"].ToString();
                    if (this.dt.Rows[dgv1.CurrentRow.Index]["Naissance"].ToString() != "")
                    {
                        this.tbNaissance.Text = String.Format("{0:dd/MM/yyyy}",
                                                               DateTime.Parse(this.dt.Rows[dgv1.CurrentRow.Index]["Naissance"].ToString())
                                                              );
                    }
                    else
                    {
                        this.tbNaissance.Text = "";
                    }
                    MajBtn();
                }
            }
     
            private void MajBtn()
            {
                btnPrecedent.Enabled = dgv1.CurrentRow.Index > 0;
                btnSuivant.Enabled = dgv1.CurrentRow.Index < this.dt.Rows.Count - 1;
            }
            #endregion
     
            #region déplacement dans enregistrements
            private void btnPrecedent_Click(object sender, EventArgs e)
            {
                this.Precedent(this.dgv1.CurrentRow.Index);
            }
     
            private void Precedent(int index)
            {
                if (this.dt != null && index > 0)
                {
                    //if (this.dt.Rows[index - 1].RowState != DataRowState.Deleted)
                        this.dgv1.CurrentCell = this.dgv1.Rows[index - 1].Cells[0];
                    //else
                    //    this.Precedent(index - 1);
                }
            }
     
            private void btnSuivant_Click(object sender, EventArgs e)
            {
                this.Next(this.dgv1.CurrentRow.Index);
            }
     
            private void Next(int index)
            {
                if (this.dt != null && index < this.dt.Rows.Count - 1)
                {
                    //if(this.dt.Rows[index + 1].RowState != DataRowState.Deleted)
                        this.dgv1.CurrentCell = this.dgv1.Rows[index + 1].Cells[0];
                    //else
                    //    this.Next(index + 1);
                }
            }
     
            private void btnFirst_Click(object sender, EventArgs e)
            {
                MessageBox.Show("First");
            }
     
            private void btnLast_Click(object sender, EventArgs e)
            {
                MessageBox.Show("Last");
            }
            #endregion
     
            #region fonctions
     
            // retourne chaine de connection
            private OleDbConnection GetConnection()
            {
                string s = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}";
                OleDbConnection conn = new OleDbConnection(String.Format(s, this.pathDB));
                return conn;
            }
     
            #endregion
     
            #region boutons action (ajout, suppression, modif)
            // btn ajout enregistrement
            private void btnAjout_Click(object sender, EventArgs e)
            {
                if (btnAjout.Text == "Nouveau")
                {
                    tbNum.Text = "";
                    tbNom.Text = "";
                    tbPrenom.Text = "";
                    tbNaissance.Text = "";
                    btnAjout.Text = "Ajouter";
                    btnDelete.Text = "Annuler";
     
                    btnSave.Enabled = false;
                    btnPrecedent.Enabled = false;
                    btnSuivant.Enabled = false;
                }
                else
                {
                    DataRow dr;
                    dr = this.dt.NewRow();
                    if (tbNum.Text != "") dr[" Num"] = tbNum.Text;
                    dr["Nom"] = tbNom.Text;
                    dr["Prenom"] = tbPrenom.Text;
                    if (tbNaissance.Text.Trim() != "")
                    {
                        dr["Naissance"] = tbNaissance.Text;
                    }
     
                    this.dt.Rows.Add(dr);
     
                    btnAjout.Text = "Nouveau";
                    btnDelete.Text = "Supprimer";
     
                    btnSave.Enabled = true;
                    MajBtn();
                }
            }
     
     
            // modifier enregistrement
            private void btnModifier_Click(object sender, EventArgs e)
            {
                this.dt.Rows[dgv1.CurrentRow.Index]["Nom"] = tbNom.Text;
                this.dt.Rows[dgv1.CurrentRow.Index]["Prenom"] = tbPrenom.Text;
                if (tbNaissance.Text.Trim() != "")
                {
                    this.dt.Rows[dgv1.CurrentRow.Index]["Naissance"] = tbNaissance.Text;
                }
            }
     
            // btn supprimer enregistrement
            private void btnDelete_Click(object sender, EventArgs e)
            {
                if (btnDelete.Text == "Supprimer")
                {
                    this.dt.Rows[this.dgv1.CurrentRow.Index].Delete();
                }
                else
                {
                    //
                    btnDelete.Text = "Supprimer";
                }
            }
     
            // btn enregistrer les modifs
            private void btnSave_Click(object sender, EventArgs e)
            {
                OleDbDataAdapter da = new OleDbDataAdapter(this.sqlPerson, this.conn);
                OleDbCommandBuilder cmdBuild;
                cmdBuild = new OleDbCommandBuilder(da);
                da.UpdateCommand = cmdBuild.GetUpdateCommand();
                da.Update(this.dt);
                MessageBox.Show("Enregistrement effectuée !", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            #endregion
     
            private void cbTest_SelectedIndexChanged(object sender, EventArgs e)
            {
                MessageBox.Show(cbTest.SelectedValue.ToString() + " - " + cbTest.Text);
            }
     
        }
    }
    il fonctionne... presque...
    j'ai un soucis sur les déplacements lorsque je supprimer une ligne dans le milieu.

    je voulais déjà votre avis et vos conseils sur mon code.
    est-ce que cela vous semble bon, voyez vous des choses qui vous choquent dans ce code ?

    merci de vos commentaires
    ben

    [EDIT 1]
    bonjour,

    j'ai revu mon code, cela fonctionne maintenant bien comme je veux.
    j'ai ajouté un bindingsource

    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
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
     
    using System.IO;
    using System.Data.OleDb;
    using System.Collections;
     
    namespace Base2
    {
        public partial class Form1 : Form
        {
            #region variables
            private string pathDB = Path.Combine(Application.StartupPath, "BaseTest.accdb");
            private OleDbConnection conn;
            private string sqlPerson = "select * from Personnes";
            private DataTable dt;
            private int maxID;
            #endregion
     
            public Form1()
            {
                InitializeComponent();
            }
     
            private void Form1_Load(object sender, EventArgs e)
            {
                this.conn = GetConnection();
                OleDbDataAdapter da = new OleDbDataAdapter(this.sqlPerson, this.conn);
                DataSet ds = new DataSet();
                this.dt = new DataTable();
     
                try
                {
                    da.Fill(ds, "Personnes");
                }
                catch (Exception)
                {
                    MessageBox.Show("Erreur à l'ouverture de la base !", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                this.dt = ds.Tables["Personnes"];
     
                this.dgv1.AllowUserToAddRows = false;
                this.dgv1.AllowUserToDeleteRows = false;
     
                this.bs.DataSource = this.dt;
                this.bindingNavigatorAddNewItem.Visible = false;
                this.dgv1.DataSource = this.bs;
     
                this.dgv1.Columns["Num"].HeaderText = "N°";
     
                this.dgv1.AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight;
                this.dgv1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
     
                this.MajTb();
     
                this.Show();
     
                this.maxID = 0;
                foreach (DataRow row in this.dt.Rows)
                {
                    if (int.Parse(row["Num"].ToString()) > this.maxID)
                    {
                        this.maxID = int.Parse(row["Num"].ToString());
                    }
                }
            }
     
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                this.conn.Close();
            }
     
            private void dgv1_CurrentCellChanged(object sender, EventArgs e)
            {
                this.MajTb();
            }
     
            #region maj des composants
            private void MajTb()
            {
                DataRowView drv = (DataRowView)this.bs.Current;
                if(drv != null)
                {
                    this.tbNum.Text = drv.Row["Num"].ToString();
                    this.tbNom.Text = drv.Row["Nom"].ToString();
                    this.tbPrenom.Text = drv.Row["Prenom"].ToString();
                    if(drv.Row["Num"].ToString() != "")
                    {
                        this.tbNaissance.Text = String.Format("{0:dd/MM/yyyy}",
                                                                DateTime.Parse(drv.Row["Naissance"].ToString())
                                                              );
                    }
                    this.MajBtn();
                }
            }
     
            private void MajBtn()
            {
                this.btnPrecedent.Enabled = this.bs.Position > 0;
                this.btnSuivant.Enabled = this.bs.Position < this.bs.Count - 1;
            }
            #endregion
     
            #region déplacement dans enregistrements
            private void btnPrecedent_Click(object sender, EventArgs e)
            {
                this.bs.MovePrevious();
            }
     
            private void btnSuivant_Click(object sender, EventArgs e)
            {
                this.bs.MoveNext();
            }
     
            private void btnFirst_Click(object sender, EventArgs e)
            {
                this.bs.MoveFirst();
            }
     
            private void btnLast_Click(object sender, EventArgs e)
            {
                this.bs.MoveLast();
            }
            #endregion
     
            #region fonctions
     
            // retourne chaine de connection
            private OleDbConnection GetConnection()
            {
                string s = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}";
                OleDbConnection conn = new OleDbConnection(String.Format(s, this.pathDB));
                return conn;
            }
     
            #endregion
     
            #region boutons action (ajout, suppression, modif)
            // btn ajout enregistrement
            private void btnAjout_Click(object sender, EventArgs e)
            {
                if (this.btnAjout.Text == "Nouveau")
                {
                    this.maxID++;
                    this.tbNum.Text = this.maxID.ToString();
                    this.tbNom.Text = "";
                    this.tbPrenom.Text = "";
                    this.tbNaissance.Text = "";
                    this.btnAjout.Text = "Ajouter";
                    this.btnDelete.Text = "Annuler";
     
                    this.btnSave.Enabled = false;
                    this.btnPrecedent.Enabled = false;
                    this.btnSuivant.Enabled = false;
                }
                else
                {
                    var itm = new {
                        num = int.Parse(tbNum.Text),
                        nom = tbNom.Text,
                        prenom = tbPrenom.Text,
                        naissance = tbNaissance.Text
                    };
     
                    this.bs.MoveLast();
                    this.bs.AddNew();
     
                    DataRowView drv = (DataRowView)this.bs.Current;
                    drv.Row["Num"] = itm.num;
                    drv.Row["Nom"] = itm.nom;
                    drv.Row["Prenom"] = itm.prenom;
                    drv.Row["Naissance"] = itm.naissance;
     
                    this.btnAjout.Text = "Nouveau";
                    this.btnDelete.Text = "Supprimer";
     
                    this.btnSave.Enabled = true;
                    this.MajTb();
                }
            }
     
            // btn modifier
            private void btnModifier_Click(object sender, EventArgs e)
            {
                DataRowView drv = (DataRowView)this.bs.Current;
                drv.Row["Num"] = int.Parse(tbNum.Text);
                drv.Row["Nom"] = int.Parse(tbNom.Text);
                drv.Row["Prenom"] = int.Parse(tbPrenom.Text);
                drv.Row["Naissance"] = int.Parse(tbNaissance.Text);
            }
     
            // btn supprimer enregistrement
            private void btnDelete_Click(object sender, EventArgs e)
            {
                if (this.btnDelete.Text == "Supprimer")
                {
                    this.bs.RemoveCurrent();
                }
                else
                {
                    //
                    this.maxID--;
                    this.btnDelete.Text = "Supprimer";
                    this.btnAjout.Text = "Nouveau";
                    this.MajTb();
                }
            }
     
            // btn enregistrer les modifs
            private void btnSave_Click(object sender, EventArgs e)
            {
                OleDbDataAdapter da = new OleDbDataAdapter(this.sqlPerson, this.conn);
                OleDbCommandBuilder cmdBuild = new OleDbCommandBuilder(da);
                da.UpdateCommand = cmdBuild.GetUpdateCommand();
                da.Update(this.dt);
                MessageBox.Show("Enregistrement effectuée !", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            #endregion
        }
    }
    avez-vous des conseils ou remarque sur mon code ?
    merci.

    [EDIT 2]
    au lieu de valider les modifications avec le code suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
                OleDbDataAdapter da = new OleDbDataAdapter(this.sqlPerson, this.conn);
                OleDbCommandBuilder cmdBuild = new OleDbCommandBuilder(da);
                da.UpdateCommand = cmdBuild.GetUpdateCommand();
                da.Update(this.dt);
    peut-on annuler toutes les modifs sans refaire une requête vers la base de données ?
    Dernière modification par DotNetMatt ; 31/07/2015 à 09h31. Motif: Fusion de messages consécutifs

Discussions similaires

  1. [Delphi 6] Problème avec une base Access
    Par chakir76 dans le forum Bases de données
    Réponses: 1
    Dernier message: 13/03/2008, 17h08
  2. Pb communication avec une base Access
    Par Syrrus dans le forum Access
    Réponses: 1
    Dernier message: 06/06/2007, 10h59
  3. Réponses: 1
    Dernier message: 06/08/2006, 04h00
  4. [ODBC] comment je peut conecter avec une base access chez le client avec php
    Par louzar dans le forum PHP & Base de données
    Réponses: 5
    Dernier message: 05/08/2006, 21h35
  5. [VB6]Problème connexion avec une base ACCESS
    Par mcay dans le forum VB 6 et antérieur
    Réponses: 8
    Dernier message: 15/05/2006, 17h47

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