Why do I need to change the Binding Source Position before I can SaveChanges
Asked Answered
R

1

7

I have a small demo WinForms app. One of the Forms is my Add New Person form. I used the Details View instead of the DataGridView from my Data Sources. When I enter data and click the save button on the Navigator there are zero changes, However I put a MovePrevious and a MoveNext after my AddNew in the form Load, everything works as expected.

public partial class AddPersonForm : Form
{
    private readonly DemoContext _context;

    public AddPersonForm()
    {
        _context = new DemoContext();
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        _context.People.Load();

        personBindingSource.DataSource = _context.People.Local.ToBindingList();

        personBindingSource.AddNew();
        personBindingSource.MovePrevious();
        personBindingSource.MoveNext();

        base.OnLoad(e);
    }

    private void personBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        int changes = _context.SaveChanges();
        Debug.WriteLine("# of changes: " + changes);
    }
}

Why do I need to toggle the BindingSource Position before it will recognize changes and save?

Rodin answered 14/12, 2015 at 15:25 Comment(3)
You don't need to change position, in fact you need BindingSource.EndEdit()Intricacy
I think you can just call EndEdit(). doh, @RezaAghaei beat me by 5 secs ;)Driftage
EndEdit works. Thanks @RezaAghaei, to both of you really!Rodin
I
4

You don't need to change the position, in fact you need to call EndEdit of the BindingSource that applies pending changes to the underlying data source.

Changing the position causes the underlying currency manager calls EndCurrentEdit and this is what the EndEdit method of binding source does for you.

So this is what you usually want to do:

try
{
    this.Validate();
    bindingSource1.EndEdit();
    //Save data by dbContext.SaveChange or tableAdapter.Update
    //Set the dialog result or show a success message
}
catch (Exception ex)
{
    //Handle the exception, log it and/or show a failure message
}
Intricacy answered 14/12, 2015 at 15:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.