EF Core - VS2022 How to obtain DataGrid Column Value and insert it in TextBox

Dmtr_Grms 331 Reputation points
2022-05-28T15:26:34.58+00:00

Hi,
I'm using Visual Studio 2022, WPF, EF Core and C#.
I have a DataGrid that is working fine.
I select a line and I would like to put the columns of the selected line in a Grid on the same page each column value have to be put in a TextBox.
I have tried several codes found on the Web but none of these is working for me.
// 2dn attempt provide row but no access to defined column
DataGrid dataGrid = (DataGrid)sender;
var selected_row = dataGrid.SelectedItem;
TxBxUserCode1.Text = selected_row.ToString();

206403-immagine-2022-05-28-172042.jpg

Most of the cases the selected_row is null. In the above example I have page.DbModel.Entity only.
Could someone send me some usefull links or example?
Thanks

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,667 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2022-05-30T07:04:53.35+00:00

    Hi Dimitri,
    try following demo. For details I use Grid with DataContext binded to SelectedItem of DataGrid.

    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:WpfApp022"  
            mc:Ignorable="d"  
            Title="DimitriGarmaise-5522_20220530" Height="300" Width="400">  
      <Window.DataContext>  
        <local:ViewModel/>  
      </Window.DataContext>  
        <Grid>  
        <Grid.ColumnDefinitions>  
          <ColumnDefinition/>  
          <ColumnDefinition/>  
        </Grid.ColumnDefinitions>  
        <Grid DataContext="{Binding ElementName=dg, Path=SelectedItem}">  
          <Grid.RowDefinitions>  
            <RowDefinition Height="Auto"/>  
            <RowDefinition Height="Auto"/>  
            <RowDefinition/>  
          </Grid.RowDefinitions>  
          <Grid.ColumnDefinitions>  
            <ColumnDefinition/>  
            <ColumnDefinition/>  
          </Grid.ColumnDefinitions>  
          <Label Grid.Row="0" Grid.Column="0" Content="Codic" HorizontalAlignment="Right" Margin="5"/>  
          <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Codic}" Margin="5"/>  
          <Label Grid.Row="1" Grid.Column="0" Content="Nome" HorizontalAlignment="Right" Margin="5"/>  
          <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Nome}" Margin="5"/>  
        </Grid>  
        <DataGrid x:Name="dg" Grid.Column="1" ItemsSource="{Binding View}"/>  
      </Grid>  
    </Window>  
    
    using System.Collections.Generic;  
    using System.ComponentModel;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
      
    namespace WpfApp022  
    {  
      public class ViewModel  
      {  
        // Load Data  
        public ViewModel() { for (int i = 1; i < 100; i++) View.Add(new Data() { Codic = i, Nome = $"Nome {i}" }); }  
        public List<Data> View { get; set; } = new List<Data>();  
      }  
    }  
    

    Result:

    206593-x.gif

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Hui Liu-MSFT 38,026 Reputation points Microsoft Vendor
    2022-05-30T08:12:39.543+00:00

    Reference documentation:Getting Started with WPF

    Add the NuGet Packages:

    • Microsoft.EntityFrameworkCore.Sqlite
    • Microsoft.Extensions.DependencyInjection

    App.xaml:

        <Application x : Class="WpfApp1.App"  
                    ...  
                     Startup="OnStartup" >  
            <Application.Resources>  
    
            </Application.Resources>  
        </Application>  
    

    App.xaml.cs:

    using Microsoft.EntityFrameworkCore;  
    using Microsoft.Extensions.DependencyInjection;  
    using System.Windows;  
    
    namespace WpfApp1  
    {  
      public partial class App : Application  
      {  
        private readonly ServiceProvider serviceProvider;  
        public App()  
        {  
          ServiceCollection services = new ServiceCollection();  
          services.AddDbContext<ProductDbContext>(options =>  
          {  
            options.UseSqlite("Data Source = Product.db");  
          });  
          services.AddSingleton<MainWindow>();  
          serviceProvider = services.BuildServiceProvider();  
        }  
        private void OnStartup(object s, StartupEventArgs e)  
        {  
          var mainWindow = serviceProvider.GetService<MainWindow>();  
          mainWindow.Show();  
        }  
      }  
    }  
    

    MainWindow.xaml:

    <Grid >  
            <Grid.RowDefinitions>  
                <RowDefinition Height="45"/>  
                <RowDefinition/>  
                <RowDefinition/>  
            </Grid.RowDefinitions>  
            <Label FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5"  
                   Grid.Row="0" Content="CRUD Application using EntityFrameworkCore and SQLite"/>   
            <DataGrid x:Name="ProductDG" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True"    
                     SelectedItem="{Binding SelectedProduct}"  
                      Grid.Row="1" ColumnWidth="*" Margin="5" IsSynchronizedWithCurrentItem="True" >  
                <DataGrid.Columns>  
                    <DataGridTextColumn Header="Product Id" Binding="{Binding  Id}"/>  
                    <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>  
                    <DataGridTextColumn Header="Description" Binding="{Binding Description}"/>  
                    <DataGridTextColumn Header="Price" Binding="{Binding Price}"/>  
                    <DataGridTextColumn Header="Unit" Binding="{Binding Unit}"/>  
                    <DataGridTemplateColumn Header="Delete Product">  
                        <DataGridTemplateColumn.CellTemplate>  
                            <DataTemplate>  
                                <Button Content="Delete" Click="DeleteProduct"/>  
                            </DataTemplate>  
                        </DataGridTemplateColumn.CellTemplate>  
                    </DataGridTemplateColumn>  
                </DataGrid.Columns>  
            </DataGrid>  
    
            <Grid Grid.Row="3">  
                <Grid.ColumnDefinitions>  
                    <ColumnDefinition/>  
                    <ColumnDefinition/>  
                </Grid.ColumnDefinitions>  
                <Border Grid.Column="0" Margin="5" BorderThickness="1" BorderBrush="Black">  
                    <StackPanel  Margin="5">  
                        <Label Content="Add new product" FontWeight="Bold"  
                           HorizontalAlignment="Center"   
                           VerticalAlignment="Center" Margin="5"/>  
                        <Grid Name="NewProductGrid">  
                            <Grid.RowDefinitions>  
                                <RowDefinition/>  
                                <RowDefinition/>  
                                <RowDefinition/>  
                                <RowDefinition/>  
                                <RowDefinition/>  
                            </Grid.RowDefinitions>  
                            <Grid.ColumnDefinitions>  
                                <ColumnDefinition/>  
                                <ColumnDefinition/>  
                            </Grid.ColumnDefinitions>  
                            <Label Grid.Row="0" Grid.Column="0" Content="Product Name"/>  
                            <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>  
                            <Label Grid.Row="1" Grid.Column="0" Content="Description"/>  
                            <TextBox Grid.Row="1" Grid.Column="2" Text="{Binding Description}"/>  
                            <Label Grid.Row="2" Grid.Column="0" Content="Price"/>  
                            <TextBox Grid.Row="2" Grid.Column="3" Text="{Binding Price}"/>  
                            <Label Grid.Row="3" Grid.Column="0" Content="Unit"/>  
                            <TextBox Grid.Row="3" Grid.Column="4" Text="{Binding Unit}"/>  
                            <Button Grid.Row="4" Grid.ColumnSpan="2" Width="150" Content="Add" Margin="5" Click="AddItem"  
                                HorizontalAlignment="Center" VerticalAlignment="Center"/>  
                        </Grid>  
                    </StackPanel>  
                </Border>  
                <Border Grid.Column="1" Margin="5" BorderThickness="1" BorderBrush="Black">  
                    <StackPanel Margin="5">  
                        <Label Content="Edit product" FontWeight="Bold"  
                           HorizontalAlignment="Center"   
                           VerticalAlignment="Center" Margin="5"/>  
                        <Grid Name="UpdateProductGrid">  
                            <Grid.RowDefinitions>  
                                <RowDefinition/>  
                                <RowDefinition/>  
                                <RowDefinition/>  
                                <RowDefinition/>  
                                <RowDefinition/>  
                            </Grid.RowDefinitions>  
                            <Grid.ColumnDefinitions>  
                                <ColumnDefinition/>  
                                <ColumnDefinition/>  
                            </Grid.ColumnDefinitions>  
                            <Label Grid.Row="0" Grid.Column="0" Content="Product Name"/>  
                            <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding ElementName=ProductDG,Path=SelectedItem.Name}"/>  
                            <Label Grid.Row="1" Grid.Column="0" Content="Description"/>  
                            <TextBox Grid.Row="1" Grid.Column="2" Text="{Binding ElementName=ProductDG,Path=SelectedItem.Description}"/>  
                            <Label Grid.Row="2" Grid.Column="0" Content="Price"/>  
                            <TextBox Grid.Row="2" Grid.Column="3" Text="{Binding ElementName=ProductDG,Path=SelectedItem.Price}"/>  
                            <Label Grid.Row="3" Grid.Column="0" Content="Unit"/>  
                            <TextBox Grid.Row="3" Grid.Column="4" Text="{Binding ElementName=ProductDG,Path=SelectedItem.Unit}"/>  
                            <Button Grid.Row="4" Grid.ColumnSpan="2" Width="150" Click="UpdateItem"  
                                    Content="Save" Margin="5"  
                                HorizontalAlignment="Center" VerticalAlignment="Center"/>  
                        </Grid>  
                    </StackPanel>  
                </Border>  
            </Grid>  
        </Grid>  
    

    MainWindow.xaml.cs:

    using Microsoft.EntityFrameworkCore;  
    using System.ComponentModel;  
    using System.Linq;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
    
    namespace WpfApp1  
    {  
      public partial class MainWindow : Window  
      {  
        ProductDbContext context;  
        Product NewProduct = new Product();  
        Product selectedProduct = new Product();  
    
        public MainWindow(ProductDbContext context)  
        {  
          this.context = context;  
          InitializeComponent();  
          GetProducts();  
          NewProductGrid.DataContext = NewProduct;  
        }  
        private void GetProducts()  
        {  
          ProductDG.ItemsSource = context.Products.ToList();  
        }  
        private void AddItem(object s, RoutedEventArgs e)  
        {  
          context.Products.Add(NewProduct);  
          context.SaveChanges();  
          GetProducts();  
          NewProduct = new Product();  
          NewProductGrid.DataContext = NewProduct;  
        }  
        private void UpdateItem(object s, RoutedEventArgs e)  
        {  
          context.SaveChanges();  
          GetProducts();  
        }  
        private void DeleteProduct(object s, RoutedEventArgs e)  
        {  
          var productToDelete = (s as FrameworkElement).DataContext as Product;  
          context.Products.Remove(productToDelete);  
          context.SaveChanges();  
          GetProducts();  
        }  
        private void SelectProductToEdit(object s, RoutedEventArgs e)  
        {  
          selectedProduct = (s as FrameworkElement).DataContext as Product;  
          UpdateProductGrid.DataContext = selectedProduct;  
        }  
      }  
      public class Product  
      {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public string Description { get; set; }  
        public double Price { get; set; }  
        public int Unit { get; set; }  
      }  
      public class ProductDbContext : DbContext, INotifyPropertyChanged  
      {  
        public ProductDbContext(DbContextOptions<ProductDbContext> options) : base(options)  
        {  
          Database.EnsureCreated();  
        }  
        public DbSet<Product> Products { get; set; }  
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)  
        {  
          modelBuilder.Entity<Product>().HasData(GetProducts());  
          base.OnModelCreating(modelBuilder);  
        }  
        private Product selectedProduct;  
        public Product SelectedProduct { get { return selectedProduct;}set{ selectedProduct=value; OnPropertyChanged("SelectedProduct");} }  
        public event PropertyChangedEventHandler PropertyChanged;  
        internal void OnPropertyChanged([CallerMemberName] string propName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));  
    
        private Product[] GetProducts()  
        {  
          return new Product[]  
          {  
                new Product { Id = 1, Name = "TShirt", Description = "Blue Color", Price = 2.99, Unit =1},  
                new Product { Id = 2, Name = "Shirt", Description = "Formal Shirt", Price = 12.99, Unit =1},  
                new Product { Id = 3, Name = "Socks", Description = "Wollen", Price = 5.00, Unit =2},  
                new Product { Id = 4, Name = "Tshirt", Description = "Red", Price = 2.99, Unit =3},  
          };  
        }  
    
      }  
    }  
    

    The result:
    206624-33.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html

    1 person found this answer helpful.
    0 comments No comments