question

BitSmithy-4663 avatar image
0 Votes"
BitSmithy-4663 asked RichardZhang-MSFT commented

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

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);
     }
 }
windows-uwp
· 3
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.

Hello, does the yanxiaodi's answer solve your problem?

0 Votes 0 ·

Hello, do you have any other questions?

0 Votes 0 ·

Hello, if you have any other questions, please feel free to ask

0 Votes 0 ·

1 Answer

yanxiaodi avatar image
0 Votes"
yanxiaodi answered

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://docs.microsoft.com/en-us/ef/core/
https://docs.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/datagrid_basics





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.