Reputation: 83
I have a settingsForm and in this form the user will change different values , Add/delete things from the database and I need when the use hit cancel button all changes he made will be cancelled and return to last saved state ,how this works ?
Upvotes: 0
Views: 914
Reputation: 149
You can use BeginTransaction
then after that execute query against the database.
private static SqlTransaction transaction;
private static SqlConnection conn;
public static void BeginTransaction()
{
try
{
transaction = conn.BeginTransaction();
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
If a user clicks OK then execute CommitTransaction
:
public static void CommitTransaction()
{
try
{
transaction.Commit();
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
If a user clicks cancel then execute RollbackTransaction
:
public static void RollbackTransaction()
{
try
{
transaction.Rollback();
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
you can use BeginTransaction
on Form load event, example:
private void Form1_Load(object sender, EventArgs e)
{
conn.Open();
ClassName.BeginTransaction();
}
And then close connection depending on a click event. Use cancel button and all changes he made will be cancelled and return'd to last saved state. If ok button is clicked all changes are committed to the database.
private void cancel_Click(object sender, EventArgs e)
{
ClassName.RollbackTransaction();
conn.Close();
}
private void ok_Click(object sender, EventArgs e)
{
ClassName.CommitTransaction();
conn.Close();
}
ClassName is your class that defines the connection. Now you can execute a query based on a connection that is opened at Form_Load
. Until the user presses the OK or the Cancel button. For example you can execute delete all from table button click.
private void deleteAll_Click(object sender, EventArgs e)
{
SqlCommand cmnd = CreateCommand("TRUNCATE TABLE TABLE_1", CommandType.Text);
cmd.ExecuteNonQuery();
}
and the changes (delete all) to a database will be made or not, depending on a user clicking cancel
or ok
.
Upvotes: 0
Reputation: 77364
The easiest way is to not make changes at all until the user hits OK. Make a list of all changes that have to be done and only execute that list on OK. Simply close the form on Cancel.
Upvotes: 6