J'ai un form principal : using Microsoft.EntityFrameworkCore; using…
- User
J'ai un form principal : using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Query.Internal;
namespace TP_Evaluation_Forms_IMBAUD_Florian { public partial class FormVisionnageBDD : Form { int indexMinCourant = 0; int nombreAffichages = 0; int indexMin = 1; int indexMax = 0;
bool popupDebut = false; bool popupFin = false; private bool boutonsDesactives = false; // Si le bool est vrai, c'est une mise à jour, sinon c'est un ajout private List<(object, string)> modificationsEnAttente = new List<(object, string)>(); private string tablePrecedenteSelectionnee = string.Empty; public FormVisionnageBDD() { InitializeComponent(); // tant qu'aucun intem de boiteListeAffichageTables n'est sélectionné, on ne peut pas sélectionner des boutons : on les désactive if (boiteListeAffichageTables.SelectedIndex == -1) { DesacitverTousBoutons(); } // On charge la liste des tables // Les tables seront nommées : Departements, Employes, EmployeProjets, Projets List<string> tables = ["Departements", "Employes", "EmployesProjets", "Projets"]; boiteListeAffichageTables.Items.Clear(); foreach (var table in tables) { boiteListeAffichageTables.Items.Add(table); } } private void DesacitverTousBoutons() { // Modifier l'apparence des boutons pour qu'ils paraissent désactivés bouton1Precedent.BackColor = Color.DarkGray; bouton10000Precedent.BackColor = Color.DarkGray; boutonPrecedentToute.BackColor = Color.DarkGray; bouton1Suivant.BackColor = Color.DarkGray; bouton10000Suivant.BackColor = Color.DarkGray; boutonSuivantToute.BackColor = Color.DarkGray; boutonAjoutEnregistrement.BackColor = Color.DarkGray; boutonValidationChangementsTable.BackColor = Color.DarkGray; boutonModificationEnregistrementSelection.BackColor = Color.DarkGray; // Mettre à jour l'état boutonsDesactives = true; } private void ActiverTousBoutons() { // Restaurer l'apparence des boutons bouton1Precedent.BackColor = SystemColors.Window; bouton10000Precedent.BackColor = SystemColors.Window; boutonPrecedentToute.BackColor = SystemColors.Window; bouton1Suivant.BackColor = SystemColors.Window; bouton10000Suivant.BackColor = SystemColors.Window; boutonSuivantToute.BackColor = SystemColors.Window; boutonAjoutEnregistrement.BackColor = SystemColors.Window; boutonValidationChangementsTable.BackColor = SystemColors.Window; boutonModificationEnregistrementSelection.BackColor = SystemColors.Window; // Mettre à jour l'état boutonsDesactives = false; } private void AffichageDonnees() { using (var contexte = new AppDbContext()) { var table = boiteListeAffichageTables.SelectedItem.ToString(); switch (table) { case "Departements": grilleDonneesTables.Columns.Clear(); indexMax = contexte.Departements.Count(); CorrectionIndexesEtGestionPopup(); // Si il y a plus de 10000 données, on les affiche par page de 10000 dans grilleDonneesTable if (indexMax >= 10000) { var departements = contexte.Departements.OrderBy(e => e.department_id).Skip(indexMinCourant).Take(nombreAffichages).ToList(); grilleDonneesTables.DataSource = departements; } else { var departements = contexte.Departements.OrderBy(e => e.department_id).ToList(); grilleDonneesTables.DataSource = departements; } break; case "Employes": grilleDonneesTables.Columns.Clear(); indexMax = contexte.Employes.Count(); CorrectionIndexesEtGestionPopup(); // Si il y a plus de 10000 données, on les affiche par page de 10000 dans grilleDonneesTable if (indexMax >= 10000) { // Ensuite, on affiche les employés de l'indice minimal courant, à l'indice maximal courant var employes = contexte.Employes.Include(e => e.departement).OrderBy(e => e.employee_id).Skip(indexMinCourant).Take(nombreAffichages).ToList(); grilleDonneesTables.DataSource = employes; } else { var employes = contexte.Employes.Include(e => e.departement).OrderBy(e => e.employee_id).ToList(); grilleDonneesTables.DataSource = employes; } break; case "EmployesProjets": grilleDonneesTables.Columns.Clear(); indexMax = contexte.EmployeProjets.Count(); CorrectionIndexesEtGestionPopup(); // Si il y a plus de 10000 données, on les affiche par page de 10000 dans grilleDonneesTable if (indexMax >= 10000) { var employeProjets = contexte.EmployeProjets.OrderBy(e => e.employee_id).Skip(indexMinCourant).Take(nombreAffichages).ToList(); grilleDonneesTables.DataSource = employeProjets; } else { var employesProjets = contexte.EmployeProjets.OrderBy(e => e.employee_id).ToList(); grilleDonneesTables.DataSource = employesProjets; } break; case "Projets": grilleDonneesTables.Columns.Clear(); indexMax = contexte.Projets.Count(); CorrectionIndexesEtGestionPopup(); // Si il y a plus de 10000 données, on les affiche par page de 10000 dans grilleDonneesTable if (indexMax >= 10000) { var projets = contexte.Projets.OrderBy(e => e.project_id).Skip(indexMinCourant).Take(nombreAffichages).ToList(); grilleDonneesTables.DataSource = projets; } else { var projets = contexte.Projets.OrderBy(e => e.project_id).ToList(); grilleDonneesTables.DataSource = projets; } break; default: break; } if (popupDebut) MessageBox.Show("Vous êtes arrivé au début de la liste"); if (popupFin) MessageBox.Show("Vous êtes arrivé à la fin de la liste"); } } private void CorrectionIndexesEtGestionPopup() { if (indexMinCourant >= indexMax || indexMinCourant + nombreAffichages >= indexMax) { indexMinCourant = indexMax - nombreAffichages; // On fait apparaître un popup après l'affichage des données pour signifier qu'on est à la fin popupDebut = false; popupFin = true; } else if (indexMinCourant < indexMin) { indexMinCourant = 0; // On fait apparaître un popup après l'affichage des données pour signifier qu'on est au début popupDebut = true; popupFin = false; } else { // On ne fera apparaître aucun popup popupDebut = false; popupFin = false; } } private void bouton_MouseEnter(object sender, EventArgs e) { if (boutonsDesactives) Cursor = Cursors.No; else Cursor = Cursors.Hand; } private void bouton_MouseLeave(object sender, EventArgs e) { Cursor = Cursors.Default; } private void bouton1Precedent_Click(object sender, EventArgs e) { VerificationSiChangements(); if (boutonsDesactives) { MessageBox.Show("Veuillez sélectionner une table pour activer les boutons.", "Bouton désactivé", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } indexMinCourant -= 1; nombreAffichages = 10000; AffichageDonnees(); } private void bouton10000Precedent_Click(object sender, EventArgs e) { VerificationSiChangements(); if (boutonsDesactives) { MessageBox.Show("Veuillez sélectionner une table pour activer les boutons.", "Bouton désactivé", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } indexMinCourant -= 10000; nombreAffichages = 10000; AffichageDonnees(); } private void bouton10000PrecedentToute_Click(object sender, EventArgs e) { VerificationSiChangements(); if (boutonsDesactives) { MessageBox.Show("Veuillez sélectionner une table pour activer les boutons.", "Bouton désactivé", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } indexMinCourant = 0; nombreAffichages = 10000; AffichageDonnees(); } private void bouton1Suivant_Click(object sender, EventArgs e) { VerificationSiChangements(); if (boutonsDesactives) { MessageBox.Show("Veuillez sélectionner une table pour activer les boutons.", "Bouton désactivé", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } indexMinCourant += 1; nombreAffichages = 10000; AffichageDonnees(); } private void bouton10000Suivant_Click(object sender, EventArgs e) { VerificationSiChangements(); if (boutonsDesactives) { MessageBox.Show("Veuillez sélectionner une table pour activer les boutons.", "Bouton désactivé", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } indexMinCourant += 10000; nombreAffichages = 10000; AffichageDonnees(); } private void bouton10000SuivantToute_Click(object sender, EventArgs e) { VerificationSiChangements(); if (boutonsDesactives) { MessageBox.Show("Veuillez sélectionner une table pour activer les boutons.", "Bouton désactivé", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } indexMinCourant = int.MaxValue; nombreAffichages = 10000; AffichageDonnees(); } private void boiteListeAffichageTables_SelectedIndexChanged(object sender, EventArgs e) { VerificationSiChangements(); nombreAffichages = 10000; ActiverTousBoutons(); // Mettre à jour la table précédente tablePrecedenteSelectionnee = boiteListeAffichageTables.SelectedItem.ToString(); // On affiche la table sélectionnée using (var contexte = new AppDbContext()) { var table = boiteListeAffichageTables.SelectedItem.ToString(); switch (table) { case "Departements": grilleDonneesTables.Columns.Clear(); indexMax = contexte.Departements.Count(); CorrectionIndexesEtGestionPopup(); // Si il y a plus de 10000 données, on les affiche par page de 10000 dans grilleDonneesTable if (indexMax >= 10000) { var departements = contexte.Departements.OrderBy(e => e.department_id).Skip(indexMinCourant).Take(nombreAffichages).ToList(); grilleDonneesTables.DataSource = departements; } else { indexMinCourant = 0; var departements = contexte.Departements.OrderBy(e => e.department_id).ToList(); grilleDonneesTables.DataSource = departements; } break; case "Employes": grilleDonneesTables.Columns.Clear(); indexMax = contexte.Employes.Count(); CorrectionIndexesEtGestionPopup(); // Si il y a plus de 10000 données, on les affiche par page de 10000 dans grilleDonneesTable if (indexMax >= 10000) { // Ensuite, on affiche les employés de l'indice minimal courant, à l'indice maximal courant var employes = contexte.Employes.Include(e => e.departement).OrderBy(e => e.employee_id).Skip(indexMinCourant).Take(nombreAffichages).ToList(); grilleDonneesTables.DataSource = employes; } else { indexMinCourant = 0; var employes = contexte.Employes.Include(e => e.departement).OrderBy(e => e.employee_id).ToList(); grilleDonneesTables.DataSource = employes; } break; case "EmployesProjets": grilleDonneesTables.Columns.Clear(); indexMax = contexte.EmployeProjets.Count(); CorrectionIndexesEtGestionPopup(); // Si il y a plus de 10000 données, on les affiche par page de 10000 dans grilleDonneesTable if (indexMax >= 10000) { var employeProjets = contexte.EmployeProjets.OrderBy(e => e.employee_id).Skip(indexMinCourant).Take(nombreAffichages).ToList(); grilleDonneesTables.DataSource = employeProjets; } else { var employesProjets = contexte.EmployeProjets.OrderBy(e => e.employee_id).ToList(); grilleDonneesTables.DataSource = employesProjets; } break; case "Projets": grilleDonneesTables.Columns.Clear(); indexMax = contexte.Projets.Count(); CorrectionIndexesEtGestionPopup(); // Si il y a plus de 10000 données, on les affiche par page de 10000 dans grilleDonneesTable if (indexMax >= 10000) { var projets = contexte.Projets.OrderBy(e => e.project_id).Skip(indexMinCourant).Take(nombreAffichages).ToList(); grilleDonneesTables.DataSource = projets; } else { var projets = contexte.Projets.OrderBy(e => e.project_id).ToList(); grilleDonneesTables.DataSource = projets; } break; default: break; } } } private void BoutonValidationChangementsTable_Click(object sender, EventArgs e) { if (modificationsEnAttente.Count == 0) { MessageBox.Show("Aucune modification n'a été apportée à date.", "Aucune modification", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } SauvegarderModifications(); MessageBox.Show("Modifications sauvegardées.", "Succès", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void BoutonAjoutEnregistrement_Click(object sender, EventArgs e) { if (boiteListeAffichageTables.SelectedItem == null) { MessageBox.Show("Veuillez sélectionner une table avant d'ajouter un enregistrement.", "Aucune table sélectionnée", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string tableName = boiteListeAffichageTables.SelectedItem.ToString(); using (var formAjout = new FormAjouterModifierEnregistrement(tableName)) { if (formAjout.ShowDialog() == DialogResult.OK) { // Récupérer les modifications en attente de FormAjouterEnregistrement et ajouter à la liste locale modificationsEnAttente.AddRange(formAjout.modificationsEnAttente); // Rafraîchir les données après l'ajout AffichageDonnees(); } } } private bool VerifierModificationsEnAttente() { if (modificationsEnAttente.Any()) { var resultat = MessageBox.Show("Vous avez des modifications non sauvegardées. Voulez-vous les sauvegarder ?", "Modifications non sauvegardées", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (resultat == DialogResult.Yes) { SauvegarderModifications(); return true; } else if (resultat == DialogResult.No) { // On vide la liste des changements modificationsEnAttente.Clear(); return false; } // Si l'utilisateur clique sur "No", continuer sans sauvegarder } return true; } private void SauvegarderModifications() { using (var contexte = new AppDbContext()) { foreach (var (modification, action) in modificationsEnAttente) { if (action == "MAJ") // S'il s'agit d'une mise à jour { // Vérifiez le type et procédez selon le type d'objet if (modification is CDepartement departement) { var departementExistant = contexte.Departements.Find(departement.department_id); if (departementExistant != null) { departementExistant.department_name = departement.department_name; // Vous pouvez également mettre un messageBox ici si nécessaire } } else if (modification is CEmploye employe) { var employeExistant = contexte.Employes.Find(employe.employee_id); if (employeExistant != null) { employeExistant.first_name = employe.first_name; employeExistant.last_name = employe.last_name; employeExistant.hire_date = employe.hire_date; employeExistant.department_id = employe.department_id; employeExistant.salary = employe.salary; } } else if (modification is CEmployeProjet employeProjet) { var employeProjetExistant = contexte.EmployeProjets .FirstOrDefault(ep => ep.employee_id == employeProjet.employee_id && ep.project_id == employeProjet.project_id); if (employeProjetExistant != null) { employeProjetExistant.role = employeProjet.role; } } else if (modification is CProjet projet) { var projetExistant = contexte.Projets.Find(projet.project_id); if (projetExistant != null) { projetExistant.project_name = projet.project_name; projetExistant.start_date = projet.start_date; projetExistant.end_date = projet.end_date; } } } else // S'il s'agit d'un ajout { // Ajoutez l'objet à la base de données if (modification is CDepartement nouveauDepartement) { contexte.Departements.Add(nouveauDepartement); } else if (modification is CEmploye nouvelEmploye) { contexte.Employes.Add(nouvelEmploye); } else if (modification is CEmployeProjet nouvelEmployeProjet) { contexte.EmployeProjets.Add(nouvelEmployeProjet); } else if (modification is CProjet nouveauProjet) { contexte.Projets.Add(nouveauProjet); } } } // Sauvegarder les modifications effectuées contexte.SaveChanges(); modificationsEnAttente.Clear(); // Vider la liste après sauvegarde } } private void VerificationSiChangements() { if (!VerifierModificationsEnAttente()) { // Si l'utilisateur choisit d'annuler le changement de table, remettre la sélection précédente boiteListeAffichageTables.SelectedIndexChanged -= boiteListeAffichageTables_SelectedIndexChanged; boiteListeAffichageTables.SelectedItem = tablePrecedenteSelectionnee; // Prenez soin de garder track de l'ancien index boiteListeAffichageTables.SelectedIndexChanged += boiteListeAffichageTables_SelectedIndexChanged; return; } } private void boutonModificationEnregistrementSelection_Click(object sender, EventArgs e) { if (grilleDonneesTables.SelectedRows.Count == 0) { MessageBox.Show("Veuillez sélectionner un enregistrement à modifier.", "Aucune sélection", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var selectedRow = grilleDonneesTables.SelectedRows[0]; int selectedId = (int)selectedRow.Cells[0].Value; // Assurez-vous que c'est bien l'ID // Accéder à la base de données pour récupérer l'enregistrement using (var contexte = new AppDbContext()) { object recordToEdit = null; // Initialiser le record string tableName = boiteListeAffichageTables.SelectedItem.ToString(); switch (tableName) { case "Employes": recordToEdit = contexte.Employes.Find(selectedId); break; case "Departements": recordToEdit = contexte.Departements.Find(selectedId); break; case "EmployesProjets": // Récupérer les deux clés int employeeId = (int)selectedRow.Cells["employee_id"].Value; // Assurez-vous que la clé est correcte int projectId = (int)selectedRow.Cells["project_id"].Value; // Assurez-vous que la clé est correcte recordToEdit = contexte.EmployeProjets .FirstOrDefault(ep => ep.employee_id == employeeId && ep.project_id == projectId); break; case "Projets": recordToEdit = contexte.Projets.Find(selectedId); break; default: break; } if (recordToEdit != null) { using (var formModification = new FormAjouterModifierEnregistrement(tableName, recordToEdit)) { // Lorsque le formulaire de modifications est validé if (formModification.ShowDialog() == DialogResult.OK) { // Mettez à jour l'objet de modification si des valeurs ont été changées modificationsEnAttente.Remove(modificationsEnAttente.FirstOrDefault(m => m.Item1.Equals(recordToEdit))); // Si nécessaire, retirez l'ancien objet modificationsEnAttente.Add(formModification.modificationsEnAttente.FirstOrDefault()); // Ajoutez l'enregistrement modifié à la liste des modifications AffichageDonnees(); // Réafficher les données pour inclure les modifications } } } else { MessageBox.Show("Enregistrement non trouvé dans la base de données.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void boutonSuppressionEnregistrementSelection_Click(object sender, EventArgs e) { } } - Assistant
- User
Donne moi Sauvegarder Modifications en entier. Aussi, j'aurais besoin que la confirmation des suppression soit dans la même méthode et donc dans la même bouton que les modifications et ajouts
- Assistant
- User
J'ai déjà cette fonction : private void BoutonValidationChangementsTable_Click(object sender, EventArgs e) { if (modificationsEnAttente.Count == 0) { MessageBox.Show("Aucune modification n'a été apportée à date.", "Aucune modification", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } SauvegarderModifications(); MessageBox.Show("Modifications sauvegardées.", "Succès", MessageBoxButtons.OK, MessageBoxIcon.Information); }
- Assistant
- User
- Assistant