If I click the "No" button at MessageBoxButton.YesNo
the data that is being typed is still inserting in the database. How should I fix this?
This is my code:
string insertQuery = "INSERT INTO db_personal(per_image,per_Fname,per_Mname,per_Lname)VALUES(@per_image,@per_Fname,@per_Mname,@per_Lname)";
connection.Open();
MySqlCommand cmd = new MySqlCommand(insertQuery, connection);
cmd.Parameters.AddWithValue("@per_image", newPicture.Image);
cmd.Parameters.AddWithValue("@per_Fname", newFirstName.Text);
cmd.Parameters.AddWithValue("@per_Mname", newMiddleName.Text);
cmd.Parameters.AddWithValue("@per_Lname", newLastName.Text);
try
{
if (cmd.ExecuteNonQuery() == 1)
{
MetroFramework.MetroMessageBox.Show(this, "New student information has been successfully saved.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MetroFramework.MetroMessageBox.Show(this, "Incomplete information. Are you sure you want to save?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
First off you run the query:
And check the result to see what message you want to show. At this point the data is either already saved to the database or not. You then ask the user if they still want to save the data to the database but do nothing with that information, you'd want to do something like:
I have never had to rollback a command to a database but I found the method SqlTransaction.Rollback, although I don't know how it works or if it is applicable.
You should think about redoing your logic so that it flows better:
So something like:
If the validation check fails but it is still compatible with the database you could also present the user with a message if they still want to continue: