question

DimitriGarmaise-5522 avatar image
0 Votes"
DimitriGarmaise-5522 asked HuiLiu-MSFT answered

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

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



windows-wpfdotnet-entity-framework-core
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered PeterFleischer-3316 edited

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






x.gif (116.8 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

HuiLiu-MSFT avatar image
0 Votes"
HuiLiu-MSFT answered

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 to enable e-mail notifications if you want to receive the related email notification for this thread. 


33.gif (181.7 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.