I’m trying to figure out how to bind a datagrid’s itemsource to a List. In particular, I am using LINQ to SQL that pulls the data off a table, and converts it to a List:
var tempTable = (from p in dc.LiveData
select new Custom_GridResult
{ x = p.x,
y = p.y,
z = p.z
}).ToList();
dataGrid.ItemsSource = tempTable.ToList();
public class CustomETO_GridResult
{
public CustomETO_GridResult()
{ }
double x { get; set; }
public double y{ get; set; }
public double z{ get; set; }
}
My plan is to re-pull the data every few minutes (as it is constantly updating) and I’d like my DataGrid to automatically reflect the changes. Is is easier for me to just constantly re-set the ItemsSource, or is there another way?
Thanks a lot
EDIT: I should have added that the database has a constant number of rows (they are predefined). What is constantly updating are the values in the database. For example, pretend that its a database of Airplanes, and the column values are constantly updated with GPS coordinates of where the plane is flying.
For the DataGrid to receive the updates from your source collection it will need to implement INotifyCollectionChanged. Luckily, ObservableCollection already does that. Have your database query populate an ObservableCollection and bind your DataGrid to the ObservableCollection.
Update:
An even better answer is to use the MVVM pattern. You would create a Model class that interfaces with the database and a ViewModel class that prepares the data for presentation but putting it into an ObservableCollection (for example). Then your View would bind to the ViewModel where you would set the DataGrid’s ItemsSource to the ObservableCollection. See this post for getting started with MVVM.
Update #2:
Create an instance of ViewModel in your control’s constructor and assign it to the control’s DataContext. Your DataGrid will bind to the Results property on the ViewModel. When the contents of the ObservableCollection change the contents of the DataGrid will be automatically updated. N
Code:
XAML: