Recuperer la valeur d'une cellule de Datagrid et la mettre dans un comboBox

Résolu/Fermé
danny243 Messages postés 74 Date d'inscription vendredi 19 mars 2021 Statut Membre Dernière intervention 16 octobre 2021 - 26 avril 2021 à 01:12
danny243 Messages postés 74 Date d'inscription vendredi 19 mars 2021 Statut Membre Dernière intervention 16 octobre 2021 - 27 avril 2021 à 07:51
Bonjour j'ai une question je veux être capable de recuperer la valeur de la colonne Id de ma datagrid pour la mettre dans un combobox j'ai essayé de faire un biding et ça n'a pas marché y a t-il une façon de le faire voila une partie de mon code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using BLL;


namespace UIL
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        int recup;
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this; 
            Film.ChargerListeEtudiant();
            dgFilm.ItemsSource = Film.films;
            cbolds.ItemsSource = Film.Lid;
        }

        private void LigneDG_dblClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void Loaded_Cbolds(object sender, RoutedEventArgs e)
        {
            
        }
    }
}






<Window x:Class="UIL.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:labTiers"
        mc:Ignorable="d"
        Title="MainWindow" Height="780" Width="875">
    <Grid Height="559" VerticalAlignment="Top">
        <DataGrid HorizontalAlignment="Left" Height="149" Margin="45,21,0,0" VerticalAlignment="Top" Width="428"
                  Name="dgFilm" 
                  AutoGenerateColumns="False" RowBackground="Khaki" 
                  AlternatingRowBackground="Lavender" MouseDoubleClick="LigneDG_dblClick"
                                                                                  >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Width="2*" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="Titre" Width="12*" Binding="{Binding Titre}"/>
               
                <DataGridTextColumn Header="Année" Width="2*" Binding="{Binding Annee}"/>
                <DataGridTextColumn Header="Pays" Width="2*" Binding="{Binding Pays}"/>
            </DataGrid.Columns>


        </DataGrid>

        <Label Content="Label" HorizontalAlignment="Left" Height="24" Margin="145,0,0,0" VerticalAlignment="Center" Width="73"/>
        <ComboBox HorizontalAlignment="Left" Margin="460,196,0,337" Width="179" x:Name="cbolds" ItemsSource="{Binding LesIds}" DisplayMemberPath="Id" Loaded="Loaded_Cbolds"/>
        <Label Content="Titre:" HorizontalAlignment="Left" Height="28" Margin="21,258,0,0" VerticalAlignment="Top" Width="48"/>
        <TextBox HorizontalAlignment="Left" Height="28" Margin="69,258,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="185"/>
        <Label Content="Pays" HorizontalAlignment="Left" Height="24" Margin="311,259,0,0" VerticalAlignment="Top" Width="72"/>
        <TextBox HorizontalAlignment="Left" Height="26" Margin="400,260,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="96"/>
        <Label Content="Année" HorizontalAlignment="Left" Height="26" Margin="550,259,0,0" VerticalAlignment="Top" Width="58"/>
        <TextBox HorizontalAlignment="Left" Height="24" Margin="630,260,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="128"/>
        <Label Content="Veuillez sélectionner un pays:" HorizontalAlignment="Left" Height="28" Margin="32,316,0,0" VerticalAlignment="Top" Width="164"/>
        <ComboBox HorizontalAlignment="Left" Height="28" Margin="216,321,0,0" VerticalAlignment="Top" Width="138"/>
        <Label Content="Veuillez sélectionner une année:" HorizontalAlignment="Left" Margin="471,318,0,0" VerticalAlignment="Top"/>
        <ComboBox HorizontalAlignment="Left" Height="24" Margin="666,318,0,0" VerticalAlignment="Top" Width="73"/>
        <Label Content="Id" HorizontalAlignment="Left" Margin="32,390,0,0" VerticalAlignment="Top"/>
        <Label Content="Titre" HorizontalAlignment="Left" Margin="124,390,0,0" VerticalAlignment="Top"/>
        <Label Content="Année" HorizontalAlignment="Left" Margin="216,390,0,0" VerticalAlignment="Top"/>
        <ListBox HorizontalAlignment="Left" Height="74" Margin="29,439,0,0" VerticalAlignment="Top" Width="227"/>
        <ListBox HorizontalAlignment="Left" Height="74" Margin="471,439,0,0" VerticalAlignment="Top" Width="287"/>
        <Label Content="Id" HorizontalAlignment="Left" Margin="471,390,0,0" VerticalAlignment="Top"/>
        <Label Content="Titre" HorizontalAlignment="Left" Margin="583,390,0,0" VerticalAlignment="Top"/>
        <Label Content="Pays" HorizontalAlignment="Left" Margin="720,390,0,0" VerticalAlignment="Top"/>
        <Label Content="Veuillez selectionner l'identifiant:" HorizontalAlignment="Left" Margin="235,196,0,0" VerticalAlignment="Top" Width="184"/>

    </Grid>
</Window>


A voir également:

5 réponses

Whismeril Messages postés 19028 Date d'inscription mardi 11 mars 2003 Statut Non membre Dernière intervention 24 avril 2024 931
26 avril 2021 à 19:48
Bonjour

la programmation c'est d'abord une logique, et qui dit logique dit cohérence.
Et là tu voies, ça manque de cohérence.

Ça commence par l'appel à
Film.ChargerListeEtudiant();
qui manifestement sert à charger une liste de films. Bon ça ne va rien changer à ton problème, mais si dès le départ les méthodes ne font pas ce que leur nom dit, on commence déjà à s'embrouiller.

Là où le manque que cohérence fait que ça merdouille c'est ce qui suit:

Cette ligne
DataContext = this;
veut dire que le xaml va chercher les sources de son binding dans ce code behind, or
  • y'a rien à binder dans ce code behind (on binde sur des propriétés et y'en a pas)
  • 2 lignes plus loin, tu fusilles tout en affectant les itemssources des 2 controles.


Et aussi, cette ligne
<ComboBox HorizontalAlignment="Left" Margin="460,196,0,337" Width="179" x:Name="cbolds" ItemsSource="{Binding LesIds}" DisplayMemberPath="Id" Loaded="Loaded_Cbolds"/>
dit que ce combobox doit aller chercher ses items dans la collection de
this
qui s'appelle LesIds
Et cette ligne
cbolds.ItemsSource = Film.Lid;
dit que ce même comboxbox doit aller chercher ses items dans une collection de Film qui s'appelle Lid


Comme tu n'as pas montré le code de Film, je fais des plans sur la comète.

Une option est de dire que le datacontext, c'est Film.

        public MainWindow()
        {
            InitializeComponent();
            Film.ChargerListeEtudiant();
            DataContext = Film;
        }


        <DataGrid HorizontalAlignment="Left" Height="149" Margin="45,21,0,0" VerticalAlignment="Top" Width="428"
                  Name="dgFilm" 
                  AutoGenerateColumns="False" RowBackground="Khaki" 
                  AlternatingRowBackground="Lavender" MouseDoubleClick="LigneDG_dblClick"
                  ItemsSource="{Binding films}"
                                                                                  >


et
<ComboBox HorizontalAlignment="Left" Margin="460,196,0,337" Width="179" x:Name="cbolds" ItemsSource="{Binding films}" DisplayMemberPath="Id" Loaded="Loaded_Cbolds"/>


Et pas besoin de Lid.
0
danny243 Messages postés 74 Date d'inscription vendredi 19 mars 2021 Statut Membre Dernière intervention 16 octobre 2021
26 avril 2021 à 20:08
Voici le code de film

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using MySql.Data.MySqlClient;
using System.ComponentModel;
using System.Collections.ObjectModel;
using DAL;


namespace BLL
{
   public class Film: INotifyPropertyChanged
    {
        public static ObservableCollection<Film> films = new ObservableCollection<Film>();
        public static ObservableCollection<Film> Lid = new ObservableCollection<Film>();

        public static void ChargerListeEtudiant()
        {
            //Appel de la fonction dans AccessDB pour la connection à la DB
            var listeFilms = new ObservableCollection<Film>();
            DataTable dt = AccessDB.ConnecterBD();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var etu = new Film
                {
                    Id = Int32.Parse(dt.Rows[i]["ID"].ToString()),
                    Titre = dt.Rows[i]["Titre"].ToString(),
                    Annee = Int32.Parse(dt.Rows[i]["Annee"].ToString()),
                    Pays = dt.Rows[i]["Pays"] as Pays,
                    
                };

                listeFilms.Add(etu);
            }

            films = listeFilms;
        }
        private List<int> lesIds;
        public List<int> LesIds
        {
            get
            {
                return lesIds;
            }

            set
            {
                if (this.lesIds != value)
                {
                    this.lesIds = value;
                    this.NotifyPropertyChanged("LesIds");
                }
            }
        }



        public static void ChargerId()
        {
            //Appel de la fonction dans AccessDB pour la connection à la DB
            var listeId = new ObservableCollection<Film>();
            DataTable dt = AccessDB.ConnecterBD();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var etu = new Film
                {
                    Id = Int32.Parse(dt.Rows[i]["ID"].ToString()),
                   

                };

                listeId.Add(etu);
            }

           Lid = listeId;
        }


        public void NotifyPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
        private int id;

        public int Id
        {
            get
            {
                return id;
            }

            set
            {
                if (this.id != value)
                {
                    this.id = value;
                    this.NotifyPropertyChanged("Id");
                }
            }
        }

        private string titre;
        public string Titre
        {
            get
            {
                return titre;
            }

            set
            {
                if (this.titre != value)
                {
                    this.titre = value;
                    this.NotifyPropertyChanged("Titre");
                }
            }
        }
        private int annee;

        public int Annee
        {
            get
            {
                return annee;
            }

            set
            {
                if (this.annee != value)
                {
                    this.annee = value;
                    this.NotifyPropertyChanged("Annee");
                }
            }
        }
        private Pays pays;
        

        public Pays Pays
        {
            get
            {
                return pays;
            }

            set
            {
                if (this.pays != value)
                {
                    this.pays = value;
                    this.NotifyPropertyChanged("Pays");
                }
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
    }
}



0
danny243 Messages postés 74 Date d'inscription vendredi 19 mars 2021 Statut Membre Dernière intervention 16 octobre 2021
26 avril 2021 à 20:10
Parce que en fait j'ai fait un premier binding pour tous les champs de ma datagrid et là je veux faire juste pour l'id et mettre cela dans le combobox
0
Whismeril Messages postés 19028 Date d'inscription mardi 11 mars 2003 Statut Non membre Dernière intervention 24 avril 2024 931
26 avril 2021 à 20:54
oui et as tu essayé ce que je t'ai proposé?
0
danny243 Messages postés 74 Date d'inscription vendredi 19 mars 2021 Statut Membre Dernière intervention 16 octobre 2021
26 avril 2021 à 21:50
Quand je fais j'ai une erreur qui dit Film est un type qui n'est pas valide dans le contexte donné
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using BLL;


namespace UIL
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        
        public MainWindow()
        {
            InitializeComponent();
           
          
            Film.ChargerListeEtudiant();
            DataContext = Film;
            // dgFilm.ItemsSource = Film.films;

        }

        private void LigneDG_dblClick(object sender, MouseButtonEventArgs e)
        {
            txt_Titre.Text = (dgFilm.SelectedItem as Film).Id.ToString();

        }

        private void Loaded_Cbolds(object sender, RoutedEventArgs e)
        {
            
        }
    }
}


0
Whismeril Messages postés 19028 Date d'inscription mardi 11 mars 2003 Statut Non membre Dernière intervention 24 avril 2024 931
26 avril 2021 à 22:34
Ha oui, ce sont des collections statique, mais film ne l'est pas.

Alors comme ça
        public MainWindow()
        {
            InitializeComponent();
           
          
            Film.ChargerListeEtudiant();
            DataContext = this;

        }

       public films {get {return Film.fimls;}}




0
danny243 Messages postés 74 Date d'inscription vendredi 19 mars 2021 Statut Membre Dernière intervention 16 octobre 2021
26 avril 2021 à 23:15
cette ligne de code est à mettre dans le mainwindow ou dans la classe film
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
Whismeril Messages postés 19028 Date d'inscription mardi 11 mars 2003 Statut Non membre Dernière intervention 24 avril 2024 931
27 avril 2021 à 07:32
Tout ce bout de code va dans la fenêtre
0
danny243 Messages postés 74 Date d'inscription vendredi 19 mars 2021 Statut Membre Dernière intervention 16 octobre 2021
27 avril 2021 à 07:51
d'accord merci
0