Refresh WPF Datagrid not bound to observable collection?

点点圈 提交于 2020-01-05 04:09:06

问题


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?


回答1:


You could try SqlDataAdapter and DataTable to load info from database and bind to DataGrid:

var da = new SqlDataAdapter("SELECT * FROM " + view, conn);
var dt = new DataTable();
da.Fill(dt);
var dg = new DataGrid();// Your DataGrid
dg.ItemsSource = dt.DefaultView;

On update:

dt.Rows.Clear();
da.Fill(dt);
dt.AcceptChanges();


来源:https://stackoverflow.com/questions/38223793/refresh-wpf-datagrid-not-bound-to-observable-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!