KyloRen KyloRen - 4 months ago 77
SQL Question

Refresh WPF Datagrid not bound to observable collection?

I am using LINQ to SQL with a Datagrid and binding the data to the auto generated fields. The data updates fine when when submitting changes via LINQ.
The problem I am having is I cannot seem to refresh the updated data after I run a SQL statement on the database directly. The Databases data is updated correctly and closing down and re-starting the application the data is updated correctly.

I have tried,

MyTable.Items.Refresh();


And

private DatabaseDataContext sql = new DatabaseDataContext(
Properties.Settings.Default.StaffConnectionString);

sql.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues);


The XAML used to bind the data to a Datagrid column,
Info_Data
is the auto generated field from the Database table.

<DataGridTemplateColumn Header="Info" Width="*" SortMemberPath="Words">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontWeight="Light" Text="{Binding Path=Info_Data, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>


By all accounts it seems that I need to create an observable collection and bind the data to that and update the collection to refresh the data-grid table.
Is there any way around this?

Answer

OK, I have found out what I was doing so that the DataGrid was not updating.

I was not disposing of the DataContext after each use. To keep with the SQL to LINQ, Refreshing of the data was achieved by creating a new DataContext for each time I was updating the DataBase.

The below code automatically disposes of the DataContext when finished and then when making the new DataContext the updated data shows in the DataGrid

using (DatabaseDataContext sql = new DatabaseDataContext(ConnectionString)) 
   {
       //Your code
   }