Search code examples
c#wpfdata-bindingdatatablewpfdatagrid

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 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:

 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. 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.


Solution

  • I don't think DataRow implements notifications. Instead of using Rows collection as ItemsSource (m_grid.ItemsSource = l_table.Rows;) use DefaultView:

     m_grid.ItemsSource = l_table.DefaultView;
    

    It will also correctly auto-generate columns in DataGrid. And DataView supports sorting and filtering.

    But note, that after such change DataGrid will contain items of type DataRowView (which has Row property). Code which uses SelectedItem should be modified as well