【问题标题】:Updating DataGrid after changing DataTable row value更改 DataTable 行值后更新 DataGrid
【发布时间】:2018-11-29 22:13:29
【问题描述】:

我有一个 DataGrid(名为 m_grid)设置,以便它显示 DataTable 的行:

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

我在后面的代码中填充网格是这样的:

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

我有一个上下文菜单,点击事件附加了以下方法:

 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"];
 }

单击运行后,数据库更新,行中的值发生了变化,但DataGrid保持不变。我尝试使用

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

但这没有任何效果。我是否在这里遗漏了什么,或者我是否需要更改将数据绑定到网格的方式。谢谢。

【问题讨论】:

    标签: c# wpf data-binding datatable wpfdatagrid


    【解决方案1】:

    我不认为 DataRow 实现通知。而不是使用 Rows 集合作为 ItemsSource (m_grid.ItemsSource = l_table.Rows;) 使用 DefaultView:

     m_grid.ItemsSource = l_table.DefaultView;
    

    它还会在 DataGrid 中正确地自动生成列。并且DataView支持排序和过滤。

    但请注意,在进行此类更改后,DataGrid 将包含 DataRowView 类型的项目(具有 Row 属性)。使用 SelectedItem 的代码也应该修改

    【讨论】:

    • 谢谢,我试过了,但是在对列进行排序时遇到了崩溃问题,因为我是如何进行绑定的(这适用于 DataRow,但不适用于 DataRowView)。
    猜你喜欢
    • 2011-04-07
    • 2015-12-02
    • 2014-08-17
    • 2014-01-23
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多