David Shepard
David Shepard

Reputation: 181

How to populate a datagrid from database?

I have an sql database with data, which I'd like to be shown in the DataGrid. I've read how to work with a DataGrid, but haven't found information about my case. There's a class with properties

public class OrderModel : INotifyPropertyChanged
{

    public int ID { get; set; }
    public string Street { get; set; }
    public string Building { get; set; }
    public string Flat { get; set; }
    public string Date { get; set; }
    public string Month { get; set; }
    public string Year { get; set; }
}

The entity of the database

public OrdersEntitiesNew db = new OrdersEntitiesNew();

This is how I populate the DataGrid with only Year and I'd like to populate it with everything, how to do that?

private void Info_OnLoaded(object sender, RoutedEventArgs e)
    {
        var items = new List<OrderModel>();
        Info.ItemsSource= (from s in db.OrderInfoes
            group s by s.Year
            into result
            select new { "Years" = result.Key }).ToList();
    }

I know I also can create a list of OrderModel and make it an itemsSource but in this case, how do I populate this list from the database?

There's xaml

<DataGrid Name="Info" Loaded="Info_OnLoaded" SelectionChanged="Info_SelectionChanged" 
Width="568" Canvas.Left="39" Canvas.Top="173" Height="122">
    </DataGrid>

Upvotes: 0

Views: 166

Answers (1)

Wubbler
Wubbler

Reputation: 127

Try something like this:

var model = db.OrderModel;
Info.ItemSource = model.ToList();

You might wish to read more into Linq to get all the information you want to display, hope this helps.

Upvotes: 1

Related Questions