[UWP] [EF] How to populate DataGrid with data using EF

BitSmithy 1,751 Reputation points
2020-03-12T15:56:58.717+00:00

Hello;

I dont know How to populate DataGrid with data using EF. In my app I use classes:

DataGrid myDG;

public class myDbContext : DbContext 
{
    public string connectionString;

    public DbSet<MyClass> MyTable{ get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite(connectionString);
    }
}
Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Xiaodi Yan 876 Reputation points MVP
    2020-03-12T20:26:40.933+00:00

    First, you need to query the data from your dbContext:

    using (var db = new BloggingContext())  
    {  
        var blogs = db.Blogs  
            .Where(b => b.Rating > 3)  
            .OrderBy(b => b.Url)  
            .ToList();  
    }  
    

    Then, you need to add the DataGrid control to your XAML page and set the data-binding. I'm not sure what DataGrid control you are using. I suppose you can use the DataGrid from Windows Community Toolkit.

    Install this nuget package from the NuGet Package Manger:
    Microsoft.Toolkit.UWP.UI.Controls.DataGrid

    Add the control and set the data-binding:

    <controls:DataGrid x:Name="dataGrid1"   
        Height="600" Margin="12"  
        AutoGenerateColumns="True"  
        ItemsSource="{x:Bind MyViewModel.Customers}" />    
    

    This is just code samples from Docs and you need to modify them. FYI:
    https://learn.microsoft.com/en-us/ef/core/
    https://learn.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/datagrid_basics

    0 comments No comments

0 additional answers

Sort by: Most helpful