Samudra Lakmal
Samudra Lakmal

Reputation: 61

How to identify only change rows in datagrid which is bind ObservableCollection in WPF MVVM

I have a data grid which is bind the Observable Collection. First i load the data from the database. If i change one row and click on save button i should only update that particular row. if i add new rows, when i click save id should insert the rows to database. i don't have doubt to update and insert to database. But problem is how to identify the row changes.

<DataGrid SelectedIndex="{Binding SelectedIntex}" IsEnabled="{Binding IsKeySet}" CanUserDeleteRows="False" CanUserAddRows="False" Name="dgwTemplateDetails" SelectionMode="Single" ItemsSource="{Binding OrderTemplateList, Mode=TwoWay}" SelectedItem="{Binding SelectedOrderTemplate}" IsReadOnly="False" AutoGenerateColumns="False" Width="auto">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Change State" Visibility="Visible" Binding="{Binding ChangeState}"/>
                        <DataGridTextColumn Header="Srl No" Visibility="Hidden" Binding="{Binding SrlNo}"/>
                        <DataGridTextColumn Header="Act Code" Width="75" Binding="{Binding ActCode}"/>
                        <DataGridTextColumn Header="Act Name" Width="275" Binding="{Binding ActName}"/>
                        <DataGridTextColumn Header="No. Of Days" Width="75" Binding="{Binding NoOfDays}"/>
                        <DataGridCheckBoxColumn Header="Is Cutting" Width="75" Binding="{Binding IsCutSelected}" />
                      </DataGrid.Columns>
                </DataGrid>

Upvotes: 0

Views: 898

Answers (2)

toadflakz
toadflakz

Reputation: 7944

Implement an IsDirty flag on your bound data objects. When you update the property values, set the IsDirty flag. In your Save Command, find all objects where the flag is set and update them and then reset the flag.

Upvotes: 1

Mike Eason
Mike Eason

Reputation: 9713

As far as I am aware, there is no way to identify this. However you can add another property in your class called HasChanged

public bool HasChanged { get; set; }

And in the setter code of any of your other properties, simply set the HasChanged property to true. For example:

private string _ActName; 
public string ActName 
{
   get
   {
      return _ActName;
   }
   set
   {
      _ActName = value;
      this.HasChanged = true;

      //INotifyPropertyChanged stuff if you are using it here.
   }
}

When you then save the changes to the database, you can simply select all of the records where the has changed property is set to true.

var hasChanged = OrderTemplateList.Where(x => x.HasChanged);

Upvotes: 1

Related Questions