Robert Harvey
Robert Harvey

Reputation: 180788

How do I distinguish the new rows in a datagrid from the existing ones?

I have an ordinary DataGrid in a WPF application that is backed by an ObservableCollection<T>. I am updating a SQL Server database using Dapper.

Dapper can update existing records without problems, but to get new records into the database I have to insert them. So I have to make two Dapper calls; one to update any changes made by the user to existing records, and one to add any new records.

How do I distinguish the records in the ObservableCollection that have been added by the user from the original ones that were loaded from the database when the form was loaded?

Upvotes: 2

Views: 235

Answers (2)

Rekshino
Rekshino

Reputation: 7325

You can spare event listening. Just make default initialization for new records with another value as for existing.

public class Document
{
    static bool IsNewInitializer { get; set; } = false;

    int Id { get; set; }
    string DocumentName { get; set; }
    bool IsNew { get; set; } = IsNewInitializer; // This field is not in the database
}

public void LoadDocuments()
{
    Document.IsNewInitializer = false;

    var documents = myIdbConnection.GetAll<Document>();
    Documents = new ObservableCollection<Document>(documents);

    Document.IsNewInitializer = true;
}
public void Save()
{
    myIdbConnection.Update(Documents.Where(x => !x.IsNew));
    myIdbConnection.Insert(Documents.Where(x => x.IsNew));
    foreach (var d in Documents.Where(x => x.IsNew))
    {
        d.IsNew = false;
    }
}

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180788

Assuming a DTO of

public class Document
{
    int Id { get; set; }
    string DocumentName { get; set; }
    bool IsNew { get; set; } // This field is not in the database
}

I can use this event handler:

private void Documents_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    foreach(Document item in e.NewItems)
    {
        item.IsNew = true;
    }
}

to mark any new records the user has added to the datagrid. I hook this handler after loading the original records from the database:

public void LoadDocuments()
{
    var documents = myIdbConnection.GetAll<Document>();         
    Documents = new ObservableCollection<Document>(documents);
    Documents.CollectionChanged += Documents_CollectionChanged;
}

And then:

public void Save()
{
    myIdbConnection.Update(Documents.Where(x=>!x.IsNew));
    myIdbConnection.Insert(Documents.Where(x=>x.IsNew));
}

Upvotes: 1

Related Questions