简体   繁体   English

更改DataTable行值后更新DataGrid

[英]Updating DataGrid after changing DataTable row value

I have a DataGrid (named m_grid) setup so that it displays the rows of a DataTable: 我有一个DataGrid(名为m_grid)设置,以便显示DataTable的行:

 <DataGrid name="m_grid">
      <DataGrid.Columns>
           <DataGridCheckBoxColumn Header="Locked"
                                   Binding="{Binding '[Locked]'}"/>
           ...
      </DataGrid.Columns>
 </DataGrid>

I populuate the grid in the code behind like this: 我在下面的代码中填充网格,如下所示:

 DataTable l_table = Database.GetTable("SELECT * FROM Reports")
 m_grid.ItemsSource = l_table.Rows;

I have a context menu that has the following method attached to the click event: 我有一个上下文菜单,其中将以下方法附加到click事件:

 DataRow l_row = m_grid.SelectedItem as DataRow;
 int l_id = (int)l_row["Report ID"];
 int l_result = Database.Execute("Update [Reports] SET [Locked] = not [Locked] WHERE [Report ID]=" + l_id;
 if (l_result > 0){
      l_row["Locked"] = !l_row["Locked"];
 }

After click is run, the database is updated, and the value in the row has changed, but the DataGrid remains unchanged. 单击运行后,将更新数据库,并且该行中的值已更改,但是DataGrid保持不变。 I have attempted to use 我尝试使用

m_grid.BeginEdit();
// execute code
m_grid.CommitEdit();

But that has had no effect. 但这没有效果。 Am I missing something here or do I need to change up how I am binding my data to the grid. 我是否在这里丢失了某些东西,还是需要更改将数据绑定到网格的方式。 Thanks. 谢谢。

I don't think DataRow implements notifications. 我不认为DataRow实现通知。 Instead of using Rows collection as ItemsSource ( m_grid.ItemsSource = l_table.Rows; ) use DefaultView: 不要将Rows集合用作ItemsSource( m_grid.ItemsSource = l_table.Rows; ),请使用DefaultView:

 m_grid.ItemsSource = l_table.DefaultView;

It will also correctly auto-generate columns in DataGrid. 它还将正确地自动生成DataGrid中的列。 And DataView supports sorting and filtering. 而且DataView支持排序和过滤。

But note, that after such change DataGrid will contain items of type DataRowView (which has Row property). 但是请注意,在进行此类更改之后,DataGrid将包含DataRowView类型的项(具有Row属性)。 Code which uses SelectedItem should be modified as well 使用SelectedItem的代码也应修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM