First thing you want is to start the transaction immediately after you open the connection. Also, please move the connection opening out of the try
block and wrap its creation in the using
- this is a good practice for IDisposable
implementations:
using (var conn = new SqlConnection(connectionString))
{
// your code before conn.Open()
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try
{
// your code goes here
Then leave everything as it is, and then in the end of the operation commit the transaction:
tran.Commit();
MessageBox.Show("Data Inserted");
frmload();
Also note that there is no finally
because using
is taking care of closing the connection in case of exceptions.