开发者

Recognise Unsaved Changes and Notify User

开发者 https://www.devze.com 2023-02-19 09:06 出处:网络
I have a form that is linked to a database and allows a user to insert, update and delete records. I want the user to开发者_如何学Python be notified of any unsaved changes when they click to go back t

I have a form that is linked to a database and allows a user to insert, update and delete records. I want the user to开发者_如何学Python be notified of any unsaved changes when they click to go back to the main menu, and have the option whether or not to save them.

The code I have so far is below, but it doesn't recognize the changes. It just goes straight back to the main menu.

private void btnBack_Click(object sender, EventArgs e)
    {
        frmMenu frmMainMenu = new frmMenu();

        if (dsOrders.HasChanges())
        {


            if (DialogResult.Yes == MessageBox.Show("There are changes that have not been saved and will be lost. Would you like to save them before leaving this form?", "Unsaved Changes", MessageBoxButtons.YesNo))
            {
                dsOrders.AcceptChanges();
            }
            else
            {
                frmOrders.ActiveForm.Hide();

                frmMainMenu.Show();
            }

        }
        else
        {
            frmOrders.ActiveForm.Hide();

            frmMainMenu.Show();
        }

    }


I am guessing you are using DataBinding and dsOrders is a dataset.

What you could try to do is to check if your databinding is working correctly (both-ways) by setting a breakpoint just before the menu is called.

Then, you could edit some data, and when the breakpoint is triggered, check if the changes are in the dataset. If they are not, the HasChanges method will return false, and you won't get the messagebox.

An other way to check if your data has changed to show this message would be to attach an eventhandler on the change event of all the controls on your form. In this event handler you could set a boolean like blnChanged to true and check its value instead of dsOrders.HasChanges


One way to do is use the individual controls' Changed event and set a dirty bit

for eg

    public bool Dirty { get; set; }


    private void textBox1_TextChanged(object sender, EventArgs e)
    {
          Dirty = true;
    }

and then

        if (Dirty)
        {


            if (DialogResult.Yes == MessageBox.Show("There are changes that have not been saved and will be lost. Would you like to save them before leaving this form?", "Unsaved Changes", MessageBoxButtons.YesNo))
            {
                dsOrders.AcceptChanges();
            }
            else
            {
                frmOrders.ActiveForm.Hide();

                frmMainMenu.Show();
            }

        }
0

精彩评论

暂无评论...
验证码 换一张
取 消