D
D
Dant3lion2021-05-21 12:40:32
MySQL
Dant3lion, 2021-05-21 12:40:32

WPF binding (referencing) DB values ​​to ComboBox?

Hello, I am currently learning how to work with wpf, and the question arose of how to bind values ​​from a database table to a ComboBox, or more precisely, how to return values ​​from a database in a ComboBox. The point is that the values ​​​​from the Education table appear as a list in the ComboBox, and then send the selected option to the value of the InformationPatient table through SelectionChanged.
An example of the WPF window itself
60a77d25490f5970386611.png
Here is the database added to the WPF
60a77ff27d07f868219552.png
This is the XAML code of the given WPF window

<Grid>
        <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="50" Margin="72,75,0,0" VerticalAlignment="Top" Width="637">
            <StackPanel Orientation="Horizontal" Margin="0,0,381,-1">
                <Label Content="Фамилия и инициалы" Width="150" Height="25"/>
                <TextBox TextWrapping="Wrap" Text="" Width="103" Height="25" BorderThickness="2" Margin="0,12" Background="#FFE6E691"/>
            </StackPanel>
        </Border>
        <Label x:Name="LbMainName" Content="Система психологического тестирования по форме pav-1" Margin="165,10,165,0" VerticalAlignment="Top" Height="32" FontSize="16" FontWeight="Bold"/>
        <TabControl HorizontalAlignment="Left" Height="424" Margin="10,148,0,0" VerticalAlignment="Top" Width="772">
            <TabItem Header="Сведения">
                <Grid Background="#FFE5E5E5">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="85*"/>
                        <ColumnDefinition Width="681*"/>
                    </Grid.ColumnDefinitions>
                    <Label x:Name="Education" Content="Образование" HorizontalAlignment="Left" Margin="21,10,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2"/>
                    <Label x:Name="FamilyState" Content="Семейное положение" HorizontalAlignment="Left" Margin="21,41,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2"/>
                    <Label x:Name="FamilyData" Content="Состав семьи" HorizontalAlignment="Left" Margin="21,72,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2"/>
                    <Label x:Name="PoliceData" Content="Наличие приводов в полицию" HorizontalAlignment="Left" Margin="21,103,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2"/>
                    <Label x:Name="DeathData" Content="Наличие суицидов в семье" HorizontalAlignment="Left" Margin="21,134,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2"/>
                    <CheckBox x:Name="DrugButt" Content="Отношение к наркотикам" HorizontalAlignment="Left" Margin="21,174,0,0" VerticalAlignment="Top" Checked="DrugButt_Checked" Grid.ColumnSpan="2" Unchecked="DrugButt_Unchecked"/>
                    <CheckBox x:Name="PrisonData" Content="Наличие судимостей у родственников" HorizontalAlignment="Left" Margin="21,205,0,0" VerticalAlignment="Top" Checked="PrisonData_Checked" Grid.ColumnSpan="2" Unchecked="PrisonData_Unchecked"/>
                    <CheckBox x:Name="ProbData" Content="Выраженные дефекты" HorizontalAlignment="Left" Margin="21,236,0,0" VerticalAlignment="Top" Checked="ProbData_Checked" Grid.ColumnSpan="2" Unchecked="ProbData_Unchecked"/>
                    <CheckBox x:Name="AddData" Content="Дополнительные данные" HorizontalAlignment="Left" Margin="21,267,0,0" VerticalAlignment="Top" Checked="AddData_Checked" Grid.ColumnSpan="2" Unchecked="AddData_Unchecked"/>
                    <TextBox x:Name="AddDataEnter" HorizontalAlignment="Left" Height="86" Margin="21,300,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="735" IsEnabled="False" Grid.ColumnSpan="2"/>
                    <ComboBox x:Name="DrugCombo" HorizontalAlignment="Left" Margin="197,167,0,0" VerticalAlignment="Top" Width="237" IsEnabled="False" Grid.Column="1"/>
                    <ComboBox x:Name="PrisonCombo" HorizontalAlignment="Left" Margin="197,198,0,0" VerticalAlignment="Top" Width="237" IsEnabled="False" Grid.Column="1"/>
                    <ComboBox x:Name="ProbCombo" HorizontalAlignment="Left" Margin="197,229,0,0" VerticalAlignment="Top" Width="237" IsEnabled="False" Grid.Column="1"/>
                    <ComboBox x:Name="EduCombo"   Grid.Column="1" HorizontalAlignment="Left" Margin="197,14,0,0" VerticalAlignment="Top" Width="237" SelectionChanged="EduCombo_SelectionChanged"/>
                    <ComboBox Grid.Column="1" HorizontalAlignment="Left" Margin="197,45,0,0" VerticalAlignment="Top" Width="237"/>
                    <ComboBox Grid.Column="1" HorizontalAlignment="Left" Margin="197,76,0,0" VerticalAlignment="Top" Width="237"/>
                    <ComboBox Grid.Column="1" HorizontalAlignment="Left" Margin="197,107,0,0" VerticalAlignment="Top" Width="237"/>
                    <ComboBox Grid.Column="1" HorizontalAlignment="Left" Margin="197,134,0,0" VerticalAlignment="Top" Width="237"/>
                </Grid>
            </TabItem>

Here is the C# 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.Shapes;

namespace project
{
    /// <summary>
    /// Логика взаимодействия для Test.xaml
    /// </summary>
    public partial class Test : Window
    {
        MasterMindEntities DB = new MasterMindEntities();
        public Test()
        {
            InitializeComponent();
            EduCombo.ItemsSource = DB.Educations.ToList();
        }

        private void SaveButt_Click(object sender, RoutedEventArgs e)
        {
            MainForm f = new MainForm();
            f.Show();
            Close();
        }

        private void ButtExit_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Вы действительно хотите выйти?", "Уведомление", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
                Application.Current.Shutdown();
        }

        private void NewTestButt_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Вы действительно хотите ввести данные нового пациента?", "Уведомление", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                Test f = new Test();
                f.Show();
                Close();
            }
        }

        private void DrugButt_Checked(object sender, RoutedEventArgs e)
        {
            DrugCombo.IsEnabled = true;
        }

        private void PrisonData_Checked(object sender, RoutedEventArgs e)
        {
            PrisonCombo.IsEnabled = true;
        }

        private void ProbData_Checked(object sender, RoutedEventArgs e)
        {
            ProbCombo.IsEnabled = true;
        }

        private void AddData_Checked(object sender, RoutedEventArgs e)
        {
            AddDataEnter.IsEnabled = true;
        }

        private void DrugButt_Unchecked(object sender, RoutedEventArgs e)
        {
            DrugCombo.IsEnabled = false;
        }

        private void PrisonData_Unchecked(object sender, RoutedEventArgs e)
        {
            PrisonCombo.IsEnabled = false;
        }

        private void ProbData_Unchecked(object sender, RoutedEventArgs e)
        {
            ProbCombo.IsEnabled = false;
        }

        private void AddData_Unchecked(object sender, RoutedEventArgs e)
        {
            AddDataEnter.IsEnabled = false;
        }

        private void EduCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int d = (EduCombo.SelectedItem as Education).ID_edu;

        }
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dant3lion, 2021-05-21
@Dant3lion

The whole problem is that when used
EduCombo.ItemsSource = DB.Educations.ToList();
in the application itself, this appears
60a788c11e64f361839389.png

C
cicatrix, 2021-05-21
@cicatrix

What doesn't work?
WPF is ideologically created for the MVVM pattern. According to it, your view (window) should have a model (viewModel), which contains a collection of elements to which you can bind a ComboBox.
Yes, it is better to wrap the list in an ObservableCollection, and not in a List, or you need to manually notify the view about changing the contents of the list.

V
Vladimir Korotenko, 2021-05-21
@firedragon

in Education, override the tostring method.
However, there the bindings can be corrected for specific fields of the entity

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question