Search code examples
c#visual-studio-2010sql-server-2008-r2sqltransaction

Sql transaction rollback from other form


I have 2 Forms: enter image description here 1.MainForm :

in which users are asked to input name, Family, then there is button named as "payment detail"(which opens Form2).

2.Form2

The user input the payment detail and click on Save button. Then this transaction insert the new row in sql table and this form will be closed (Step 2). While MainFrom is still Open I would like, on user click on Save button on MainForm (Step 3), transaction of Form2 committed, but If user close the Main form then Form2 transaction roll backed.

I would appreciate your suggestions for this scenario ?

go throw steps 1,2,3


Solution

  • I think you are looking for something like this:

    class MainForm()
    {
        private TransactionScope _scope;
        public void SaveButton_Click()
        {
            _scope.Complete();
            Close();
        }
        public MainForm()
        {
            _scope = new TransactionScope();
        }
        ~MainForm()
        {
            _scope.Dispose();
        }
    }
    

    However, I strongly advise you NOT to do this. Since you will possibly have to wait a long time for the user to complete the inputs, you will run into all kinds of problems with transaction lifetime and locked database records.

    Depending on your needs, consider picking one of the following solutions instead:

    • If the user clicks cancel in MainForm, simply delete the created Transaction again.

    • Pass the inputted values from the Transaction Form to the Main Form and only save the Transaction if the user clicks the Main Form's Save button.